from __future__ import annotations

import os
import sys
import time
from typing import Any

from fastapi.responses import JSONResponse


def register_health_diagnostics_routes(
    fastapi_app: Any,
    *,
    delegate: Any,
    mesh_manager: Any,
    process_start_ts: float,
) -> None:
    """Mount ``/health``, ``/diagnostics``, and ``/diagnostics/doctor`` on *fastapi_app*.

    Auth: only ``/health`` is exempt from global auth (see ``app_http_routes``).
    """

    @fastapi_app.get("/health")
    async def health():
        try:
            queue_depth = int(getattr(mesh_manager.queue.queue, "qsize", lambda: 0)())
        except Exception:
            queue_depth = 0
        try:
            # HeadlessDelegate tracks in-flight agent work via _running_thread_ids; legacy UI used _agent_threads.
            _threads = getattr(delegate, "_agent_threads", None)
            if _threads is not None:
                agent_active = len(_threads)
            else:
                agent_active = len(getattr(delegate, "_running_thread_ids", set()) or set())
        except Exception:
            agent_active = 0
        return JSONResponse(
            content={
                "ok": True,
                "version": "1",
                "uptime_seconds": max(0.0, time.time() - process_start_ts),
                "mesh": {
                    "started": bool(getattr(mesh_manager, "_started", False)),
                    "active_sessions": len(mesh_manager.list_sessions()),
                    "queue_depth": queue_depth,
                },
                "active_sessions": agent_active,
                "venv_health": os.path.isfile(sys.executable),
            }
        )

    @fastapi_app.get("/diagnostics")
    async def diagnostics_route():
        import asyncio

        from diagnostics import run_diagnostics

        try:
            result = await asyncio.get_event_loop().run_in_executor(None, run_diagnostics)
            return JSONResponse(content=result)
        except Exception as exc:
            return JSONResponse(content={"ok": False, "error": str(exc)}, status_code=500)

    @fastapi_app.get("/diagnostics/doctor")
    async def doctor_route():
        import asyncio

        from diagnostics import build_doctor_report

        try:
            report = await asyncio.get_event_loop().run_in_executor(None, build_doctor_report)
            return JSONResponse(content=report)
        except Exception as exc:
            return JSONResponse(content={"ok": False, "error": str(exc)}, status_code=500)
