# Post-ERG Justfile
# Unified recipes for the complete site (public + admin)

# Default recipe - show available commands
default:
    @just --list

# ============================================================================
# Development Setup
# ============================================================================

[group('dev')]
setup:
    @echo "🛠️  Setting up development environment..."
    @bash setup-dev.sh

# ============================================================================
# Development Server
# ============================================================================

[group('dev')]
serve:
    @echo "🚀 Starting Post-ERG development server"
    @echo "========================================"
    @echo ""
    @echo "📍 Public site:  http://localhost:8000"
    @echo "📍 Admin panel:  http://localhost:8000/admin/"
    @echo "🔒 Serving from public/ directory (matches production)"
    @echo ""
    @echo "✨ Live reload enabled - browser auto-refreshes on file save!"
    @echo ""
    @echo "Press Ctrl+C to stop"
    @echo ""
    @php -S 127.0.0.1:8000 -t public/

[group('dev')]
stop:
    @echo "🛑 Stopping development server..."
    @pkill -f "php -S 127.0.0.1:8000" 2>/dev/null && echo "✓ Server stopped" || echo "No server running"

[group('dev')]
logs:
    @echo "📋 Development logs"
    @echo "==================="
    @echo ""
    @if [ -f error.log ]; then \
        echo "Application errors:"; \
        echo "------------------"; \
        tail -n 20 error.log; \
    else \
        echo "No error log found"; \
    fi

# ============================================================================
# Deploy Group
# ============================================================================

[group('deploy')]
deploy:
    @echo "📤 Deploying Post-ERG complete site"
    @echo "===================================="
    @echo ""
    @echo "⚠️  First time? Ensure /var/www/posterg/ exists on server with:"
    @echo "   ssh posterg"
    @echo "   sudo mkdir -p /var/www/posterg"
    @echo "   sudo chown www-data:posterg /var/www/posterg"
    @echo "   sudo chmod 775 /var/www/posterg"
    @echo ""
    @echo "Step 1: Deploying application to /var/www/posterg/..."
    rsync -vur --progress \
        --chown="www-data:posterg" \
        --exclude 'vendor' \
        --exclude 'tests' \
        --exclude 'test.db' \
        --exclude '*.md' \
        --exclude '.git*' \
        --exclude '.jj' \
        --exclude '.DS_Store' \
        --exclude 'database/backup_*' \
        --exclude 'database/fixtures' \
        --exclude 'database/docs' \
        --exclude 'nginx' \
        --exclude 'docs' \
        --exclude 'justfile*' \
        --exclude 'migrate-structure.sh' \
        --exclude 'setup-dev.sh' \
        --exclude 'var/cache/*' \
        --exclude 'var/logs/*' \
        ./ posterg:/var/www/posterg/
    @echo ""
    @echo "Step 2: Setting up directories and permissions..."
    ssh posterg "cd /var/www/posterg && \
                 mkdir -p var/{cache,logs,tmp} && \
                 chown -R www-data:posterg . && \
                 chmod -R 755 . && \
                 chmod -R 775 var/ database/ && \
                 chmod 660 database/*.db 2>/dev/null || true"
    @echo ""
    @echo "✅ Deployment complete!"
    @echo ""
    @echo "📁 Server structure:"
    @echo "  • App root:      /var/www/posterg/"
    @echo "  • DocumentRoot:  /var/www/posterg/public/"
    @echo ""
    @echo "🔍 Verify deployment:"
    @echo "  • Public: https://posterg.erg.be/"
    @echo "  • Admin:  https://posterg.erg.be/admin/"
    @echo ""
    @echo "⚠️  IMPORTANT: Update nginx config to point to /var/www/posterg/public/"
    @echo "   Run: just deploy-nginx"

[group('deploy')]
deploy-database:
    @echo "⚠️  Deploying test database (will overwrite remote test.db)"
    @echo "Creating database directory if needed..."
    ssh posterg "mkdir -p /var/www/posterg/database"
    rsync -vur --progress ./database/test.db posterg:/var/www/posterg/database/test.db
    @echo "Setting correct permissions..."
    ssh posterg "chown www-data:posterg /var/www/posterg/database /var/www/posterg/database/test.db && chmod 775 /var/www/posterg/database && chmod 660 /var/www/posterg/database/test.db"
    @echo "✅ Test database deployed and configured"

