"""Detailed cache analytics and reporting for agent-preflight runs.

CLI usage::

    python -m agent_preflight cache-report              # latest run
    python -m agent_preflight cache-report run-20260312-120000
"""

from __future__ import annotations

import json
import sys
from pathlib import Path

RUNS_DIR = Path("runs")


def latest_run(runs_dir: Path = RUNS_DIR) -> Path | None:
    """Return the most recently modified run directory, or None."""
    if not runs_dir.is_dir():
        return None
    dirs = [d for d in runs_dir.iterdir() if d.is_dir()]
    if not dirs:
        return None
    return max(dirs, key=lambda d: d.stat().st_mtime)


def generate_cache_report(run_dir: Path) -> str:
    """Generate a detailed cache report for a run."""
    lines = []
    lines.append(f"\nCache Analytics Report: {run_dir.name}")
    lines.append("=" * 70)

    model_dirs = sorted(d for d in run_dir.iterdir() if d.is_dir())
    if not model_dirs:
        lines.append("  No model directories found.")
        return "\n".join(lines)

    # Aggregate stats
    total_prompt_tokens = 0
    total_cached_tokens = 0
    total_cache_creation = 0
    total_requests = 0
    total_cache_hits = 0
    models_data = []

    for model_dir in model_dirs:
        alias = model_dir.name
        summary_path = model_dir / "summary.json"

        model_info = {
            "alias": alias,
            "cost": None,
            "cache": {
                "request_count": 0,
                "cached_tokens": 0,
                "total_prompt_tokens": 0,
                "cache_creation_tokens": 0,
                "hit_rate": 0.0,
            },
        }

        if summary_path.exists():
            try:
                s = json.loads(summary_path.read_text())
                model_info["cost"] = s.get("cost_usd")
                cache_data = s.get("cache", {})
                if isinstance(cache_data, dict):
                    model_info["cache"] = {
                        "request_count": cache_data.get("request_count", 0),
                        "cached_tokens": cache_data.get("cached_tokens", 0),
                        "total_prompt_tokens": cache_data.get("total_prompt_tokens", 0),
                        "cache_creation_tokens": cache_data.get("cache_creation_tokens", 0),
                        "hit_rate": cache_data.get("hit_rate", 0.0),
                    }
            except json.JSONDecodeError:
                pass

        cache = model_info["cache"]
        if cache["request_count"] > 0:
            total_requests += cache["request_count"]
            total_prompt_tokens += cache["total_prompt_tokens"]
            total_cached_tokens += cache["cached_tokens"]
            total_cache_creation += cache["cache_creation_tokens"]
            total_cache_hits += 1

        models_data.append(model_info)

    # Per-model details
    lines.append("\nPer-Model Cache Performance:")
    lines.append("-" * 70)
    for m in models_data:
        cache = m["cache"]
        if cache["request_count"] == 0:
            lines.append(f"  {m['alias']:<20} [no cache data]")
            continue

        hit_rate_pct = cache["hit_rate"] * 100
        cost_str = f" (${m['cost']:.4f})" if m["cost"] else ""
        lines.append(
            f"  {m['alias']:<20} "
            f"hit_rate={hit_rate_pct:>5.1f}%  "
            f"cached={cache['cached_tokens']:>6}  "
            f"total={cache['total_prompt_tokens']:>7}  "
            f"requests={cache['request_count']:>3}{cost_str}"
        )

    # Aggregate summary
    if total_requests > 0:
        overall_hit_rate = total_cached_tokens / total_prompt_tokens if total_prompt_tokens else 0.0
        lines.append("\n" + "=" * 70)
        lines.append("Aggregate Cache Statistics:")
        lines.append("-" * 70)
        lines.append(f"  Total requests with cache data:     {total_requests}")
        lines.append(f"  Total prompt tokens:                {total_prompt_tokens:,}")
        lines.append(f"  Total cached tokens:                {total_cached_tokens:,}")
        lines.append(f"  Total cache creation tokens:        {total_cache_creation:,}")
        lines.append(f"  Overall cache hit rate:             {overall_hit_rate*100:.1f}%")

        # Estimate savings using a blended prompt cost assumption.
        # Typical prompt costs: Sonnet ~$3/1M, Haiku ~$0.25/1M, GPT-4o ~$2.50/1M.
        # Using $1/1M as a conservative blended average.
        # Cache discount: OpenAI ~50%, Anthropic ~90% on reads. Using 50%.
        prompt_cost_per_token = 1.00 / 1_000_000  # $1 per 1M tokens
        estimated_savings = total_cached_tokens * prompt_cost_per_token * 0.50
        lines.append(f"  Est. cache savings (50% discount):  ${estimated_savings:.4f}")
    else:
        lines.append("\nNo cache data recorded for this run.")

    lines.append("=" * 70 + "\n")
    return "\n".join(lines)


def main(run_id: str | None = None, runs_dir: Path = RUNS_DIR) -> None:
    """Print the cache report for a run."""
    if run_id:
        run_dir = runs_dir / run_id
    else:
        run_dir = latest_run(runs_dir)

    if run_dir is None or not run_dir.is_dir():
        print(f"  No runs found in {runs_dir}/")
        return

    report = generate_cache_report(run_dir)
    print(report)


if __name__ == "__main__":
    _run_id = sys.argv[1] if len(sys.argv) > 1 else None
    main(_run_id)
