"""Main proxy server for Robot Resources."""

from fastapi import Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware

from robot_resources.config import get_settings
from robot_resources.proxy.handlers.completions import router as completions_router
from robot_resources.proxy.security import verify_api_key

app = FastAPI(
    title="Robot Resources",
    description="AI Execution Intelligence Layer - Intelligent LLM cost optimization",
    version="2.0.0",
)


# ---------------------------------------------------------------------------
# CORS configuration (read once at startup)
# ---------------------------------------------------------------------------

_settings = get_settings()
_cors_origins = _settings.router_cors_origins.strip()

if _cors_origins == "*":
    # Explicit opt-in: allow all origins.
    # Note: credentials cannot be used with wildcard origins (browser spec).
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=False,
        allow_methods=["*"],
        allow_headers=["*"],
    )
elif _cors_origins:
    # Specific origins (comma-separated)
    origins = [o.strip() for o in _cors_origins.split(",") if o.strip()]
    app.add_middleware(
        CORSMiddleware,
        allow_origins=origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
else:
    # Default: localhost only (any port).
    # Regex anchors prevent bypass via localhost.evil.com.
    app.add_middleware(
        CORSMiddleware,
        allow_origin_regex=r"^https?://localhost(:\d+)?$",
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )


# ---------------------------------------------------------------------------
# Public endpoints (no auth)
# ---------------------------------------------------------------------------


@app.get("/health")
async def health() -> dict:
    """Health check endpoint — always public for load balancers and probes."""
    return {"status": "healthy", "version": "2.0.0"}


# ---------------------------------------------------------------------------
# Protected endpoints (auth required when ROUTER_API_KEY is set)
# ---------------------------------------------------------------------------


@app.get("/v1/models", dependencies=[Depends(verify_api_key)])
async def list_models() -> dict:
    """List available models."""
    return {
        "object": "list",
        "data": [
            {"id": "auto", "object": "model", "owned_by": "robot-resources"},
        ],
    }


# Completions router — protected with auth dependency
app.include_router(
    completions_router,
    dependencies=[Depends(verify_api_key)],
)
