# src/dattos_cli/commands/doctor.py
from __future__ import annotations

import httpx
import typer

from dattos_cli import __version__
from dattos_cli.config import ConfigError, get_config, get_active_profile

app = typer.Typer(help="Diagnose configuration and connectivity.", invoke_without_command=True)


def _make_http_client() -> httpx.Client:
    return httpx.Client(timeout=10, follow_redirects=False)


def _check(label: str, ok: bool, detail: str = "") -> bool:
    status = "OK" if ok else "FAIL"
    msg = f"  {status:>4}  {label}"
    if detail:
        msg += f"  ({detail})"
    typer.echo(msg)
    return ok


def _warn(label: str, detail: str = "") -> None:
    msg = f"  WARN  {label}"
    if detail:
        msg += f"  ({detail})"
    typer.echo(msg)


@app.callback(invoke_without_command=True)
def doctor():
    """Run diagnostic checks on configuration and connectivity."""
    typer.echo()
    typer.echo(f"  dattos-cli v{__version__}")
    typer.echo(f"  profile: {get_active_profile()}")
    typer.echo()

    failed = False

    # 1. Config
    try:
        cfg = get_config()
        _check("Config", True, cfg.api_url)
    except ConfigError as e:
        _check("Config", False, str(e))
        raise typer.Exit(1)

    # 2. Connectivity
    http = _make_http_client()
    try:
        resp = http.get(
            f"{cfg.api_url}/api/User",
            headers={
                "Authorization": f"Bearer {cfg.api_key}",
                "accept": "application/json",
            },
            params={"pageInfo.page": 0, "pageInfo.pageSize": 1},
        )
    except httpx.ConnectError:
        _check("API reachable", False, "connection refused")
        raise typer.Exit(1)
    except httpx.TimeoutException:
        _check("API reachable", False, "timeout")
        raise typer.Exit(1)

    ct = resp.headers.get("content-type", "")
    if "application/json" not in ct and resp.status_code not in (401, 403):
        _check("API reachable", False, f"not a Dattos API (got {ct or 'non-JSON'}) — check URL")
        raise typer.Exit(1)

    _check("API reachable", True)

    # 3. Auth
    if resp.status_code == 401:
        _check("Auth", False, "invalid API key")
        failed = True
    elif resp.status_code == 403:
        _check("Auth", False, "forbidden — check permissions")
        failed = True
    elif resp.status_code >= 400:
        _check("Auth", False, f"HTTP {resp.status_code}")
        failed = True
    else:
        _check("Auth", True)

    # 4. Auth method
    from dattos_cli.credentials import get_secret
    session = get_secret(get_active_profile(), "session_token")
    if session:
        _check("Auth method", True, "session token")
    else:
        _check("Auth method", True, "API key")

    # 5. Folder
    if cfg.folder_id:
        _check("Folder", True, f"{cfg.folder_name or cfg.folder_id}")
    else:
        _warn("Folder", "no folder selected — run: dattos folders select")

    typer.echo()
    if failed:
        raise typer.Exit(1)
