"""
ReleaseOps CLI - Release engineering infrastructure for AI behavior.

Commands:
  init       Initialize .releaseops/ directory structure
  bundle     Create, inspect, and manage bundles
  env        Manage environments and bundle mappings
  promote    Promote bundles through environments
  rollback   Roll back to a previous bundle version
  eval       Run evaluation suites and quality gates
"""

import typer

from llmhq_releaseops._version import __version__
from llmhq_releaseops.cli.commands import (
    analytics_cmd,
    attribution_cmd,
    bundle,
    env,
    eval_cmd,
    init,
    promote,
    telemetry_cmd,
)

app = typer.Typer(
    name="releaseops",
    help="Release engineering infrastructure for AI behavior.",
    no_args_is_help=True,
)

# Register sub-command groups
app.add_typer(init.app, name="init")
app.add_typer(bundle.app, name="bundle")
app.add_typer(env.app, name="env")
app.add_typer(promote.app, name="promote")
app.add_typer(eval_cmd.app, name="eval")
app.add_typer(telemetry_cmd.app, name="telemetry")
app.add_typer(attribution_cmd.app, name="attribution")
app.add_typer(analytics_cmd.app, name="analytics")


@app.command("rollback")
def rollback_cmd(
    env_name: str = typer.Argument(..., help="Environment to roll back in"),
    bundle_id: str = typer.Argument(..., help="Bundle ID to roll back"),
    steps: int = typer.Option(1, "--steps", "-s", help="Steps back (default: 1)"),
    to_version: str = typer.Option(None, "--to", help="Roll back to specific version"),
    reason: str = typer.Option("", "--reason", "-r", help="Rollback reason"),
    path: str = typer.Option(".", "--path", help="Repository root path"),
):
    """Roll back a bundle to a previous version."""
    from llmhq_releaseops.core.promoter import Promoter
    from llmhq_releaseops.core.resolver import Resolver
    from llmhq_releaseops.storage.git_store import GitStore

    store = GitStore(path)
    if not store.is_initialized():
        typer.echo("Error: ReleaseOps not initialized.", err=True)
        raise typer.Exit(1)

    resolver = Resolver(store)
    promoter = Promoter(store, resolver)

    try:
        record = promoter.rollback(
            env=env_name,
            bundle_id=bundle_id,
            steps=steps,
            to_version=to_version,
            promoted_by="cli",
            reason=reason,
        )
        typer.echo(
            f"Rolled back {bundle_id} in {env_name}: "
            f"{record.rolled_back_from} → {record.version}"
        )
    except (ValueError, FileNotFoundError) as e:
        typer.echo(f"Error: {e}", err=True)
        raise typer.Exit(1)


@app.command("version")
def version_cmd():
    """Show releaseops version."""
    typer.echo(f"llmhq-releaseops v{__version__}")


@app.callback()
def main():
    """ReleaseOps - Bundle, promote, evaluate, and replay AI behavior."""
    pass


if __name__ == "__main__":
    app()
