# PUBLIC DOMAIN - NO LICENSE, NO WARRANTY
# Copyright 2025 TimeHexOn & foxhop & russell@unturf
# https://www.permacomputer.com

# Makefile for ai.unturf.com project
# All commands used for testing, validation, and development

# All phony targets
.PHONY: help format check test validate-exports validate-all clean install dev build deploy
.PHONY: languages-list languages-build-all languages-test-all languages-clean
.PHONY: update-unsandbox-sdk bundle-extension

# Environment variables for testing language implementations
MODEL_ENDPOINT_1 ?= https://hermes.ai.unturf.com/v1
MODEL_ENDPOINT_2 ?= https://qwen.ai.unturf.com/v1
TTS_ENDPOINT_1 ?= https://speech.ai.unturf.com/v1
DOCKER_ENV_VARS := -e MODEL_ENDPOINT_1=$(MODEL_ENDPOINT_1) -e MODEL_ENDPOINT_2=$(MODEL_ENDPOINT_2) -e TTS_ENDPOINT_1=$(TTS_ENDPOINT_1)

# Default target
help:
	@echo "Available commands:"
	@echo "  make format           - Format all files with biome"
	@echo "  make check            - Check syntax and linting with biome"
	@echo "  make format-check     - Format and check in sequence"
	@echo "  make test             - Run integration tests"
	@echo "  make test-simple      - Run simple unit-style tests"
	@echo "  make test-modal       - Run custom modal tests"
	@echo "  make validate-exports - Validate import/export consistency"
	@echo "  make verify-translations - Verify translation completeness"
	@echo "  make validate-translations - Validate all translation files"
	@echo "  make validate-all     - Run all validation checks"
	@echo "  make clean            - Clean temporary files"
	@echo "  make install          - Install dependencies"
	@echo "  make dev              - Start development server"
	@echo "  make build            - Build for production"
	@echo "  make deploy           - Deploy to production"
	@echo "  make git-status       - Show git status"
	@echo "  make git-add          - Stage all changes"
	@echo "  make git-commit       - Commit with biome formatting"
	@echo "  make git-push         - Push to remote"
	@echo "  make update-unsandbox-sdk - Download latest un.js SDK from unsandbox.com"
	@echo "  make bundle-extension     - Bundle uncloseai.js for browser extension (CSP-safe IIFE)"
	@echo ""
	@echo "Language Examples:"
	@echo "  make languages-list           - List all language directories"
	@echo "  make languages-build-<lang>   - Build Docker image for language (use - for /: python-openai)"
	@echo "  make languages-build-all      - Build all language Docker images"
	@echo "  make languages-test-<lang>    - Test language implementation with endpoints"
	@echo "  make languages-test-all       - Test all language implementations"
	@echo "  make languages-clean          - Stop and remove language test containers"

# Code formatting and linting
format:
	npx biome format --write .

check:
	npx biome check .

format-check: format check

# Testing and validation
test:
	@echo "Running integration tests..."
	@if command -v node >/dev/null 2>&1; then \
		if node -e "import('jsdom')" 2>/dev/null; then \
			node integration_tests.js; \
		else \
			echo "⚠️  JSDOM not available - running simple tests instead"; \
			node simple_tests.js; \
		fi; \
	else \
		echo "❌ Node.js not available"; \
	fi

test-simple:
	node simple_tests.js

validate-exports:
	@echo "Running export validation..."
	@if command -v node >/dev/null 2>&1; then \
		node validate_exports.js; \
	else \
		echo "❌ Node.js not available"; \
	fi

test-modal:
	@echo "Running custom modal tests..."
	@if command -v node >/dev/null 2>&1; then \
		if node -e "import('jsdom')" 2>/dev/null; then \
			node modal_tests.js; \
		else \
			echo "⚠️  JSDOM not available - skipping modal tests (install jsdom for full modal testing)"; \
		fi; \
	else \
		echo "❌ Node.js not available"; \
	fi

