"""FastAPI application for the voice control web interface."""

from __future__ import annotations

import os
import sys
import threading
from typing import Any

import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse, Response

# Handle both package and direct script execution
# __package__ is None when run as script, '' when imported from a script
if not __package__:
    _pkg_dir = os.path.dirname(os.path.abspath(__file__))
    if _pkg_dir not in sys.path:
        sys.path.insert(0, _pkg_dir)
    from models import CommandRequest, CommandResponse
    from state import SharedState
    from templates import HTML_TEMPLATE
else:
    from .models import CommandRequest, CommandResponse
    from .state import SharedState
    from .templates import HTML_TEMPLATE


def create_api(state: SharedState) -> FastAPI:
    """Create FastAPI application with voice control endpoints."""
    app = FastAPI(
        title="Voice Control Debug API",
        description="Debug interface for the voice control node",
        version="0.1.0",
    )

    @app.get("/", response_class=HTMLResponse)
    def index() -> str:
        """Serve the web interface."""
        return HTML_TEMPLATE

    @app.get("/api/status")
    def get_status() -> dict:
        """Get current status."""
        try:
            return state.get_status()
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))

    @app.get("/api/objects")
    def get_objects() -> dict:
        """Get detected and static objects."""
        try:
            return state.get_objects()
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))

    @app.get("/api/queue")
    def get_queue() -> list:
        """Get the command queue."""
        try:
            return state.get_queue()
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))

    @app.post("/api/queue/clear")
    def clear_queue() -> dict:
        """Clear the command queue."""
        try:
            with state._lock:
                state.voice_state.queue.clear()
            return {"ok": True}
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))

    @app.get("/api/history")
    def get_history() -> list:
        """Get command history."""
        try:
            return state.get_history()
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))

    @app.get("/api/errors")
    def get_errors() -> list:
        """Get error log."""
        try:
            return state.get_errors()
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))

    @app.post("/api/command", response_model=CommandResponse)
    def send_command(request: CommandRequest) -> CommandResponse:
        """Send a voice command."""
        try:
            callback = state.get_command_callback()
            if callback is None:
                return CommandResponse(ok=False, text="No command handler available", status="error")

            result = callback(request.text)
            return CommandResponse(
                ok=result.get("status") == "ok",
                text=result.get("text", ""),
                status=result.get("status", "error"),
            )
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))

    @app.get("/api/image")
    def get_image() -> Response:
        """Get the latest camera image as JPEG."""
        try:
            image_data = state.get_image()
            if image_data is None:
                # Return a 1x1 transparent pixel if no image
                return Response(
                    content=b"",
                    media_type="image/jpeg",
                    status_code=204,
                )
            return Response(
                content=image_data,
                media_type="image/jpeg",
                headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
            )
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))

    @app.get("/api/image/info")
    def get_image_info() -> dict:
        """Get image metadata."""
        try:
            return {
                "has_image": state.get_image() is not None,
                "age_ms": state.get_image_age_ms(),
            }
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))

    return app


def run_uvicorn(app: FastAPI, host: str, port: int) -> None:
    """Run uvicorn server (for use in background thread)."""
    config = uvicorn.Config(app, host=host, port=port, log_level="warning")
    server = uvicorn.Server(config)
    server.run()


def start_api_server(state: SharedState, config: Any) -> threading.Thread:
    """Start the API server in a background thread."""
    import time as _time
    app = create_api(state)
    api_thread = threading.Thread(
        target=run_uvicorn,
        args=(app, config.host, config.port),
        daemon=True,
    )
    api_thread.start()
    timestamp = _time.strftime("%H:%M:%S")
    print(f"[voice_control {timestamp}] Web interface at http://{config.host}:{config.port}", flush=True)
    return api_thread
