"""Tests for status dashboard helpers."""

import json
import tempfile
from pathlib import Path

from agent_preflight.status import summarise_model


class TestSummariseModel:
    def _make_model_dir(self, tmp, summary=None, events=None):
        model_dir = Path(tmp) / "test-model"
        model_dir.mkdir(parents=True)
        if summary is not None:
            (model_dir / "summary.json").write_text(json.dumps(summary))
        if events is not None:
            lines = "\n".join(json.dumps(e) for e in events)
            (model_dir / "events.jsonl").write_text(lines + "\n")
        return model_dir

    def test_reads_summary(self):
        with tempfile.TemporaryDirectory() as tmp:
            md = self._make_model_dir(tmp, summary={
                "cost_usd": 0.15,
                "tool_calls": 8,
                "duration_s": 120,
                "started_at": "2026-03-12T12:00:00Z",
            })
            s = summarise_model(md)
            assert s["status"] == "DONE"
            assert s["cost"] == 0.15
            assert s["tool_calls"] == 8

    def test_reads_cache_from_summary(self):
        with tempfile.TemporaryDirectory() as tmp:
            md = self._make_model_dir(tmp, summary={
                "cost_usd": 0.10,
                "cache": {
                    "hit_rate": 0.85,
                    "request_count": 5,
                    "cached_tokens": 8500,
                    "total_prompt_tokens": 10000,
                },
            })
            s = summarise_model(md)
            assert s["cache_hit_rate"] == 0.85

    def test_no_cache_data_defaults_zero(self):
        with tempfile.TemporaryDirectory() as tmp:
            md = self._make_model_dir(tmp, summary={"cost_usd": 0.10})
            s = summarise_model(md)
            assert s["cache_hit_rate"] == 0.0

    def test_error_in_summary(self):
        with tempfile.TemporaryDirectory() as tmp:
            md = self._make_model_dir(tmp, summary={
                "error": "ejected: budget",
                "cost_usd": 0.05,
            })
            s = summarise_model(md)
            assert s["status"] == "ERR"
            assert s["error"] == "ejected: budget"

    def test_fallback_to_events(self):
        with tempfile.TemporaryDirectory() as tmp:
            events = [
                {"type": "tool_execution_start", "toolName": "bash", "elapsed_s": 1.2},
                {"type": "tool_execution_end", "toolName": "bash", "elapsed_s": 5.0},
                {"type": "tool_execution_start", "toolName": "read", "elapsed_s": 9.8},
            ]
            md = self._make_model_dir(tmp, events=events)
            s = summarise_model(md)
            assert s["events"] == 3
            assert s["tool_calls"] == 2  # 2 starts
            assert s["duration_s"] == 9

    def test_pending_status_with_no_summary(self):
        with tempfile.TemporaryDirectory() as tmp:
            md = self._make_model_dir(tmp)
            s = summarise_model(md)
            assert s["status"] == "pending"

    def test_corrupt_summary_does_not_crash(self):
        with tempfile.TemporaryDirectory() as tmp:
            md = Path(tmp) / "broken"
            md.mkdir(parents=True)
            (md / "summary.json").write_text("not json at all")
            s = summarise_model(md)
            assert s["status"] == "pending"


class TestCacheReportIntegration:
    """Verify cache_report reads the exact keys CacheStats.to_dict() writes."""

    def test_key_contract(self):
        from agent_preflight.cache_report import generate_cache_report
        from agent_preflight.models import CacheStats

        stats = CacheStats(
            total_prompt_tokens=5000,
            cached_tokens=4000,
            cache_creation_tokens=1000,
            request_count=10,
            cache_hit_requests=8,
        )
        summary = {
            "cost_usd": 0.10,
            "cache": stats.to_dict(),
        }

        with tempfile.TemporaryDirectory() as tmp:
            run_dir = Path(tmp) / "run"
            model_dir = run_dir / "model"
            model_dir.mkdir(parents=True)
            (model_dir / "summary.json").write_text(json.dumps(summary))

            report = generate_cache_report(run_dir)
            assert "80.0%" in report
            assert "4,000" in report
            assert "1,000" in report  # cache creation tokens present