# Legacy alias
[group('deploy')]
test-deploy:
    @just deploy-database
# ============================================================================
# Testing
# ============================================================================

[group('test')]
test:
    @echo "🧪 Running Post-ERG Test Suite"
    @echo "==============================="
    @echo ""
    @php tests/run-tests.php

[group('test')]
test-unit:
    @echo "🧪 Unit Tests"
    @echo "============="
    @php tests/Unit/DatabaseTest.php
    @echo ""
    @php tests/Unit/RateLimitTest.php

[group('test')]
test-integration:
    @echo "🧪 Integration Tests"
    @echo "===================="
    @php tests/Integration/SearchTest.php

[group('test')]
test-security:
    @echo "🧪 Security Tests"
    @echo "================="
    @php tests/Security/SecurityTest.php

[group('test')]
syntax:
    @echo "🔍 Checking PHP Syntax"
    @echo "======================"
    @find . -maxdepth 1 -name "*.php" -not -path "./vendor/*" -exec php -l {} \; | grep -v "No syntax errors"
    @find admin/ -name "*.php" -exec php -l {} \; 2>/dev/null | grep -v "No syntax errors" || true
    @find src/ -name "*.php" -exec php -l {} \; | grep -v "No syntax errors"
    @echo "✅ All PHP files have valid syntax"

# ============================================================================
# Database Management
# ============================================================================

# ============================================================================
# Database Statistics
# ============================================================================

[group('stats')]
stats:
    @echo "📊 Database Statistics"
    @echo "======================"
    @echo ""
    @sqlite3 database/test.db "SELECT COUNT(*) || ' total theses' FROM theses;"
    @sqlite3 database/test.db "SELECT COUNT(*) || ' published theses' FROM theses WHERE is_published = 1;"
    @sqlite3 database/test.db "SELECT COUNT(*) || ' authors' FROM authors;"
    @sqlite3 database/test.db "SELECT COUNT(*) || ' supervisors' FROM supervisors;"
    @sqlite3 database/test.db "SELECT COUNT(*) || ' keywords' FROM keywords;"
    @sqlite3 database/test.db "SELECT COUNT(*) || ' files uploaded' FROM thesis_files;"

[group('stats')]
recent:
    @echo "📅 Recent Theses"
    @echo "================"
    @sqlite3 -column -header database/test.db "SELECT id, title, year, authors FROM v_theses_public ORDER BY year DESC, title LIMIT 10;"

# ============================================================================
# Database Management
# ============================================================================

[group('database')]
init-db:
    @echo "📊 Creating test database from schema..."
    @sqlite3 database/test.db < database/schema.sql
    @echo "✓ Test database created"
    @sqlite3 database/test.db "SELECT COUNT(*) || ' tables created' FROM sqlite_master WHERE type='table';"
    @sqlite3 database/test.db "SELECT COUNT(*) || ' orientations loaded' FROM orientations;"
    @sqlite3 database/test.db "SELECT COUNT(*) || ' AP programs loaded' FROM ap_programs;"

[group('database')]
reset-db:
    @echo "⚠️  Resetting database (will delete all data)..."
    @rm -f database/test.db
    @just init-db
    @echo "✓ Database reset complete"

[group('database')]
query:
    @sqlite3 database/test.db

[group('database')]
show id:
    @echo "Thesis #{{id}}"
    @echo "=============="
    @sqlite3 -column -header database/test.db "SELECT * FROM v_theses_full WHERE id = {{id}};"

[group('database')]
backup:
    @echo "💾 Backing up database..."
    @sqlite3 database/test.db .dump > database/backup_$(date +%Y%m%d_%H%M%S).sql
    @echo "✓ Database dumped to database/backup_$(date +%Y%m%d_%H%M%S).sql"

[group('database')]
fixtures:
    @echo "🎭 Creating test database with fixtures..."
    @php database/fixtures/CreateTestDatabase.php

