"""bilge update command - self-update BilgeAI."""

from __future__ import annotations

import logging
import subprocess
import sys

import typer
from rich.console import Console

from bilgeai import __version__

logger = logging.getLogger(__name__)
console = Console()


def _get_latest_version() -> str | None:
    """Fetch the latest version from PyPI."""
    try:
        import json
        from urllib.request import urlopen

        with urlopen("https://pypi.org/pypi/bilgeai/json", timeout=10) as resp:
            data = json.loads(resp.read().decode())
            return data["info"]["version"]
    except Exception:
        logger.debug("Failed to fetch latest version from PyPI", exc_info=True)
        return None


def _run_pip_install(version: str | None = None) -> bool:
    """Run pip install to update bilgeai."""
    target = f"bilgeai=={version}" if version else "bilgeai --upgrade"
    cmd = [sys.executable, "-m", "pip", "install", target, "--quiet"]
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
        return result.returncode == 0
    except Exception:
        logger.debug("pip install failed", exc_info=True)
        return False


def update_command(
    check: bool = typer.Option(
        False,
        "--check",
        help="Only check for updates, don't install.",
    ),
    force: bool = typer.Option(
        False,
        "--force",
        help="Force reinstall even if already on latest.",
    ),
) -> None:
    """Check for updates and upgrade BilgeAI."""
    console.print(f"[bold]Current version:[/bold] {__version__}")

    with console.status("Checking for updates..."):
        latest = _get_latest_version()

    if latest is None:
        console.print(
            "[yellow]Could not check for updates.[/yellow] "
            "Check your internet connection or visit https://pypi.org/project/bilgeai/"
        )
        raise typer.Exit(1)

    console.print(f"[bold]Latest version:[/bold]  {latest}")

    if latest == __version__ and not force:
        console.print("[green]You are already on the latest version.[/green]")
        return

    if latest != __version__:
        console.print(f"[cyan]Update available: {__version__} → {latest}[/cyan]")

    if check:
        return

    if not force and latest == __version__:
        return

    with console.status(f"Upgrading to {latest}..."):
        success = _run_pip_install(latest if latest != __version__ else None)

    if success:
        console.print(f"[green]Successfully updated to {latest}![/green]")
        console.print("Restart your terminal to use the new version.")
    else:
        console.print(
            f"[red]Update failed.[/red] Try manually: [bold]pip install bilgeai=={latest}[/bold]"
        )
        raise typer.Exit(1)
