"""linear-canal update — Upgrade Linear Canal packages to the latest version."""

from __future__ import annotations

import subprocess
import sys

import click
from rich.console import Console

console = Console()

_PACKAGES = [
    "linear-canal-cli",
    "linear-canal-scout",
    "linear-canal-graph-engine",
    "linear-canal-context-compiler",
    "linear-canal-indexer",
    "linear-canal-api",
]


@click.command("update")
@click.pass_context
def update_cmd(ctx: click.Context) -> None:
    """Upgrade all Linear Canal packages to the latest version.

    Runs ``pip install --upgrade`` for every LC package so the CLI,
    indexer, and MCP server are always in sync.
    """
    console.print("[bold blue]Updating Linear Canal...[/bold blue]\n")

    console.print("[bold]Upgrading packages...[/bold]")
    for pkg in _PACKAGES:
        console.print(f"  Upgrading {pkg}...", end=" ")
        try:
            result = subprocess.run(
                [sys.executable, "-m", "pip", "install", "--upgrade", "--quiet", pkg],
                capture_output=True,
                text=True,
                timeout=120,
            )
            if result.returncode == 0:
                console.print("[green]✓[/green]")
            else:
                console.print(f"[yellow]⚠ {result.stderr.strip()[:60]}[/yellow]")
        except subprocess.TimeoutExpired:
            console.print("[yellow]⚠ timeout[/yellow]")
        except Exception as exc:
            console.print(f"[red]✗ {exc}[/red]")

    console.print("\n[green]✓ Update complete.[/green]")
    console.print("[dim]Restart any running MCP servers for changes to take effect.[/dim]")
