"""Frontend-serving endpoints: dashboard UI, JSX, JS, config — extracted from main.py."""

from __future__ import annotations

import os

import structlog
from fastapi import APIRouter, Request
from fastapi.responses import Response

from proxym.config import get_settings

logger = structlog.get_logger()

router = APIRouter()

_HERE = os.path.dirname(os.path.abspath(__file__))
_SRC_ROOT = os.path.dirname(_HERE)  # src/proxym/
_MIME_JS = "text/javascript"
_MIME_JS_UTF8 = "text/javascript; charset=utf-8"


def _serve_file(paths: list[str], media_type: str, charset_header: str | None = None) -> Response:
    """Try paths in order; return content from first found file."""
    for file_path in paths:
        try:
            with open(file_path, "r") as f:
                content = f.read()
            headers = {"Content-Type": charset_header} if charset_header else {}
            return Response(content=content, media_type=media_type, headers=headers)
        except FileNotFoundError:
            continue
        except Exception as e:
            logger.error("serve_file_error", error=str(e), path=file_path)
            continue
    logger.error("serve_file_not_found", paths=paths)
    return Response(content="// file not found", media_type=media_type, status_code=404)


@router.get("/dashboard-ui")
async def dashboard_ui():
    """Serve the React dashboard UI."""
    paths = [
        "frontend/dashboard.html",
        "/app/frontend/dashboard.html",
    ]
    resp = _serve_file(paths, "text/html", "text/html; charset=utf-8")
    if resp.status_code == 404:
        return Response(
            content="<h1>Dashboard Error</h1><p>Could not load dashboard: HTML file not found</p>",
            status_code=500,
            media_type="text/html",
        )
    return resp


@router.get("/dashboard-hook.js")
async def dashboard_hook_js():
    """Serve the useDashboardData hook (plain JS, no Babel needed)."""
    return _serve_file(
        [os.path.join(_SRC_ROOT, "dashboard", "hooks", "useDashboardData.js")],
        _MIME_JS, _MIME_JS_UTF8,
    )


@router.get("/dashboard-api.js")
async def dashboard_api_js():
    """Serve the dashboard API client (plain JS, no Babel needed)."""
    return _serve_file(
        [os.path.join(_SRC_ROOT, "dashboard", "api.js")],
        _MIME_JS, _MIME_JS_UTF8,
    )


@router.get("/proxym-dashboard.jsx")
async def dashboard_jsx():
    """Serve the React dashboard JSX file."""
    return _serve_file(
        [
            os.path.join(_SRC_ROOT, "dashboard", "panel.jsx"),
            "frontend/proxym-dashboard.jsx",
            "/app/frontend/proxym-dashboard.jsx",
        ],
        _MIME_JS, _MIME_JS_UTF8,
    )


@router.get("/config")
async def get_frontend_config(request: Request):
    """Return configuration for frontend."""
    settings = get_settings()
    
    # Use Host header to get the actual port
    host_header = request.headers.get("host", "localhost:4000")
    if ":" in host_header:
        host, port = host_header.split(":")
        scheme = request.url.scheme
    else:
        host = host_header
        port = settings.port
        scheme = "http"
    
    api_url = f"{scheme}://{host}:{port}"
    
    return {
        "api_url": api_url,
        "api_key": settings.master_key,
        "debug": settings.debug,
        "dashboard_api_url": settings.dashboard_api_url,
        "default_proxy_url": settings.default_proxy_url,
        "monthly_budget_usd": settings.monthly_budget_usd,
        "daily_budget_usd": settings.daily_budget_usd,
        "max_request_cost_usd": settings.max_request_cost_usd,
        "available_providers": list(settings.available_providers().keys()),
        "redis_url": settings.redis_url,
        "ollama_base_url": settings.ollama_base_url,
        "watch_dir": settings.watch_dir,
        "max_context_tokens": settings.max_context_tokens,
        "delta_threshold": settings.delta_threshold,
    }
