"""CLI commands for rollback and run history."""

from __future__ import annotations

from typing import Optional

import typer
from rich.console import Console
from rich.table import Table

console = Console()


def rollback_cmd(
    run_id: str = typer.Argument(..., help="Run ID to rollback"),
    output_dir: str = typer.Option(".", "--output-dir", help="Directory containing run log"),
) -> None:
    """Rollback a previous merge run by deleting its output files."""
    from goldenmatch.core.rollback import rollback_run

    result = rollback_run(run_id, output_dir)

    if "error" in result:
        console.print(f"[red]Error:[/] {result['error']}")
        if "available_runs" in result:
            console.print(f"Available runs: {', '.join(result['available_runs'][:5])}")
        raise typer.Exit(code=1)

    console.print(f"[#2ecc71]Rolled back run {run_id}[/]")
    if result["deleted"]:
        for f in result["deleted"]:
            console.print(f"  Deleted: {f}")
    if result["not_found"]:
        for f in result["not_found"]:
            console.print(f"  [dim]Not found: {f}[/dim]")


def runs_cmd(
    output_dir: str = typer.Option(".", "--output-dir", help="Directory containing run log"),
) -> None:
    """List previous runs (for rollback)."""
    from goldenmatch.core.rollback import list_runs

    runs = list_runs(output_dir)

    if not runs:
        console.print("[dim]No runs found. Run a dedupe first.[/dim]")
        return

    table = Table(title="Run History", border_style="#d4a017", header_style="bold #d4a017")
    table.add_column("Run ID", style="bold")
    table.add_column("Timestamp")
    table.add_column("Files")
    table.add_column("Status")

    for run in reversed(runs[-10:]):
        status = "[red]rolled back[/]" if run.get("rolled_back") else "[#2ecc71]active[/]"
        ts = run.get("timestamp", "")[:19]
        files = str(len(run.get("output_files", [])))
        table.add_row(run["run_id"][:12], ts, files, status)

    console.print(table)


def unmerge_cmd(
    record_id: int = typer.Argument(..., help="Record row ID to unmerge from its cluster"),
    clusters_file: str = typer.Option(None, "--clusters", help="Path to clusters CSV from a previous run"),
    scored_pairs_file: str = typer.Option(None, "--pairs", help="Path to scored pairs file"),
    shatter: bool = typer.Option(False, "--shatter", help="Shatter the entire cluster into singletons"),
    threshold: float = typer.Option(0.0, "--threshold", help="Min score threshold for re-clustering"),
) -> None:
    """Remove a record from its cluster (per-entity unmerge).

    The record becomes a singleton. Remaining cluster members are re-clustered
    using their stored pair scores. Use --shatter to break the entire cluster.
    """
    from goldenmatch.core.cluster import build_clusters, unmerge_record, unmerge_cluster

    # For now, demonstrate with inline cluster building
    # Full integration would load from run snapshot
    console.print(f"[#d4a017]Unmerge record {record_id}[/]")

    if clusters_file:
        import polars as pl
        clusters_df = pl.read_csv(clusters_file)
        console.print(f"  Loaded clusters from {clusters_file}")

        # Find the cluster containing the record
        target_row = clusters_df.filter(pl.col("__row_id__") == record_id)
        if target_row.height == 0:
            console.print(f"[red]Record {record_id} not found in clusters file.[/red]")
            raise typer.Exit(code=1)

        cluster_id = target_row["__cluster_id__"][0]
        cluster_members = clusters_df.filter(
            pl.col("__cluster_id__") == cluster_id
        )["__row_id__"].to_list()

        console.print(f"  Found in cluster {cluster_id} ({len(cluster_members)} members)")
        console.print(f"  Members: {cluster_members}")

        if shatter:
            console.print(f"  [bold yellow]Shattering cluster {cluster_id} into {len(cluster_members)} singletons[/]")
        else:
            console.print(f"  [bold]Removing record {record_id} from cluster[/]")
            remaining = [m for m in cluster_members if m != record_id]
            console.print(f"  Remaining members: {remaining}")
    else:
        console.print(
            "[dim]Tip: Pass --clusters path/to/clusters.csv from a previous run.[/dim]\n"
            "[dim]The clusters file is generated by: goldenmatch dedupe --output-all[/dim]"
        )
        console.print(f"\n[bold]unmerge_record({record_id}) and unmerge_cluster() are available in:[/]")
        console.print("  goldenmatch.core.cluster.unmerge_record(record_id, clusters, threshold)")
        console.print("  goldenmatch.core.cluster.unmerge_cluster(cluster_id, clusters)")
