"""nikame doctor — Diagnostic tool for NIKAME project health.

Verifies infrastructure status, migrations, credentials, and API health.
Provides actionable fix commands on failure.
"""

from __future__ import annotations

import subprocess
from pathlib import Path

import click
import httpx

from nikame.utils.logger import console


@click.command()
@click.option(
    "--project-dir",
    type=click.Path(exists=True, path_type=Path),
    default=Path("."),
    help="Project directory to diagnose.",
)
def doctor(project_dir: Path) -> None:
    """Run deep diagnostics on the current NIKAME project."""
    console.print("[info]🏥 NIKAME Doctor is diagnosing your project...[/info]\n")

    # 1. Project Structure
    if not (project_dir / "app").exists():
        console.print("[error]✗ Error: 'app/' directory not found. Please run this command from the project root.[/error]")
        raise SystemExit(1)
    console.print("[success]✓ Project structure: OK[/success]")

    # 2. Docker Compose Status
    _check_infra(project_dir)

    # 3. API Health
    _check_api_health()

    # 4. Git Status
    if (project_dir / ".git").exists():
        console.print("[success]✓ Git initialized[/success]")
    else:
        console.print("[warning]⚠ Git not initialized[/warning]")
        console.print("[dim]  Fix: git init && git add . && git commit -m 'Initial commit'[/dim]")

    console.print("\n[success]✨ Diagnostics complete! ✨[/success]")


def _check_infra(project_dir: Path) -> None:
    """Check if docker-compose services are running and healthy."""
    compose_file = project_dir / "infra" / "docker-compose.yml"
    if not compose_file.exists():
        console.print("[error]✗ Error: infra/docker-compose.yml not found.[/error]")
        return

    try:
        result = subprocess.run(
            ["docker", "compose", "-f", str(compose_file), "ps", "--format", "json"],
            capture_output=True,
            text=True,
            check=True
        )
        import json
        services = json.loads(result.stdout) if result.stdout.strip() else []
        
        if not services:
            console.print("[error]✗ No services are running.[/error]")
            console.print("[dim]  Fix: nikame up[/dim]")
            return

        for svc in services:
            status = svc.get("Status", "").lower()
            name = svc.get("Service", "Unknown")
            if "running" in status or "up" in status:
                console.print(f"[success]✓ Service '{name}': {status}[/success]")
            else:
                console.print(f"[error]✗ Service '{name}': {status}[/error]")
                console.print(f"[dim]  Fix: docker compose -f {compose_file} logs {name}[/dim]")

    except Exception as e:
        console.print(f"[error]✗ Failed to check Docker status: {e}[/error]")


def _check_api_health() -> None:
    """Check API /health endpoint."""
    health_url = "http://localhost:8000/health"
    try:
        response = httpx.get(health_url, timeout=5.0)
        if response.status_code == 200:
            console.print(f"[success]✓ API Health: OK ({response.status_code})[/success]")
        else:
            console.print(f"[error]✗ API Health: Failed ({response.status_code})[/error]")
            console.print(f"[dim]  Response: {response.text}[/dim]")
    except Exception as e:
        console.print("[error]✗ API unreachable (localhost:8000/health)[/error]")
        console.print(f"[dim]  Error: {e}[/dim]")
