"""
vr --update - Update the VoiceRun CLI to the latest version.
"""

import subprocess
import sys

from importlib.metadata import version

from vr_cli.utils.utils import (
    console,
    print_success,
    print_error,
    print_info,
)
from vr_cli.utils.config import get_setup_targets
from vr_cli.commands.setup import install_skills, install_mcp_server

PACKAGE_NAME = "voicerun-cli"


def get_current_version() -> str:
    """Get the currently installed version of voicerun-cli."""
    return version(PACKAGE_NAME)


def upgrade_package() -> str:
    """Upgrade voicerun-cli to the latest version from PyPI.

    Returns:
        "upgraded" if a new version was installed,
        "latest" if already on the latest version,
        "failed" if the upgrade failed.
    """
    old_version = get_current_version()
    print_info(f"Current version: {old_version}")
    print_info("Checking for updates...")

    try:
        result = subprocess.run(
            [sys.executable, "-m", "pip", "install", "--upgrade", PACKAGE_NAME],
            capture_output=True,
            text=True,
        )

        if result.returncode != 0:
            print_error(f"Failed to upgrade: {result.stderr.strip()}")
            return "failed"

        new_version = get_current_version()
        if new_version == old_version:
            print_success(f"Already on the latest version ({old_version})")
            return "latest"

        print_success(f"voicerun-cli upgraded from {old_version} to {new_version}")
        return "upgraded"

    except Exception as e:
        print_error(f"Failed to upgrade: {e}")
        return "failed"


def run_update() -> None:
    """Run the full update: upgrade package, reinstall skills, refresh MCP."""
    console.print("[bold]Updating VoiceRun CLI...[/bold]")
    console.print()

    # Step 1: Upgrade the package
    console.print("[bold]1. Upgrading voicerun-cli[/bold]")
    status = upgrade_package()
    if status == "failed":
        return

    console.print()

    # Read targets persisted by vr setup
    setup_targets = get_setup_targets()
    skill_targets = setup_targets.get("skills", [])
    mcp_targets = setup_targets.get("mcp", [])

    if not skill_targets and not mcp_targets:
        print_info("No setup targets configured. Run 'vr setup' first to configure skills and MCP.")
        console.print()
        print_success("Update complete!")
        return

    # Step 2: Reinstall skills to previously configured targets
    console.print("[bold]2. Reinstalling skills[/bold]")
    if skill_targets:
        install_skills(skill_targets)
    else:
        print_info("No skill targets were configured during setup, skipping")

    console.print()

    # Step 3: Refresh MCP configuration for previously configured targets
    console.print("[bold]3. Refreshing MCP configuration[/bold]")
    if mcp_targets:
        install_mcp_server(mcp_targets)
    else:
        print_info("No MCP targets were configured during setup, skipping")

    console.print()
    print_success("Update complete!")
