"""Tests for LLM cost tracking."""

from bilgeai.llm.cost_tracker import CostTracker, TokenUsage, estimate_cost


class TestEstimateCost:
    def test_claude_sonnet(self):
        cost = estimate_cost("claude-sonnet-4-20250514", 1000)
        assert cost > 0
        # (3.0 + 15.0) / 2 / 1M * 1000 = 0.009
        assert abs(cost - 0.009) < 0.001

    def test_gpt4o(self):
        cost = estimate_cost("gpt-4o-2024-08-06", 1000)
        assert cost > 0

    def test_unknown_model(self):
        cost = estimate_cost("some-unknown-model", 1000)
        # Falls back to $5/1M tokens
        assert abs(cost - 0.005) < 0.001

    def test_zero_tokens(self):
        cost = estimate_cost("claude-sonnet", 0)
        assert cost == 0.0


class TestTokenUsage:
    def test_auto_timestamp(self):
        usage = TokenUsage(model="test", tokens_used=100)
        assert usage.timestamp != ""

    def test_custom_fields(self):
        usage = TokenUsage(
            model="gpt-4o",
            tokens_used=500,
            purpose="optimize",
        )
        assert usage.model == "gpt-4o"
        assert usage.tokens_used == 500
        assert usage.purpose == "optimize"


class TestCostTracker:
    def test_record(self):
        tracker = CostTracker()
        usage = tracker.record("claude-sonnet", 1000, purpose="test")
        assert usage.tokens_used == 1000
        assert usage.estimated_cost_usd > 0

    def test_total_tokens(self):
        tracker = CostTracker()
        tracker.record("claude-sonnet", 500)
        tracker.record("claude-sonnet", 300)
        assert tracker.total_tokens == 800

    def test_total_cost(self):
        tracker = CostTracker()
        tracker.record("claude-sonnet", 1000)
        assert tracker.total_cost_usd > 0

    def test_summary(self):
        tracker = CostTracker()
        tracker.record("claude-sonnet", 1000, purpose="a")
        tracker.record("gpt-4o", 500, purpose="b")
        summary = tracker.summary()

        assert summary["total_tokens"] == 1500
        assert summary["total_calls"] == 2
        assert "claude-sonnet" in summary["by_model"]
        assert "gpt-4o" in summary["by_model"]

    def test_save_and_load(self, tmp_path):
        tracker = CostTracker()
        tracker.record("claude-sonnet", 1000, purpose="test")

        path = tmp_path / "cost.json"
        tracker.save(path)
        assert path.exists()

        loaded = CostTracker.load(path)
        assert loaded.total_tokens == 1000
        assert len(loaded.usages) == 1
        assert loaded.usages[0].purpose == "test"

    def test_load_nonexistent(self, tmp_path):
        path = tmp_path / "nonexistent.json"
        tracker = CostTracker.load(path)
        assert tracker.total_tokens == 0

    def test_empty_summary(self):
        tracker = CostTracker()
        summary = tracker.summary()
        assert summary["total_tokens"] == 0
        assert summary["total_calls"] == 0
