"""System status, providers, logs, and projects endpoints for dashboard API."""
from __future__ import annotations

from pathlib import Path

from fastapi import APIRouter

from proxym.accounts import AccountManager
from proxym.config import get_settings
from proxym.providers import MODELS
from proxym.virt import VMOrchestrator
from proxym.dashboard._accounts import _accounts as _shared_accounts

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

# Singletons
_acct_mgr: AccountManager | None = None
_vm_orch: VMOrchestrator | None = None


def _accounts() -> AccountManager:
    global _acct_mgr
    if _acct_mgr is not None:
        return _acct_mgr
    return _shared_accounts()


def _vms() -> VMOrchestrator:
    global _vm_orch
    if _vm_orch is None:
        _vm_orch = VMOrchestrator()
    return _vm_orch


# ── System status ────────────────────────────────────────────

@router.get("/")
async def dashboard_root():
    """Dashboard root - redirects to system status."""
    return await system_status()


@router.get("/system")
async def system_status():
    """Full system overview: accounts + VMs + costs + libvirt + providers + watchdog + repair."""
    settings = get_settings()
    libvirt = VMOrchestrator.check_libvirt_available()
    configured = settings.available_providers()

    # Watchdog status
    from proxym.observability.health_events import get_health_store
    store = get_health_store()
    active_events = store.get_active()
    watchdog_status = {
        "enabled": settings.watchdog_enabled,
        "interval_s": settings.watchdog_interval,
        "active_alerts": len(active_events),
        "alerts": [
            {"source": e.source, "severity": e.severity.value, "title": e.title,
             "detail": e.detail, "since": e.timestamp}
            for e in active_events
        ],
    }

    # Repair agent status
    repair_status = {
        "enabled": settings.repair_enabled,
        "mode": settings.repair_mode,
        "has_api_key": bool(settings.repair_api_key or settings.openrouter_api_key),
        "budget_daily_usd": settings.repair_budget_daily,
    }

    # Tool executor status
    try:
        from proxym.tools.executor import ToolExecutor
        executor = ToolExecutor.get()
        executor_status = executor.queue_summary()
    except Exception:
        executor_status = {"running": False, "error": "not initialized"}

    return {
        "accounts": _accounts().get_cost_summary(),
        "vms": {
            "total": len(_vms().vms),
            "running": sum(1 for v in _vms().vms.values() if v.state.value == "running"),
        },
        "libvirt": libvirt,
        "providers": {
            "configured": list(configured.keys()),
            "total_models": sum(
                1 for m in MODELS.values() if m.provider in configured
            ),
        },
        "watchdog": watchdog_status,
        "repair": repair_status,
        "executor": executor_status,
    }


@router.get("/providers")
async def list_providers():
    """Show configured providers from .env and their model counts."""
    settings = get_settings()
    configured = settings.available_providers()
    providers = []
    for name, key in configured.items():
        model_count = sum(1 for m in MODELS.values() if m.provider == name)
        # Ollama doesn't require API key (local service)
        is_active = name == "ollama" or (name != "ollama" and bool(key))
        providers.append({
            "name": name,
            "configured": True,
            "has_key": is_active,
            "model_count": model_count,
        })
    return {"providers": providers}


@router.get("/logs")
async def get_logs(lines: int = 50, level: str | None = None):
    """Get recent log entries from proxym log file."""
    import time

    log_paths = [
        Path.home() / ".local/share/proxym/proxym.log",
        Path("/var/log/proxym/proxym.log"),
        Path("./proxym.log"),
    ]

    log_file = None
    for p in log_paths:
        if p.exists():
            log_file = p
            break

    if not log_file:
        return {"logs": [], "error": "No log file found"}

    try:
        with open(log_file, "r") as f:
            all_lines = f.readlines()

        # Get last N lines
        recent = all_lines[-lines:]

        logs = []
        for line in recent:
            line = line.strip()
            if not line:
                continue

            # Parse structured log lines (timestamp level message)
            parts = line.split(" ", 2)
            if len(parts) >= 2:
                timestamp = parts[0] if len(parts) > 0 else ""
                log_level = parts[1] if len(parts) > 1 else "INFO"
                message = parts[2] if len(parts) > 2 else line
            else:
                timestamp = time.strftime("%Y-%m-%dT%H:%M:%S")
                log_level = "INFO"
                message = line

            # Filter by level if specified
            if level and log_level.upper() != level.upper():
                continue

            logs.append({
                "timestamp": timestamp,
                "level": log_level.upper(),
                "message": message,
            })

        return {"logs": logs[-lines:], "source": str(log_file)}
    except Exception as e:
        return {"logs": [], "error": str(e)}
