"""Account endpoints for dashboard API."""
from __future__ import annotations

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

from proxym.accounts import (
    Account,
    AccountCredentials,
    AccountLimits,
    AccountManager,
    ProviderType,
    ToolBinding,
    ToolType,
)
from proxym.storage import DEFAULT_SQLITE_PATH

router = APIRouter(prefix="/accounts", tags=["accounts"])

# Singleton
_acct_mgr: AccountManager | None = None


def _accounts() -> AccountManager:
    global _acct_mgr
    if _acct_mgr is None:
        _acct_mgr = AccountManager(config_path=DEFAULT_SQLITE_PATH)
    return _acct_mgr


# ── Pydantic models ──────────────────────────────────────────

class CreateAccountReq(BaseModel):
    name: str
    provider: str
    email: str = ""
    plan_tier: str = ""
    api_key: str = ""
    tags: list[str] = []
    daily_budget_usd: float = 0
    monthly_budget_usd: float = 0


class BindToolReq(BaseModel):
    tool_type: str
    tool_name: str
    vm_id: str = ""
    project_path: str = ""
    browser_profile: str = ""


# ── Endpoints ─────────────────────────────────────────────────

@router.get("")
async def list_accounts(provider: str | None = None, tag: str | None = None):
    mgr = _accounts()
    prov = ProviderType(provider) if provider else None
    accts = mgr.list_accounts(provider=prov, tag=tag)
    return {"accounts": [a.status_summary() for a in accts]}


@router.post("")
async def create_account(req: CreateAccountReq):
    mgr = _accounts()
    acct = Account(
        name=req.name,
        provider=ProviderType(req.provider),
        email=req.email,
        plan_tier=req.plan_tier,
        credentials=AccountCredentials(api_key=req.api_key),
        limits=AccountLimits(
            user_daily_budget_usd=req.daily_budget_usd,
            user_monthly_budget_usd=req.monthly_budget_usd,
        ),
        tags=req.tags,
    )
    mgr.add_account(acct)
    return acct.status_summary()


@router.get("/{account_id}")
async def get_account(account_id: str):
    acct = _accounts().get_account(account_id)
    if not acct:
        raise HTTPException(404, "Account not found")
    return acct.status_summary()


@router.delete("/{account_id}")
async def delete_account(account_id: str):
    if _accounts().remove_account(account_id):
        return {"ok": True}
    raise HTTPException(404, "Account not found")


@router.post("/{account_id}/bind-tool")
async def bind_tool(account_id: str, req: BindToolReq):
    binding = ToolBinding(
        tool_type=ToolType(req.tool_type),
        tool_name=req.tool_name,
        vm_id=req.vm_id,
        project_path=req.project_path,
        browser_profile=req.browser_profile,
    )
    if _accounts().bind_tool(account_id, binding):
        return {"ok": True}
    raise HTTPException(404, "Account not found")
