"""CLI commands for releaseops analytics."""

import json
import os

import typer

app = typer.Typer(help="Behavioral analytics — metrics and version comparison.")


def _resolve_platform():
    """Auto-detect analytics platform from environment variables.

    Returns LangSmithPlatform if LANGSMITH_API_KEY is set,
    otherwise falls back to MockPlatform with a warning.
    """
    if os.environ.get("LANGSMITH_API_KEY"):
        from llmhq_releaseops.analytics.platforms.langsmith import LangSmithPlatform
        return LangSmithPlatform()

    typer.echo(
        "Warning: No analytics platform configured. "
        "Set LANGSMITH_API_KEY for real metrics. Using mock data.",
        err=True,
    )
    from llmhq_releaseops.analytics.platforms.mock import MockPlatform
    return MockPlatform()


@app.command("metrics")
def metrics_cmd(
    bundle_ref: str = typer.Argument(..., help="Bundle reference (bundle-id@version)"),
    format: str = typer.Option("summary", "--format", "-f", help="Output format: summary|json"),
    path: str = typer.Option(".", "--path", help="Repository root path"),
):
    """Show aggregated metrics for a bundle version."""
    from llmhq_releaseops.analytics.aggregator import MetricsAggregator
    from llmhq_releaseops.analytics.querier import TraceQuerier
    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_ref:
        typer.echo("Error: Bundle ref must be 'bundle-id@version' format.", err=True)
        raise typer.Exit(1)

    bundle_id, version = bundle_ref.split("@", 1)

    platform = _resolve_platform()
    querier = TraceQuerier(platform)
    traces = querier.query_by_bundle(bundle_id, version, "default")

    aggregator = MetricsAggregator()
    metrics = aggregator.aggregate(traces, bundle_id, version, "default")

    if format == "json":
        typer.echo(json.dumps(metrics.to_dict(), indent=2))
    else:
        typer.echo(f"Metrics for {bundle_id}@{version}")
        typer.echo(f"{'=' * 40}")
        typer.echo(f"  Sample size:     {metrics.sample_size}")
        typer.echo(f"  Error rate:      {metrics.error_rate:.2%}")
        typer.echo(f"  Success rate:    {metrics.success_rate:.2%}")
        typer.echo(f"  Avg latency:     {metrics.avg_latency_ms:.1f} ms")
        typer.echo(f"  P95 latency:     {metrics.p95_latency_ms:.1f} ms")
        typer.echo(f"  Avg tokens:      {metrics.avg_token_usage:.1f}")
        typer.echo(f"  Total tokens:    {metrics.total_token_usage}")


@app.command("compare")
def compare_cmd(
    baseline_ref: str = typer.Argument(..., help="Baseline bundle reference"),
    candidate_ref: str = typer.Argument(..., help="Candidate bundle reference"),
    format: str = typer.Option("summary", "--format", "-f", help="Output format: summary|json"),
    path: str = typer.Option(".", "--path", help="Repository root path"),
):
    """Compare metrics between two bundle versions."""
    from llmhq_releaseops.analytics.aggregator import MetricsAggregator
    from llmhq_releaseops.analytics.comparator import VersionComparator
    from llmhq_releaseops.analytics.querier import TraceQuerier
    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)

    for ref in (baseline_ref, candidate_ref):
        if "@" not in ref:
            typer.echo(f"Error: '{ref}' must be 'bundle-id@version' format.", err=True)
            raise typer.Exit(1)

    b_id, b_ver = baseline_ref.split("@", 1)
    c_id, c_ver = candidate_ref.split("@", 1)

    platform = _resolve_platform()
    querier = TraceQuerier(platform)
    aggregator = MetricsAggregator()

    baseline_traces = querier.query_by_bundle(b_id, b_ver, "default")
    candidate_traces = querier.query_by_bundle(c_id, c_ver, "default")

    baseline_metrics = aggregator.aggregate(baseline_traces, b_id, b_ver, "default")
    candidate_metrics = aggregator.aggregate(candidate_traces, c_id, c_ver, "default")

    comparator = VersionComparator()
    comparison = comparator.compare(baseline_metrics, candidate_metrics)

    if format == "json":
        typer.echo(json.dumps(comparison.to_dict(), indent=2))
    else:
        typer.echo(f"Version Comparison")
        typer.echo(f"{'=' * 40}")
        typer.echo(f"  Baseline:    {b_id}@{b_ver}")
        typer.echo(f"  Candidate:   {c_id}@{c_ver}")
        typer.echo(f"  Assessment:  {comparison.overall_assessment}")
        typer.echo(f"  Recommendation: {comparison.recommendation}")

        if comparison.significant_changes:
            typer.echo(f"\n  Significant Changes:")
            for change in comparison.significant_changes:
                typer.echo(
                    f"    {change.metric_name}: "
                    f"{change.baseline_value:.4f} → {change.candidate_value:.4f} "
                    f"({change.direction}, {change.significance})"
                )


@app.command("report")
def report_cmd(
    bundle_ref: str = typer.Argument(..., help="Bundle reference (bundle-id@version)"),
    output: str = typer.Option(None, "--output", "-o", help="Write report to file"),
    path: str = typer.Option(".", "--path", help="Repository root path"),
):
    """Generate a full analytics report for a bundle version."""
    from llmhq_releaseops.analytics.aggregator import MetricsAggregator
    from llmhq_releaseops.analytics.querier import TraceQuerier
    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_ref:
        typer.echo("Error: Bundle ref must be 'bundle-id@version' format.", err=True)
        raise typer.Exit(1)

    bundle_id, version = bundle_ref.split("@", 1)

    platform = _resolve_platform()
    querier = TraceQuerier(platform)
    traces = querier.query_by_bundle(bundle_id, version, "default")

    aggregator = MetricsAggregator()
    metrics = aggregator.aggregate(traces, bundle_id, version, "default")

    report = json.dumps(metrics.to_dict(), indent=2)

    if output:
        from pathlib import Path
        Path(output).write_text(report)
        typer.echo(f"Report written to {output}")
    else:
        typer.echo(report)
