"""releaseops promote / rollback — Promote and roll back bundles."""

from typing import Optional

import typer

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

app = typer.Typer(help="Promote and roll back bundles through environments.")


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


@app.command()
def promote(
    bundle_id: str = typer.Argument(..., help="Bundle ID to promote"),
    version: str = typer.Argument(..., help="Bundle version"),
    target_env: str = typer.Argument(..., help="Target environment (dev, staging, prod)"),
    reason: str = typer.Option("", "--reason", "-r", help="Promotion reason"),
    skip_gates: bool = typer.Option(False, "--skip-gates", help="Skip quality gates (dangerous)"),
    dry_run: bool = typer.Option(False, "--dry-run", help="Validate without promoting"),
    path: str = typer.Option(".", "--path", help="Repository root path"),
):
    """Promote a bundle version to a target environment."""
    promoter = _get_promoter(path)

    try:
        record = promoter.promote(
            bundle_id=bundle_id,
            version=version,
            target_env=target_env,
            promoted_by="cli",
            reason=reason,
            skip_gates=skip_gates,
            dry_run=dry_run,
        )

        if dry_run:
            typer.echo(f"[DRY RUN] Would promote {bundle_id} v{version} → {target_env}")
            if record.gate_results:
                for g in record.gate_results:
                    status = "PASS" if g.passed else "FAIL"
                    typer.echo(f"  Gate [{g.gate_type.value}]: {status} — {g.details}")
        else:
            typer.echo(f"Promoted {bundle_id} v{version} → {target_env}")
            typer.echo(f"  State: {record.state.value}")
            if record.gate_results:
                for g in record.gate_results:
                    status = "PASS" if g.passed else "FAIL"
                    typer.echo(f"  Gate [{g.gate_type.value}]: {status}")

    except (ValueError, FileNotFoundError) as e:
        typer.echo(f"Error: {e}", err=True)
        raise typer.Exit(1)


@app.command()
def rollback(
    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: Optional[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 in an environment."""
    promoter = _get_promoter(path)

    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)
