"""CLI commands for releaseops attribution."""

import json
from pathlib import Path

import typer

app = typer.Typer(help="Attribution analysis — explain agent behavior.")


@app.command("explain")
def explain_cmd(
    trace_file: str = typer.Argument(..., help="Path to trace JSON file"),
    bundle: str = typer.Option(..., "--bundle", "-b", help="Bundle reference (bundle-id@version)"),
    format: str = typer.Option("text", "--format", "-f", help="Output format: text|json"),
    confidence_threshold: float = typer.Option(0.0, "--confidence-threshold", help="Filter below this confidence"),
    output: str = typer.Option(None, "--output", "-o", help="Write output to file"),
    path: str = typer.Option(".", "--path", help="Repository root path"),
):
    """Explain agent behavior by attributing it to bundle artifacts."""
    from llmhq_releaseops.attribution.analyzer import AttributionAnalyzer
    from llmhq_releaseops.attribution.reporters.json_reporter import JSONReporter
    from llmhq_releaseops.attribution.reporters.text_reporter import TextReporter
    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)

    # Parse bundle reference
    if "@" not in bundle:
        typer.echo("Error: Bundle must be 'bundle-id@version' format.", err=True)
        raise typer.Exit(1)
    bundle_id, bundle_version = bundle.split("@", 1)

    trace_path = Path(trace_file)
    if not trace_path.exists():
        typer.echo(f"Error: Trace file not found: {trace_file}", err=True)
        raise typer.Exit(1)

    try:
        analyzer = AttributionAnalyzer(store)
        attribution = analyzer.analyze_from_file(trace_path, bundle_id, bundle_version)

        # Filter by confidence
        if confidence_threshold > 0:
            filtered = [i for i in attribution.influences if i.confidence >= confidence_threshold]
            from llmhq_releaseops.attribution.models import Attribution
            attribution = Attribution(
                trace_id=attribution.trace_id,
                bundle_id=attribution.bundle_id,
                bundle_version=attribution.bundle_version,
                action=attribution.action,
                action_type=attribution.action_type,
                influences=filtered,
                overall_assessment=attribution.overall_assessment,
                analyzed_at=attribution.analyzed_at,
            )

        if format == "json":
            result = JSONReporter().report(attribution)
        else:
            result = TextReporter().report(attribution)

        if output:
            Path(output).write_text(result)
            typer.echo(f"Output written to {output}")
        else:
            typer.echo(result)

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


@app.command("analyze-batch")
def analyze_batch_cmd(
    traces_dir: str = typer.Argument(..., help="Directory containing trace JSON files"),
    bundle: str = typer.Option(..., "--bundle", "-b", help="Bundle reference (bundle-id@version)"),
    path: str = typer.Option(".", "--path", help="Repository root path"),
):
    """Analyze multiple traces and show summary statistics."""
    from llmhq_releaseops.attribution.analyzer import AttributionAnalyzer
    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)

    if "@" not in bundle:
        typer.echo("Error: Bundle must be 'bundle-id@version' format.", err=True)
        raise typer.Exit(1)
    bundle_id, bundle_version = bundle.split("@", 1)

    traces_path = Path(traces_dir)
    if not traces_path.is_dir():
        typer.echo(f"Error: Directory not found: {traces_dir}", err=True)
        raise typer.Exit(1)

    trace_files = list(traces_path.glob("*.json"))
    if not trace_files:
        typer.echo("No JSON trace files found in directory.", err=True)
        raise typer.Exit(1)

    analyzer = AttributionAnalyzer(store)
    total = 0
    expected = 0
    unexpected = 0
    unclear = 0
    influence_counts = {}

    for tf in trace_files:
        try:
            attribution = analyzer.analyze_from_file(tf, bundle_id, bundle_version)
            total += 1
            if "Expected" in attribution.overall_assessment:
                expected += 1
            elif "Unexpected" in attribution.overall_assessment:
                unexpected += 1
            else:
                unclear += 1

            if attribution.primary_influence:
                key = attribution.primary_influence.artifact_ref
                influence_counts[key] = influence_counts.get(key, 0) + 1
        except Exception as e:
            typer.echo(f"Warning: Skipped {tf.name}: {e}", err=True)

    typer.echo(f"Batch Attribution Summary")
    typer.echo(f"{'=' * 40}")
    typer.echo(f"  Traces analyzed: {total}")
    typer.echo(f"  Expected:        {expected}")
    typer.echo(f"  Unexpected:      {unexpected}")
    typer.echo(f"  Unclear:         {unclear}")

    if influence_counts:
        typer.echo(f"\n  Most common primary influences:")
        for ref, count in sorted(influence_counts.items(), key=lambda x: -x[1])[:5]:
            typer.echo(f"    {ref}: {count} traces")
