.PHONY: help install build build-offline build-tails serve-local serve-bun audit clean verify-offline verify-tails dev test

help:
	@echo "seedpgp-web Makefile - Bun-based build system"
	@echo ""
	@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
	@echo "  🚀 QUICK START"
	@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
	@echo ""
	@echo "  Recommended for real use (\$$10K+):"
	@echo "    make full-build-tails    # Build, verify, audit for TailsOS"
	@echo "    make serve-local         # Serve on http://localhost:8000"
	@echo ""
	@echo "  For development:"
	@echo "    make dev                 # Hot reload dev server"
	@echo ""
	@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
	@echo "  📦 BUILD COMMANDS"
	@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
	@echo ""
	@echo "  make install             Install dependencies with Bun"
	@echo "  make build               Build for Cloudflare Pages (absolute paths)"
	@echo "  make build-offline       Build with relative paths (local testing)"
	@echo "  make build-tails         Build for TailsOS (CSP embedded, checksums)"
	@echo ""
	@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
	@echo "  🔍 VERIFICATION & TESTING"
	@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
	@echo ""
	@echo "  make verify-tails        Verify TailsOS build (CSP, paths, integrity)"
	@echo "  make verify-offline      Verify offline build compatibility"
	@echo "  make audit               Run security audit (network, storage, CSP)"
	@echo "  make test                Run test suite (BIP39, Krux, security)"
	@echo ""
	@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
	@echo "  🌐 LOCAL SERVERS"
	@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
	@echo ""
	@echo "  make serve-local         Serve dist/ with Python HTTP server (port 8000)"
	@echo "  make serve-bun           Serve dist/ with Bun server (port 8000)"
	@echo "  make dev                 Development server with hot reload (port 5173)"
	@echo ""
	@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
	@echo "  🔗 PIPELINE COMMANDS"
	@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
	@echo ""
	@echo "  make full-build-tails    Clean → build-tails → verify → audit"
	@echo "  make full-build-offline  Clean → build-offline → verify"
	@echo ""
	@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
	@echo "  🗑️  MAINTENANCE"
	@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
	@echo ""
	@echo "  make clean               Remove dist/, dist-tails/, build cache"
	@echo ""
	@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
	@echo "  💡 EXAMPLES"
	@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
	@echo ""
	@echo "  # Full TailsOS production build"
	@echo "  make full-build-tails && make serve-local"
	@echo ""
	@echo "  # Development with hot reload"
	@echo "  make dev"
	@echo ""
	@echo "  # Manual verification"
	@echo "  make build-tails"
	@echo "  make verify-tails"
	@echo "  grep 'connect-src' dist-tails/index.html"
	@echo ""
	@echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
	@echo ""
	@echo "For more details, see README.md or run specific targets."

# Install dependencies
install:
	@echo "📦 Installing dependencies with Bun..."
	bun install

# Build for Cloudflare (absolute paths, CSP via _headers)
build:
	@echo "🔨 Building for Cloudflare Pages (absolute paths)..."
	VITE_BASE_PATH="/" bun run vite build
	@echo "✅ Build complete: dist/"
	@echo "   CSP will be enforced by _headers file"

# Build for offline/local testing (relative paths, no CSP)
build-offline:
	@echo "🔨 Building for offline use (relative paths)..."
	VITE_BASE_PATH="./" bun run vite build
	@echo "✅ Build complete: dist/ (with relative asset paths)"
	@echo "⚠️  No CSP embedded - use build-tails for production offline use"

