import os
import tempfile
from datetime import datetime, timezone

from costrouter.analytics import Analytics, RoutingRecord
from costrouter.models import CostTier


def _make_record(
    tier: CostTier = CostTier.SIMPLE,
    model: str = "gpt-3.5-turbo",
    router_type: str = "cascade",
    screener_cost: float = 0.0001,
    call_cost: float = 0.001,
    max_cost_estimate: float = 0.05,
) -> RoutingRecord:
    total = screener_cost + call_cost
    return RoutingRecord(
        timestamp=datetime.now(timezone.utc),
        prompt_length=50,
        tier=tier,
        model_used=model,
        router_type=router_type,
        screener_cost=screener_cost,
        call_cost=call_cost,
        total_cost=total,
        max_cost_estimate=max_cost_estimate,
        latency_ms=100.0,
    )


class TestAnalytics:
    def setup_method(self):
        self.analytics = Analytics()

    def test_empty_summary(self):
        summary = self.analytics.summary()
        assert "No requests recorded" in summary

    def test_record_and_count(self):
        self.analytics.record(_make_record())
        self.analytics.record(_make_record())
        assert len(self.analytics.records) == 2

    def test_summary_with_records(self):
        self.analytics.record(_make_record(CostTier.SIMPLE, "gpt-3.5-turbo"))
        self.analytics.record(_make_record(CostTier.COMPLEX, "gpt-4o"))
        self.analytics.record(_make_record(CostTier.SIMPLE, "gpt-3.5-turbo"))

        summary = self.analytics.summary()
        assert "Total requests: 3" in summary
        assert "simple" in summary
        assert "complex" in summary
        assert "gpt-3.5-turbo" in summary
        assert "gpt-4o" in summary

    def test_summary_shows_savings(self):
        self.analytics.record(
            _make_record(
                screener_cost=0.001,
                call_cost=0.01,
                max_cost_estimate=0.10,
            )
        )
        summary = self.analytics.summary()
        assert "Total saved" in summary

    def test_to_dict(self):
        self.analytics.record(_make_record())
        d = self.analytics.to_dict()
        assert d["total_requests"] == 1
        assert "total_cost" in d
        assert "screening_costs" in d
        assert "saved" in d
        assert len(d["records"]) == 1

    def test_to_records(self):
        self.analytics.record(_make_record())
        records = self.analytics.to_records()
        assert len(records) == 1
        assert "tier" in records[0]
        assert "model_used" in records[0]

    def test_export_csv(self):
        self.analytics.record(_make_record(CostTier.SIMPLE, "gpt-3.5-turbo"))
        self.analytics.record(_make_record(CostTier.COMPLEX, "gpt-4o"))

        with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
            path = f.name

        try:
            self.analytics.export_csv(path)
            with open(path) as f:
                content = f.read()
            assert "timestamp" in content
            assert "gpt-3.5-turbo" in content
            assert "gpt-4o" in content
        finally:
            os.unlink(path)

    def test_export_csv_empty(self):
        with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
            path = f.name

        try:
            self.analytics.export_csv(path)
            # Should not create/write anything
        finally:
            os.unlink(path)

    def test_reset(self):
        self.analytics.record(_make_record())
        self.analytics.record(_make_record())
        assert len(self.analytics.records) == 2

        self.analytics.reset()
        assert len(self.analytics.records) == 0

    def test_records_returns_copy(self):
        self.analytics.record(_make_record())
        records = self.analytics.records
        records.clear()
        assert len(self.analytics.records) == 1  # original unaffected
