"""Action-first API surface used by the dashboard Voice tab.

The voice UI (ACTION_SCHEMA + tool-calling) expects a stable /api/v1/* surface
for common operations (VS Code control, VM actions, costs, logs, accounts).

Most of proxym's management endpoints already exist under /dashboard/*.
This module provides thin /api/v1 aliases so the voice UI can call them
without embedding dashboard-specific paths.
"""

from __future__ import annotations

from typing import Any

from fastapi import APIRouter

from proxym.dashboard import (
    cost_summary as _dashboard_cost_summary,
    get_logs as _dashboard_get_logs,
    list_accounts as _dashboard_list_accounts,
    list_vms as _dashboard_list_vms,
    snapshot_vm as _dashboard_snapshot_vm,
    start_vm as _dashboard_start_vm,
    stop_vm as _dashboard_stop_vm,
)

router = APIRouter(prefix="/api/v1", tags=["voice-actions"])


@router.get("/vms")
async def vms_list() -> dict[str, Any]:
    """List VMs (alias for GET /dashboard/vms)."""
    return await _dashboard_list_vms()


@router.post("/vms/{vm_id}/start")
async def vms_start(vm_id: str) -> dict[str, Any]:
    """Start VM (alias for POST /dashboard/vms/{vm_id}/start)."""
    return await _dashboard_start_vm(vm_id)


@router.post("/vms/{vm_id}/stop")
async def vms_stop(vm_id: str, force: bool = False) -> dict[str, Any]:
    """Stop VM (alias for POST /dashboard/vms/{vm_id}/stop)."""
    return await _dashboard_stop_vm(vm_id, force=force)


@router.post("/vms/{vm_id}/snapshot")
async def vms_snapshot(vm_id: str, name: str = "") -> dict[str, Any]:
    """Snapshot VM (alias for POST /dashboard/vms/{vm_id}/snapshot)."""
    return await _dashboard_snapshot_vm(vm_id, name=name)


@router.get("/accounts")
async def accounts_list(provider: str | None = None, tag: str | None = None) -> dict[str, Any]:
    """List accounts (alias for GET /dashboard/accounts)."""
    return await _dashboard_list_accounts(provider=provider, tag=tag)


@router.get("/dashboard/costs/summary")
async def dashboard_costs_summary() -> dict[str, Any]:
    """Cost summary used by voice UI.

    Returns both the canonical keys from /dashboard/costs and the shorter keys
    used by voice_fixed.jsx.
    """
    d = await _dashboard_cost_summary()
    return {
        **d,
        "daily_usd": d.get("daily_total_usd", 0),
        "monthly_usd": d.get("monthly_total_usd", 0),
    }


@router.get("/logs")
async def logs_list(lines: int = 50, level: str | None = None) -> dict[str, Any]:
    """Recent logs (alias for GET /dashboard/logs)."""
    return await _dashboard_get_logs(lines=lines, level=level)


@router.get("/tickets")
async def voice_tickets(status: str | None = None) -> dict[str, Any]:
    """List tickets — voice-friendly summary."""
    from proxym.dashboard._tickets_api import _tickets
    mgr = _tickets()
    from proxym.dashboard.tickets import TicketStatus
    st = TicketStatus(status) if status else None
    tickets = mgr.list_tickets(status=st)
    in_progress = sum(1 for t in tickets if t.status.value == "in_progress")
    return {
        "count": len(tickets),
        "summary": [
            {"id": t.id[:8], "title": t.title, "status": t.status.value}
            for t in tickets[:10]
        ],
        "speech": f"Masz {len(tickets)} ticketów" + (
            f", {in_progress} w trakcie" if in_progress else ""
        ),
    }


@router.get("/diagnose")
async def voice_diagnose() -> dict[str, Any]:
    """Run diagnostics — voice-friendly summary."""
    import httpx
    try:
        async with httpx.AsyncClient(timeout=15) as client:
            r = await client.get("http://localhost:4000/tests/status")
            data = r.json()
            passed = sum(1 for v in data.values() if isinstance(v, dict) and v.get("status") == "ok")
            failed = sum(1 for v in data.values() if isinstance(v, dict) and v.get("status") != "ok")
            return {
                "passed": passed,
                "failed": failed,
                "speech": f"Diagnostyka: {passed} testów przeszło, {failed} nie przeszło" if failed else f"Wszystkie {passed} testów przeszły",
            }
    except Exception as e:
        return {"error": str(e), "speech": "Nie mogę uruchomić diagnostyki"}
