"""Partner billing and prepaid credit endpoints."""

from __future__ import annotations

from typing import Annotated, Any

from fastapi import APIRouter, Depends
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field

from hive_compute.coordinator.auth import require_client_key
from hive_compute.coordinator.billing import add_partner_credits, get_partner_credit_balance
from hive_compute.coordinator.manager_auth import record_manager_action, require_manager_admin

router = APIRouter(tags=["billing"])

ClientAuth = Annotated[dict[str, Any], Depends(require_client_key)]
ManagerAdmin = Annotated[dict[str, Any], Depends(require_manager_admin)]


class CreditsTopUpRequest(BaseModel):
    partner_id: str = Field(min_length=1)
    amount_usd: float = Field(gt=0)


@router.get("/billing/balance")
def get_balance(auth: ClientAuth):
    partner_id = auth.get("partner_id")
    if not partner_id:
        return JSONResponse(status_code=403, content={"error": "Only partner API keys have billing balances"})

    credits_usd = get_partner_credit_balance(partner_id)
    return {"partner_id": partner_id, "credits_usd": round(float(credits_usd or 0.0), 2)}


@router.post("/billing/credits/add")
def add_credits(req: CreditsTopUpRequest, admin: ManagerAdmin):
    result = add_partner_credits(req.partner_id, req.amount_usd)
    if not result:
        return JSONResponse(status_code=404, content={"error": "Partner not found"})

    record_manager_action(
        admin,
        "partner_credits_add",
        f"partner_id={req.partner_id}, amount_usd={req.amount_usd:.2f}",
    )
    result["credits_usd"] = round(float(result["credits_usd"]), 2)
    return result
