"""ievo update — update agent(s) to latest marketplace version."""

from __future__ import annotations

import asyncio
from pathlib import Path

import typer

from ievo.core.config import require_project
from ievo.core.project import ProjectManifest
from ievo.core.registry import Registry
from ievo.utils.console import error, info, step, success, warn


def update(
    agent: str | None = typer.Argument(default=None, help="Agent to update (all if omitted)."),
) -> None:
    """Update agent(s) to the latest marketplace version."""
    root = require_project()
    manifest = ProjectManifest.load(root)

    if agent and not manifest.has_agent(agent):
        error(f"Agent [bold]{agent}[/bold] is not installed.")
        raise typer.Exit(1)

    agents_to_update = [agent] if agent else list(manifest.agents.keys())

    asyncio.run(_update_agents(root, manifest, agents_to_update))


async def _update_agents(root: Path, manifest: ProjectManifest, agents: list[str]) -> None:
    registry = Registry.load_cached()
    await registry.fetch()

    updated = 0

    for name in agents:
        current = manifest.agents.get(name, "0.0.0")
        entry = registry.get(name)

        if not entry:
            warn(f"{name} — not found in marketplace, skipping.")
            continue

        if entry.version == current:
            step(f"{name}@{current} — already up to date")
            continue

        info(f"Updating {name}: {current} → {entry.version}...")
        dest = root / "agents" / name
        await registry.download_agent(name, dest)
        manifest.add_agent(name, entry.version)
        success(f"{name}@{entry.version}")
        updated += 1

    if updated > 0:
        manifest.save(root)
        success(f"{updated} agent(s) updated.")
    else:
        info("Everything up to date.")
