"""CLI command for updating model pricing from litellm."""

from __future__ import annotations

import sys

import click

from robot_resources.routing.pricing_updater import (
    PricingFetchError,
    apply_update,
)


@click.command("update-pricing")
@click.option("--dry-run", is_flag=True, help="Show changes without writing to disk.")
@click.option("--force", is_flag=True, help="Bypass cooldown check.")
def update_pricing(dry_run: bool, force: bool) -> None:
    """Update model pricing from the litellm community database."""
    try:
        result = apply_update(dry_run=dry_run, force=force)
    except PricingFetchError as exc:
        click.echo(f"Error: {exc}", err=True)
        sys.exit(1)

    if result.cooldown_remaining is not None:
        elapsed = int(300 - result.cooldown_remaining)
        click.echo(f"Cooldown active. Last fetch was {elapsed}s ago. Use --force to override.")
        return

    if not result.changes:
        click.echo("Pricing is up to date — no changes needed.")
        return

    # Print changes table
    click.echo(f"{'Model':<35} {'Field':<22} {'Old':>12} {'New':>12}")
    click.echo("-" * 83)
    for ch in result.changes:
        click.echo(
            f"{ch.model_name:<35} {ch.field:<22} {ch.old_value:>12.6f} {ch.new_value:>12.6f}"
        )

    if result.skipped:
        click.echo(f"\nSkipped (not in litellm): {', '.join(result.skipped)}")

    action = "Dry run — no changes written." if dry_run else "Written to models_db.json."
    click.echo(f"\n{len(result.changes)} change(s). {action}")