validate-all: format-check validate-exports verify-translations test test-simple test-modal

# Development workflow
install:
	npm install

dev:
	python3 -m http.server 8000

build: format-check validate-all
	@echo "Build complete - all checks passed"

# Git workflow
git-status:
	git status

git-add:
	git add -A

git-commit: format-check
	git add -A
	@echo "Ready to commit - run 'git commit -m \"your message\"'"

git-push:
	git push

# Deployment
deploy: build git-add
	@echo "Ready to deploy - review changes and commit"

# Cleanup
clean:
	rm -f .biome-cache
	rm -f src/.*.swp
	rm -f .DS_Store
	find . -name "*.log" -delete
	find . -name "node_modules" -type d -exec rm -rf {} +

# Download latest unsandbox.com JavaScript SDK (Node.js)
update-unsandbox-sdk:
	@echo "Downloading latest un.js SDK..."
	@mkdir -p lib
	wget -O lib/un.js "https://git.unturf.com/engineering/unturf/un-inception/-/raw/main/clients/javascript/async/src/un_async.js"
	@echo "Done. Updated lib/un.js (Node.js SDK)"

# Bundle uncloseai.js for browser extension (IIFE, no ES modules, CSP-safe)
bundle-extension:
	@echo "Bundling uncloseai.js for browser extension..."
	node scripts/bundle-extension.mjs
	@ls -lh public/uncloseai-bundle.js
	@echo "Done. Output: public/uncloseai-bundle.js"

# Language validation
validate-languages:
	@echo "Validating language files..."
	@for file in src/languages/*.js; do \
		if [ "$$(basename $$file)" != "add-missing-keys.js" ] && [ "$$(basename $$file)" != "verify-translations.js" ]; then \
			echo "Checking $$file..."; \
			node -e "import('./$$file').then(m => console.log('✅', '$$file', 'exports:', Object.keys(m))).catch(e => console.error('❌', '$$file', 'error:', e.message))"; \
		fi \
	done

verify-translations:
	@echo "Verifying translation completeness..."
	@node src/languages/verify-translations.js

validate-translations: verify-translations validate-languages

# File structure validation
validate-structure:
	@echo "Validating project structure..."
	@test -f src/ui.js || echo "❌ Missing src/ui.js"
	@test -f src/translation.js || echo "❌ Missing src/translation.js"
	@test -f src/tts.js || echo "❌ Missing src/tts.js"
	@test -f src/chat.js || echo "❌ Missing src/chat.js"
	@test -f src/config.js || echo "❌ Missing src/config.js"
	@test -d src/languages || echo "❌ Missing src/languages directory"
	@echo "✅ Core files exist"

# Module size check
check-sizes:
	@echo "Module sizes:"
	@wc -l src/*.js | sort -n
	@echo ""
	@echo "Language files:"
	@wc -l src/languages/*.js | sort -n

# Production checks
prod-check: format-check validate-exports validate-structure
	@echo "Production readiness check complete"

# Development setup
setup: install
	@echo "Development environment setup complete"
	@echo "Run 'make dev' to start development server"

# Quick development cycle
quick: format-check git-add
	@echo "Quick validation complete - ready to commit"

# Full CI/CD cycle
ci: clean format-check validate-all validate-structure validate-translations check-sizes
	@echo "CI pipeline complete"

# Language Examples Commands
languages-list:
	@echo "Available language implementations:"
	@find languages -name "Dockerfile" -type f | sed 's|/Dockerfile||g' | sed 's|languages/||g' | sort || echo "No language implementations found"

languages-build-%:
	@echo "Building Docker image for $*..."
	@target_path=$$(echo "$*" | tr '-' '/'); \
	if [ -f "languages/$$target_path/Dockerfile" ]; then \
		echo "Found Dockerfile at languages/$$target_path/"; \
		docker build -t ai-unturf-$* languages/$$target_path/; \
	elif [ -f "languages/$*/Dockerfile" ]; then \
		echo "Found Dockerfile at languages/$*/"; \
		docker build -t ai-unturf-$* languages/$*/; \
	else \
		echo "❌ No Dockerfile found for $*"; \
		echo "Tried: languages/$$target_path/ and languages/$*/"; \
		exit 1; \
	fi

