#!/usr/bin/env python3
"""
GENESIS API SERVER
==================
Simple REST API for Genesis status, control, and monitoring.

Endpoints:
    GET  /status          - System status
    GET  /tasks           - Task queue
    GET  /budget          - Budget status
    POST /tasks           - Add new task
    POST /execute         - Execute task
    GET  /health          - Health check

Usage:
    python genesis_api.py                  # Start on port 8081
    python genesis_api.py --port 9000      # Custom port
"""

import json
import os
import sys
from datetime import datetime
from http.server import HTTPServer, BaseHTTPRequestHandler
from pathlib import Path
from urllib.parse import urlparse, parse_qs

# Genesis root
GENESIS_ROOT = Path(__file__).parent.parent
sys.path.insert(0, str(GENESIS_ROOT / "core"))

# Set API key
os.environ['GEMINI_API_KEY'] = 'AIzaSyALfbAdHfJ6aRnqNyiTRmKmGVoena1JsdU'


class GenesisAPIHandler(BaseHTTPRequestHandler):
    """HTTP request handler for Genesis API."""

    def _send_json(self, data: dict, status: int = 200):
        """Send JSON response."""
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Access-Control-Allow-Origin", "*")
        self.end_headers()
        self.wfile.write(json.dumps(data, indent=2).encode())

    def _send_error(self, message: str, status: int = 400):
        """Send error response."""
        self._send_json({"error": message, "status": status}, status)

    def do_GET(self):
        """Handle GET requests."""
        parsed = urlparse(self.path)
        path = parsed.path

        try:
            if path == "/" or path == "/health":
                self._handle_health()
            elif path == "/status":
                self._handle_status()
            elif path == "/tasks":
                self._handle_tasks()
            elif path == "/budget":
                self._handle_budget()
            elif path == "/dashboard":
                self._handle_dashboard()
            else:
                self._send_error("Not found", 404)
        except Exception as e:
            self._send_error(str(e), 500)

    def do_POST(self):
        """Handle POST requests."""
        parsed = urlparse(self.path)
        path = parsed.path

        try:
            content_length = int(self.headers.get("Content-Length", 0))
            body = self.rfile.read(content_length).decode() if content_length else "{}"
            data = json.loads(body) if body else {}

            if path == "/execute":
                self._handle_execute(data)
            elif path == "/tasks":
                self._handle_add_task(data)
            else:
                self._send_error("Not found", 404)
        except json.JSONDecodeError:
            self._send_error("Invalid JSON", 400)
        except Exception as e:
            self._send_error(str(e), 500)

    def do_OPTIONS(self):
        """Handle CORS preflight."""
        self.send_response(200)
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type")
        self.end_headers()

    def _handle_health(self):
        """Health check endpoint."""
        self._send_json({
            "status": "healthy",
            "timestamp": datetime.now().isoformat(),
            "version": "1.0.0"
        })

    def _handle_status(self):
        """System status endpoint."""
        try:
            from status_dashboard import StatusDashboard
            dashboard = StatusDashboard()
            results = dashboard.run_checks()
            self._send_json(results)
        except ImportError:
            # Fallback status
            self._send_json({
                "status": "operational",
                "timestamp": datetime.now().isoformat(),
                "components": {
                    "core": "available",
                    "hyperdrive": "available"
                }
            })

    def _handle_tasks(self):
        """Task queue endpoint."""
        tasks_path = GENESIS_ROOT / "loop" / "tasks.json"

        if not tasks_path.exists():
            self._send_json({"tasks": [], "total": 0})
            return

        with open(tasks_path) as f:
            data = json.load(f)

        stories = data.get("stories", [])
        completed = len([s for s in stories if s.get("passes")])
        pending = len([s for s in stories if not s.get("passes")])

        self._send_json({
            "project": data.get("project", "Genesis"),
            "phase": data.get("phase", 1),
            "total": len(stories),
            "completed": completed,
            "pending": pending,
            "tasks": stories
        })

    def _handle_budget(self):
        """Budget status endpoint."""
        try:
            from hyperdrive_controller import BudgetTracker
            tracker = BudgetTracker()
            summary = tracker.get_summary()
            alert = tracker.budget_alert()

            self._send_json({
                "total_remaining": summary["total_remaining"],
                "alert": alert,
                "budgets": summary["budgets"]
            })
        except ImportError:
            self._send_json({
                "total_remaining": 336.0,
                "alert": {"alert": False, "message": "Budget OK"},
                "error": "Budget tracker unavailable"
            })

    def _handle_dashboard(self):
        """Dashboard HTML endpoint."""
        html = """
<!DOCTYPE html>
<html>
<head>
    <title>Genesis Dashboard</title>
    <style>
        body { font-family: monospace; background: #1a1a2e; color: #eee; padding: 20px; }
        .card { background: #16213e; padding: 20px; margin: 10px; border-radius: 8px; }
        .ok { color: #4ade80; }
        .warn { color: #fbbf24; }
        .error { color: #ef4444; }
        h1 { color: #60a5fa; }
    </style>
</head>
<body>
    <h1>Genesis Hyperdrive Dashboard</h1>
    <div class="card" id="status">Loading...</div>
    <div class="card" id="tasks">Loading...</div>
    <div class="card" id="budget">Loading...</div>
    <script>
        async function refresh() {
            const status = await fetch('/status').then(r => r.json());
            const tasks = await fetch('/tasks').then(r => r.json());
            const budget = await fetch('/budget').then(r => r.json());

            document.getElementById('status').innerHTML =
                '<h2>System Status: ' + status.overall_status + '</h2>' +
                '<pre>' + JSON.stringify(status.checks, null, 2) + '</pre>';

            document.getElementById('tasks').innerHTML =
                '<h2>Tasks: ' + tasks.completed + '/' + tasks.total + '</h2>' +
                '<p>Phase: ' + tasks.phase + ' | Project: ' + tasks.project + '</p>';

            document.getElementById('budget').innerHTML =
                '<h2>Budget: $' + budget.total_remaining.toFixed(2) + '</h2>' +
                '<p>' + budget.alert.message + '</p>';
        }
        refresh();
        setInterval(refresh, 10000);
    </script>
</body>
</html>
"""
        self.send_response(200)
        self.send_header("Content-Type", "text/html")
        self.end_headers()
        self.wfile.write(html.encode())

    def _handle_execute(self, data: dict):
        """Execute a task."""
        task_id = data.get("task_id")

        if not task_id:
            self._send_error("task_id required", 400)
            return

        try:
            from gemini_executor import GeminiExecutor

            tasks_path = GENESIS_ROOT / "loop" / "tasks.json"
            with open(tasks_path) as f:
                tasks_data = json.load(f)

            task = None
            for story in tasks_data.get("stories", []):
                if story.get("id") == task_id:
                    task = story
                    break

            if not task:
                self._send_error(f"Task {task_id} not found", 404)
                return

            executor = GeminiExecutor()
            result = executor.execute_task(task)

            self._send_json({
                "task_id": task_id,
                "success": result.success,
                "task_complete": result.task_complete,
                "response_preview": result.response[:500] if result.response else "",
                "cost": result.cost_estimate,
                "error": result.error
            })

        except Exception as e:
            self._send_error(str(e), 500)

    def _handle_add_task(self, data: dict):
        """Add a new task."""
        title = data.get("title")
        description = data.get("description", "")
        complexity = data.get("complexity", "moderate")

        if not title:
            self._send_error("title required", 400)
            return

        tasks_path = GENESIS_ROOT / "loop" / "tasks.json"

        with open(tasks_path) as f:
            tasks_data = json.load(f)

        # Generate task ID
        stories = tasks_data.get("stories", [])
        phase = tasks_data.get("phase", 1)
        task_num = len(stories) + 1
        task_id = f"phase{phase}-{task_num:03d}"

        new_task = {
            "id": task_id,
            "title": title,
            "description": description,
            "acceptance_criteria": data.get("acceptance_criteria", []),
            "passes": False,
            "complexity": complexity
        }

        stories.append(new_task)
        tasks_data["stories"] = stories
        tasks_data["updated_at"] = datetime.now().isoformat()

        with open(tasks_path, "w") as f:
            json.dump(tasks_data, f, indent=2)

        self._send_json({
            "success": True,
            "task_id": task_id,
            "task": new_task
        })

    def log_message(self, format, *args):
        """Custom log format."""
        print(f"[API] {self.address_string()} - {args[0]}")


def run_server(port: int = 8081):
    """Run the Genesis API server."""
    server = HTTPServer(("0.0.0.0", port), GenesisAPIHandler)
    print(f"\\n{'='*50}")
    print("GENESIS API SERVER")
    print(f"{'='*50}")
    print(f"  Port: {port}")
    print(f"  URL: http://localhost:{port}")
    print(f"\\nEndpoints:")
    print(f"  GET  /health    - Health check")
    print(f"  GET  /status    - System status")
    print(f"  GET  /tasks     - Task queue")
    print(f"  GET  /budget    - Budget status")
    print(f"  GET  /dashboard - Web dashboard")
    print(f"  POST /execute   - Execute task")
    print(f"  POST /tasks     - Add task")
    print(f"\\nPress Ctrl+C to stop")
    print(f"{'='*50}\\n")

    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\\n[API] Shutting down...")
        server.shutdown()


def main():
    import argparse
    parser = argparse.ArgumentParser(description="Genesis API Server")
    parser.add_argument("--port", type=int, default=8081, help="Server port")
    args = parser.parse_args()

    run_server(args.port)


if __name__ == "__main__":
    main()