[group('database')]
deploy-test-db:
    @echo "⚠️  Deploying test database to server (will overwrite remote test.db)"
    @echo "Creating database directory if needed..."
    ssh posterg "mkdir -p /var/www/html/database"
    rsync -vur --progress ./database/test.db posterg:/var/www/html/database/test.db
    @echo "Setting correct permissions..."
    ssh posterg "chgrp posterg /var/www/html/database /var/www/html/database/test.db && \
                 chmod 775 /var/www/html/database && \
                 chmod 660 /var/www/html/database/test.db"
    @echo "✅ Test database deployed"

# ============================================================================
# Server Tools
# ============================================================================

[group('server')]
deploy-nginx:
    @echo "🔧 Deploying nginx configuration..."
    @echo ""
    @echo "⚠️  IMPORTANT: Checking nginx config has correct DocumentRoot..."
    @if ! grep -q "/var/www/posterg/public" nginx/posterg.conf 2>/dev/null; then \
        echo "❌ ERROR: nginx/posterg.conf must contain '/var/www/posterg/public'"; \
        echo "   Current DocumentRoot needs updating!"; \
        echo ""; \
        echo "   Edit nginx/posterg.conf and change:"; \
        echo "     root /var/www/html;"; \
        echo "   To:"; \
        echo "     root /var/www/posterg/public;"; \
        exit 1; \
    fi
    @echo "✅ nginx config looks correct"
    @echo ""
    rsync -vur --progress ./nginx/posterg.conf posterg:/tmp/posterg.conf
    rsync -vur --progress ./nginx/deploy-production-new.sh posterg:/tmp/deploy-production.sh
    @echo "✅ Files uploaded to /tmp/ on server"
    @echo ""
    @echo "Next steps on the server:"
    @echo "  ssh posterg"
    @echo "  sudo bash /tmp/deploy-production.sh"
    @echo "  (This will apply config and show reload command)"

[group('server')]
deploy-admin-tools:
    @echo "🔑 Uploading admin user management tools..."
    rsync -vur --progress ./nginx/manage-admin-users.sh posterg:/tmp/manage-admin-users.sh
    @echo "✅ Script uploaded"
    @echo ""
    @echo "To manage admin users:"
    @echo "  ssh posterg"
    @echo "  sudo bash /tmp/manage-admin-users.sh"

[group('server')]
server-logs:
    @echo "📋 Server logs (last 50 lines)"
    @echo "=============================="
    @echo ""
    @echo "Nginx error log:"
    @echo "----------------"
    ssh posterg "sudo tail -50 /var/log/nginx/posterg_error.log" || echo "Cannot read logs (permission denied)"
    @echo ""
    @echo "Nginx access log:"
    @echo "-----------------"
    ssh posterg "sudo tail -20 /var/log/nginx/posterg_access.log" || echo "Cannot read logs (permission denied)"

[group('server')]
server-status:
    @echo "🔍 Server Status"
    @echo "================"
    @ssh posterg "systemctl is-active nginx && echo '✓ Nginx running' || echo '✗ Nginx stopped'"
    @ssh posterg "systemctl is-active php8.4-fpm && echo '✓ PHP-FPM running' || echo '✗ PHP-FPM stopped'"
    @echo ""
    @echo "Site check:"
    @curl -s -o /dev/null -w "  • Public: %{http_code}\n" https://posterg.erg.be/ || echo "  • Public: offline"
    @curl -s -o /dev/null -w "  • Admin:  %{http_code}\n" https://posterg.erg.be/admin/ || echo "  • Admin: offline"

# ============================================================================
# Utility Commands
# ============================================================================

[group('utils')]
clean:
    @echo "🧹 Cleaning up development files..."
    @rm -f error.log
    @rm -f admin/error.log
    @rm -rf src/cache/rate_limit/*
    @rm -f /tmp/posterg-*.log
    @rm -f /tmp/posterg-*.pid
    @echo "✓ Cleanup complete"

[group('utils')]
setup-dirs:
    @echo "📁 Creating data directories..."
    @mkdir -p admin/data/theses
    @mkdir -p admin/data/covers
    @mkdir -p admin/data/yaml
    @mkdir -p src/cache/rate_limit
    @touch admin/data/theses/.gitkeep
    @touch admin/data/covers/.gitkeep
    @echo "✓ Directories created"