languages-test-%:
	@echo "Testing $* implementation with official endpoints..."
	@echo "Environment: MODEL_ENDPOINT_1=$(MODEL_ENDPOINT_1)"
	@echo "Environment: MODEL_ENDPOINT_2=$(MODEL_ENDPOINT_2)"
	@echo "Environment: TTS_ENDPOINT_1=$(TTS_ENDPOINT_1)"
	@target_path=$$(echo "$*" | tr '-' '/'); \
	if [ -f "languages/$$target_path/Dockerfile" ] || [ -f "languages/$*/Dockerfile" ]; then \
		echo "Starting container..."; \
		docker run -d --name test-$* $(DOCKER_ENV_VARS) ai-unturf-$* && \
		sleep 3 && \
		echo "Container logs:" && \
		docker logs test-$* && \
		echo "" && \
		echo "✅ Container started - check logs above for model discovery" && \
		echo "To stop: docker stop test-$* && docker rm test-$*"; \
	else \
		echo "❌ No Docker image found for $*"; \
		echo "Build it first: make languages-build-$*"; \
		exit 1; \
	fi

languages-build-all:
	@echo "Building all language implementations..."
	@failed=0; \
	total=0; \
	for dockerfile in $$(find languages -name "Dockerfile" -type f | sort); do \
		dir=$$(dirname $$dockerfile); \
		name=$$(echo $$dir | sed 's|languages/||g' | tr '/' '-'); \
		total=$$((total + 1)); \
		echo ""; \
		echo "========================================"; \
		echo "[$$total] Building $$name ($$dir)"; \
		echo "========================================"; \
		if docker build -t ai-unturf-$$name $$dir/ 2>&1 | tail -20; then \
			echo "✅ $$name built successfully"; \
		else \
			echo "❌ $$name build failed"; \
			failed=$$((failed + 1)); \
		fi; \
	done; \
	echo ""; \
	echo "========================================"; \
	echo "Build Summary: $$((total - failed))/$$total successful"; \
	if [ $$failed -gt 0 ]; then \
		echo "❌ $$failed build(s) failed"; \
		exit 1; \
	else \
		echo "✅ All builds successful!"; \
	fi

languages-test-all:
	@echo "Testing all language implementations..."
	@failed=0; \
	total=0; \
	for dockerfile in $$(find languages -name "Dockerfile" -type f | sort); do \
		dir=$$(dirname $$dockerfile); \
		name=$$(echo $$dir | sed 's|languages/||g' | tr '/' '-'); \
		total=$$((total + 1)); \
		echo ""; \
		echo "========================================"; \
		echo "[$$total] Testing $$name"; \
		echo "========================================"; \
		if docker run --rm $(DOCKER_ENV_VARS) ai-unturf-$$name 2>&1 | head -15; then \
			echo "✅ $$name ran successfully"; \
		else \
			echo "❌ $$name test failed"; \
			failed=$$((failed + 1)); \
		fi; \
	done; \
	echo ""; \
	echo "========================================"; \
	echo "Test Summary: $$((total - failed))/$$total successful"; \
	if [ $$failed -gt 0 ]; then \
		echo "❌ $$failed test(s) failed"; \
	else \
		echo "✅ All tests successful!"; \
	fi

languages-clean:
	@echo "Stopping and removing language test containers..."
	@docker ps -a | grep test- | awk '{print $$1}' | xargs -r docker stop 2>/dev/null || true
	@docker ps -a | grep test- | awk '{print $$1}' | xargs -r docker rm 2>/dev/null || true
	@echo "✅ Containers cleaned (images preserved for reuse)"
	@echo "To remove images: docker images | grep ai-unturf- | awk '{print \$$3}' | xargs docker rmi"