"""Tests for resource tracker."""

import json
import tempfile
from pathlib import Path

import pytest

from oclawma.self_improvement.resource_tracker import ResourceTracker


class TestResourceTracker:
    """Tests for ResourceTracker."""

    @pytest.fixture
    def temp_dir(self):
        """Create temporary directory for tests."""
        with tempfile.TemporaryDirectory() as tmp:
            yield Path(tmp)

    @pytest.fixture
    def tracker(self, temp_dir):
        """Create tracker with temp path."""
        return ResourceTracker(
            db_path=str(temp_dir / "resources.json"),
            budget_hourly=5.0,
            budget_daily=50.0,
            alert_threshold=0.8,
        )

    def test_log_operation(self, tracker, temp_dir):
        """Test logging an operation."""
        alerts = tracker.log_operation("test", "Test operation", cost=1.0)

        # Should not trigger alert (below 80% of $5 = $4)
        assert len(alerts) == 0

        # Verify it was saved
        data = json.loads((temp_dir / "resources.json").read_text())
        assert len(data["operations"]) == 1
        assert data["operations"][0]["type"] == "test"

    def test_log_operation_triggers_alert(self, tracker, temp_dir):
        """Test that alerts are triggered when budget exceeded."""
        # Log expensive operation (>80% of hourly budget)
        alerts = tracker.log_operation("expensive", "Expensive operation", cost=4.5)

        assert len(alerts) >= 1
        assert alerts[0].level == "warning"
        assert "hourly" in alerts[0].type

    def test_log_operation_triggers_critical(self, tracker):
        """Test critical alert when budget exceeded."""
        # Log very expensive operation (>100% of hourly budget)
        alerts = tracker.log_operation("very_expensive", "Very expensive", cost=6.0)

        hourly_alerts = [a for a in alerts if a.type == "hourly_budget"]
        assert len(hourly_alerts) >= 1
        assert hourly_alerts[0].level == "critical"

    def test_get_status(self, tracker):
        """Test getting current status."""
        # Log some operations
        tracker.log_operation("op1", "Operation 1", cost=1.0)
        tracker.log_operation("op2", "Operation 2", cost=2.0)

        status = tracker.get_status()

        assert status["hourly"]["spent"] == 3.0
        assert status["hourly"]["budget"] == 5.0
        assert status["hourly"]["percent"] == 60.0
        assert status["operations"] == 2
        assert len(status["recent"]) == 2

    def test_hourly_daily_tracking(self, tracker):
        """Test hourly and daily tracking."""
        from datetime import datetime

        tracker.log_operation("test", "Test", cost=1.0)

        db = tracker._load_db()

        # Should have current hour and day entries
        now = datetime.now()
        hour_key = now.isoformat()[:13]
        day_key = now.isoformat()[:10]

        assert hour_key in db["hourlySpent"]
        assert day_key in db["dailySpent"]
        assert db["hourlySpent"][hour_key] == 1.0
        assert db["dailySpent"][day_key] == 1.0

    def test_default_config(self):
        """Test default configuration."""
        tracker = ResourceTracker()

        assert tracker.budget_hourly == 5.0
        assert tracker.budget_daily == 50.0
        assert tracker.alert_threshold == 0.8
