"""Extension backend API server."""

import asyncio
import json
from datetime import datetime
from typing import Any, Optional

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel

from surfai.browser import Browser
from surfai.config import Config

app = FastAPI(title="SurfAI Extension API")

# Enable CORS for extension
app.add_middleware(
    CORSMiddleware,
    allow_origins=["chrome-extension://*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


class ExecuteRequest(BaseModel):
    command: str
    model: Optional[str] = None


class ScreenshotRequest(BaseModel):
    full_page: bool = True


@app.get("/health")
async def health():
    """Health check endpoint."""
    return {"status": "ok", "timestamp": datetime.now().isoformat()}


@app.post("/execute")
async def execute(request: ExecuteRequest):
    """Execute a command."""
    try:
        browser = Browser(model=request.model)
        
        async with browser:
            results = await browser.execute_task(request.command)
            
            return {
                "success": True,
                "actions_executed": results.get("actions_executed", []),
                "extracted_data": results.get("extracted_data", []),
                "screenshots": results.get("screenshots", []),
            }
    except Exception as e:
        return {
            "success": False,
            "error": str(e),
        }


@app.post("/screenshot")
async def screenshot(request: ScreenshotRequest):
    """Take a screenshot."""
    try:
        browser = Browser()
        
        async with browser:
            result = await browser.screenshot(full_page=request.full_page)
            
            return {
                "success": result.get("success", False),
                "path": result.get("path", ""),
                "size_kb": result.get("size_kb", 0),
            }
    except Exception as e:
        return {
            "success": False,
            "error": str(e),
        }


@app.get("/config")
async def get_config():
    """Get current configuration."""
    config = Config.load()
    return {
        "default_model": config.default_model,
        "available_models": list(config.models.keys()),
    }


@app.post("/config")
async def update_config(model: str, api_key: str):
    """Update configuration."""
    try:
        config = Config.load()
        config.set_model(model, api_key)
        return {"success": True}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


def start_server(host: str = "0.0.0.0", port: int = 8000):
    """Start the extension API server."""
    import uvicorn
    uvicorn.run(app, host=host, port=port)


if __name__ == "__main__":
    start_server()
