"""Cost and tool endpoints for dashboard API."""
from __future__ import annotations

from fastapi import APIRouter

from proxym.dashboard._shared import shared_accounts as _accounts

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


# ── Cost endpoints ───────────────────────────────────────────

@router.get("/costs")
async def cost_summary():
    """Aggregate cost dashboard across all accounts."""
    return _accounts().get_cost_summary()


@router.get("/costs/detailed")
async def cost_detailed():
    """Per-account cost breakdown."""
    mgr = _accounts()
    accounts = mgr.list_accounts()
    rows = []
    for a in accounts:
        rows.append({
            "id": a.id,
            "name": a.name,
            "provider": a.provider.value,
            "plan": a.plan_tier,
            "daily_cost": round(a.usage.daily_cost_usd, 4),
            "monthly_cost": round(a.usage.total_cost_usd, 4),
            "daily_requests": a.usage.daily_requests,
            "total_requests": a.usage.total_requests,
            "budget": a.limits.budget_remaining(a.usage),
            "over_budget": a.is_over_budget,
        })
    return {"accounts": rows, "summary": mgr.get_cost_summary()}


# ── Tool profiles ────────────────────────────────────────────

@router.get("/tools")
async def list_tools():
    """Return available VM tool profiles (host/browser environments)."""
    from proxym.virt.profiles import list_builtin_profiles, get_builtin_profile, PROFILES_DIR
    import yaml

    tools = []
    for name in list_builtin_profiles():
        profile_path = get_builtin_profile(name)
        info = {"name": name, "profile_exists": profile_path is not None}
        if profile_path:
            try:
                data = yaml.safe_load(profile_path.read_text())
                info["memory"] = data.get("memory", 4096)
                info["vcpus"] = data.get("vcpus", 2)
                info["base_image"] = data.get("base_image", "ubuntu-24.04")
                info["gui"] = data.get("gui", False)
                info["apps"] = data.get("apps", [])
                info["packages"] = len(data.get("packages", []))
            except Exception:
                pass
        tools.append(info)
    return {"tools": tools}
