"""releaseops env — Manage environments and bundle mappings."""

from typing import Optional

import typer
import yaml

from llmhq_releaseops.core.resolver import Resolver
from llmhq_releaseops.storage.git_store import GitStore

app = typer.Typer(help="Manage environments and bundle mappings.")


def _get_resolver(path: str = ".") -> Resolver:
    store = GitStore(path)
    if not store.is_initialized():
        typer.echo("Error: ReleaseOps not initialized. Run 'releaseops init' first.", err=True)
        raise typer.Exit(1)
    return Resolver(store)


@app.command("list")
def list_envs(
    path: str = typer.Option(".", "--path", help="Repository root path"),
):
    """Show all environments and their current bundle mappings."""
    resolver = _get_resolver(path)
    for env_name in resolver.list_environments():
        mappings = resolver.resolve_all(env_name)
        if mappings:
            typer.echo(f"{env_name}:")
            for bundle_id, version in sorted(mappings.items()):
                typer.echo(f"  {bundle_id} → {version}")
        else:
            typer.echo(f"{env_name}: (no bundles)")


@app.command()
def get(
    env_name: str = typer.Argument(..., help="Environment name"),
    path: str = typer.Option(".", "--path", help="Repository root path"),
):
    """Show detailed environment configuration."""
    resolver = _get_resolver(path)
    try:
        env = resolver.get_environment(env_name)
        typer.echo(yaml.dump(env.to_dict(), default_flow_style=False, sort_keys=False))
    except FileNotFoundError:
        typer.echo(f"Environment '{env_name}' not found.", err=True)
        raise typer.Exit(1)


@app.command("set")
def set_version(
    env_name: str = typer.Argument(..., help="Environment name"),
    bundle_id: str = typer.Argument(..., help="Bundle ID"),
    version: str = typer.Argument(..., help="Version to set"),
    force: bool = typer.Option(False, "--force", help="Skip validation"),
    path: str = typer.Option(".", "--path", help="Repository root path"),
):
    """Directly set a bundle version in an environment (low-level, bypasses gates)."""
    resolver = _get_resolver(path)
    try:
        resolver.set_version(env_name, bundle_id, version, updated_by="cli")
        typer.echo(f"Set {bundle_id}={version} in {env_name}")
    except FileNotFoundError as e:
        typer.echo(f"Error: {e}", err=True)
        raise typer.Exit(1)


@app.command()
def history(
    env_name: str = typer.Argument(..., help="Environment name"),
    limit: int = typer.Option(10, "--limit", "-n", help="Max records to show"),
    path: str = typer.Option(".", "--path", help="Repository root path"),
):
    """Show promotion history for an environment."""
    store = GitStore(path)
    if not store.is_initialized():
        typer.echo("Error: ReleaseOps not initialized.", err=True)
        raise typer.Exit(1)

    promo_history = store.load_promotion_history()
    records = promo_history.get_history(env=env_name, limit=limit)

    if not records:
        typer.echo(f"No promotion history for '{env_name}'.")
        return

    for record in records:
        prefix = "ROLLBACK" if record.is_rollback else record.state.value
        typer.echo(
            f"  [{prefix}] {record.bundle_id} v{record.version} "
            f"→ {record.to_env} by {record.promoted_by} at {record.timestamp}"
        )
        if record.reason:
            typer.echo(f"    Reason: {record.reason}")
