"""Admin API endpoints for configuration and quota management."""

from __future__ import annotations

from typing import Optional

from fastapi import APIRouter
from pydantic import BaseModel, Field

from radix_edge.db import get_db
from radix_edge.enforcer.admission import get_user_quota, set_user_quota
from radix_edge.enforcer.fairness import get_user_usage, get_all_user_usage
from radix_edge.models import BrainParams

router = APIRouter(prefix="/v1/config", tags=["admin"])


# --- Quota management ---

class QuotaUpdateRequest(BaseModel):
    max_concurrent_gpu_jobs: Optional[int] = Field(None, ge=1, le=100)
    max_gpus_total: Optional[int] = Field(None, ge=1, le=256)
    fair_share_weight: Optional[float] = Field(None, ge=0.01, le=100.0)


@router.get("/quotas/{user_id}")
async def get_quota(user_id: str):
    """Get quota settings for a user."""
    return get_user_quota(user_id)


@router.put("/quotas/{user_id}")
async def update_quota(user_id: str, req: QuotaUpdateRequest):
    """Update quota settings for a user."""
    set_user_quota(
        user_id,
        max_concurrent=req.max_concurrent_gpu_jobs,
        max_gpus=req.max_gpus_total,
        fair_share_weight=req.fair_share_weight,
    )
    return get_user_quota(user_id)


@router.get("/users")
async def list_users():
    """List all users with quotas and usage."""
    with get_db() as db:
        quotas = db.execute("SELECT * FROM user_quotas ORDER BY user_id").fetchall()
        usage = get_all_user_usage(hours=24, db_conn=db)
        usage_map = {u["user_id"]: u for u in usage}

        result = []
        for q in quotas:
            u = usage_map.get(q["user_id"], {"gpu_seconds": 0, "job_count": 0})
            result.append({
                "user_id": q["user_id"],
                "max_concurrent_gpu_jobs": q["max_concurrent_gpu_jobs"],
                "max_gpus_total": q["max_gpus_total"],
                "fair_share_weight": q["fair_share_weight"],
                "gpu_seconds_24h": u["gpu_seconds"],
                "job_count_24h": u["job_count"],
            })

        return {"users": result}


# --- Brain params ---

@router.get("/brain")
async def get_brain_params():
    """Get current brain scheduling weights."""
    with get_db() as db:
        row = db.execute("SELECT * FROM brain_params WHERE key = 'current'").fetchone()
        if not row:
            return {}
        return BrainParams.from_row(row).to_dict()


@router.get("/usage/{user_id}")
async def get_usage(user_id: str, hours: int = 24):
    """Get resource usage for a user."""
    return get_user_usage(user_id, hours=hours)