# Build for TailsOS with embedded CSP (relative paths + security hardening)
build-tails:
	@echo "🔨 Building for TailsOS (relative paths + embedded CSP)..."
	VITE_BASE_PATH="./" bun run vite build
	@echo ""
	@echo "🔒 Injecting production CSP into index.html (replacing baseline CSP)..."
	@perl -i.bak -0777 -pe 's|<meta\s+http-equiv="Content-Security-Policy"[^>]*/>|<meta http-equiv="Content-Security-Policy" content="default-src '"'"'self'"'"'; script-src '"'"'self'"'"' '"'"'unsafe-inline'"'"' '"'"'wasm-unsafe-eval'"'"'; style-src '"'"'self'"'"' '"'"'unsafe-inline'"'"'; img-src '"'"'self'"'"' data: blob:; connect-src '"'"'self'"'"' blob: data:; font-src '"'"'self'"'"'; object-src '"'"'none'"'"'; media-src '"'"'self'"'"' blob:; base-uri '"'"'self'"'"'; form-action '"'"'none'"'"';" data-env="tails">|' dist/index.html
	@rm -f dist/index.html.bak
	@echo "✅ CSP embedded in dist/index.html"
	@echo ""
	@echo "📦 Creating TailsOS distribution package..."
	@mkdir -p dist-tails
	@cp -R dist/* dist-tails/
	@echo "# SeedPGP Web - TailsOS Offline Build" > dist-tails/README.txt
	@echo "" >> dist-tails/README.txt
	@echo "Built: $$(date)" >> dist-tails/README.txt
	@echo "" >> dist-tails/README.txt
	@echo "Usage Instructions:" >> dist-tails/README.txt
	@echo "1. Copy this entire folder to a USB drive" >> dist-tails/README.txt
	@echo "2. Boot TailsOS from your primary USB" >> dist-tails/README.txt
	@echo "3. Insert this application USB drive" >> dist-tails/README.txt
	@echo "4. Open Tor Browser (or regular browser if offline)" >> dist-tails/README.txt
	@echo "5. Navigate to: file:///media/amnesia/USBNAME/index.html" >> dist-tails/README.txt
	@echo "6. Enable JavaScript if prompted" >> dist-tails/README.txt
	@echo "" >> dist-tails/README.txt
	@echo "Security Features:" >> dist-tails/README.txt
	@echo "- Content Security Policy enforced (no network access)" >> dist-tails/README.txt
	@echo "- All assets relative (works offline)" >> dist-tails/README.txt
	@echo "- No external dependencies or CDN calls" >> dist-tails/README.txt
	@echo "- Session-only crypto keys (destroyed on tab close)" >> dist-tails/README.txt
	@echo "" >> dist-tails/README.txt
	@echo "SHA-256 Checksums:" >> dist-tails/README.txt
	@cd dist-tails && find . -type f -not -name "README.txt" -exec shasum -a 256 {} \; | sort >> README.txt
	@echo ""
	@echo "✅ TailsOS build complete: dist-tails/"
	@echo ""
	@echo "Next steps:"
	@echo "  1. Verify checksums: make verify-tails"
	@echo "  2. Format USB (FAT32): diskutil eraseDisk FAT32 SEEDPGP /dev/diskX"
	@echo "  3. Copy: cp -R dist-tails/* /Volumes/SEEDPGP/"
	@echo "  4. Eject: diskutil eject /Volumes/SEEDPGP"
	@echo "  5. Boot TailsOS and test"

verify-tails:
	@echo "1️⃣  Checking for CSP in index.html..."
	@if grep -q "connect-src.*'self'" dist-tails/index.html; then \
		echo "✅ CSP allows local connections only (WASM compatible)"; \
	else \
		echo "❌ CSP misconfigured"; \
		exit 1; \
	fi
	@echo ""
	@# 2. CHECK RELATIVE PATHS
	@if grep -q 'src="./' dist-tails/index.html; then \
		echo "✅ Relative paths detected (offline compatible)"; \
	else \
		echo "❌ Absolute paths found"; \
		exit 1; \
	fi
	@echo ""
	@# 3. SECURITY NOTE (NOT FAILURE)
	@echo "5️⃣  Security Note:"
	@echo "    ℹ️  fetch() references exist in bundle (from openpgp.js)"
	@echo "    ✓  These are BLOCKED by CSP connect-src 'none' at runtime"
	@echo "    ✓  Browser will reject all network attempts with CSP violation"
	@echo ""
	@echo "✅ TailsOS build verification complete"



# Development server (for testing locally)
serve-local:
	@echo "🚀 Starting local server at http://localhost:8000"
	@echo "   Press Ctrl+C to stop"
	@if [ ! -d dist ]; then \
		echo "❌ dist/ not found. Run 'make build' first"; \
		exit 1; \
	fi
	cd dist && python3 -m http.server 8000

serve-bun:
	@echo "🚀 Starting Bun static server at http://127.0.0.1:8000"
	@echo "   Press Ctrl+C to stop"
	@if [ ! -d dist ]; then \
		echo "❌ dist/ not found. Run 'make build' first"; \
		exit 1; \
	fi
	bun ./serve.ts

# Run test suite
test:
	@echo "🧪 Running test suite..."
	bun test

# Security audit - check for network calls and suspicious patterns
audit:
	@echo "🔍 Running security audit..."
	@echo ""
	@echo "Checking for network calls in source..."
	@grep -r "fetch\|XMLHttpRequest\|axios" src/ --include="*.ts" --include="*.tsx" --include="*.js" || echo "✅ No explicit network calls found"
	@echo ""
	@echo "Checking for external resources in build..."
	@if [ -d dist ]; then \
		grep -r "cloudflare\|googleapis\|cdn\|http:" dist/ || echo "✅ No external URLs in dist/"; \
	else \
		echo "⚠️  dist/ not found - run 'make build' first"; \
	fi
	@echo ""
	@echo "Checking for persistent storage usage..."
	@grep -r "localStorage\|sessionStorage" src/ --include="*.ts" --include="*.tsx" || echo "✅ No persistent storage in crypto paths"
	@echo ""
	@echo "Checking for eval() or Function() usage..."
	@grep -r "eval(\|new Function(" src/ --include="*.ts" --include="*.tsx" || echo "✅ No dynamic code execution"
	@echo ""
	@echo "✅ Security audit complete"

# Verify offline compatibility
verify-offline:
	@echo "🧪 Verifying offline compatibility..."
	@echo ""
	@if [ ! -d dist ]; then \
		echo "❌ dist/ not found. Run 'make build-offline' first"; \
		exit 1; \
	fi
	@echo "Checking dist/ file structure..."
	@find dist -type f | wc -l | xargs echo "Total files:"
	@echo ""
	@echo "Verifying index.html exists and is readable..."
	@[ -f dist/index.html ] && echo "✅ index.html found" || (echo "❌ index.html NOT found" && exit 1)
	@echo ""
	@echo "Checking for asset references in index.html..."
	@head -20 dist/index.html | grep -q "assets" && echo "✅ Assets referenced" || echo "⚠️  No assets referenced"
	@echo ""
	@echo "Checking for relative path usage..."
	@grep -q 'src="./' dist/index.html && echo "✅ Relative paths detected" || echo "⚠️  Check asset paths"
	@echo ""
	@echo "✅ Offline compatibility check complete"

# Clean build artifacts
clean:
	@echo "🗑️  Cleaning build artifacts..."
	rm -rf dist/
	rm -rf dist-tails/
	rm -rf .dist/
	rm -rf node_modules/.vite/
	@echo "✅ Clean complete"

# Full TailsOS pipeline: clean, build, verify, audit
full-build-tails: clean build-tails verify-tails audit
	@echo ""
	@echo "✅ Full TailsOS build pipeline complete!"
	@echo "   Ready to copy to USB for TailsOS"
	@echo ""
	@echo "Package location: dist-tails/"
	@echo "Includes: index.html, assets/, and README.txt with checksums"

# Full offline pipeline (less strict than Tails)
full-build-offline: clean build-offline verify-offline audit
	@echo ""
	@echo "✅ Full offline build pipeline complete!"
	@echo "   Ready for local testing"

# Quick development setup
dev:
	@echo "🚀 Starting Bun dev server..."
	bun run dev
