"""gsearch doctor — run diagnostic checks."""

from __future__ import annotations

import click
from rich.console import Console

from gsearch_mcp_cli.config import Config
from gsearch_mcp_cli.constants import CHROME_PROFILE_DIR
from gsearch_mcp_cli.core.browser import find_browser
from gsearch_mcp_cli.exceptions import BrowserNotFoundError

console = Console()

PASS = "[bold green]✓[/]"
FAIL = "[bold red]✗[/]"


def _check_browser() -> bool:
    try:
        path = find_browser()
        console.print(f"  {PASS} Browser found: {path}")
        return True
    except BrowserNotFoundError as exc:
        console.print(f"  {FAIL} Browser not found: {exc}")
        return False


def _check_profile_dir() -> bool:
    if CHROME_PROFILE_DIR.exists():
        console.print(f"  {PASS} Profile directory exists: {CHROME_PROFILE_DIR}")
        return True
    console.print(f"  {FAIL} Profile directory missing: {CHROME_PROFILE_DIR}")
    return False


def _check_warmed_up() -> bool:
    marker = CHROME_PROFILE_DIR / ".warmed_up"
    if marker.exists():
        console.print(f"  {PASS} Profile is warmed up")
        return True
    console.print(f"  {FAIL} Profile not warmed up — run: gsearch setup")
    return False


def _check_config() -> bool:
    try:
        cfg = Config()
        cfg.show()
        console.print(f"  {PASS} Config file valid")
        return True
    except Exception as exc:
        console.print(f"  {FAIL} Config error: {exc}")
        return False


@click.command("doctor")
def doctor_cmd() -> None:
    """Run diagnostic checks on gsearch environment."""
    console.print("[bold]Running diagnostics…[/]\n")

    checks = [
        ("Browser", _check_browser),
        ("Profile directory", _check_profile_dir),
        ("Profile warmup", _check_warmed_up),
        ("Configuration", _check_config),
    ]

    passed = sum(1 for _, fn in checks if fn())
    total = len(checks)

    console.print()
    if passed == total:
        console.print(f"[bold green]All {total} checks passed.[/]")
    else:
        console.print(f"[bold yellow]{passed}/{total} checks passed.[/]")
        raise SystemExit(1)
