import pytest
from src.app_controller import AppController

@pytest.fixture
def controller():
    c = AppController()
    c.init_state()
    return c

def test_on_comms_entry_updates_metrics(controller: AppController):
    # Initial state
    assert controller.session_usage["input_tokens"] == 0
    assert controller.session_usage["output_tokens"] == 0
    assert len(controller._token_history) == 0

    # Simulate an AI response with usage
    payload = {
        "text": "Hello world",
        "usage": {
            "input_tokens": 100,
            "output_tokens": 50,
            "cache_read_input_tokens": 10,
            "cache_creation_input_tokens": 5,
            "total_tokens": 165
        },
        "model": "test-model"
    }
    entry = {
        "kind": "response",
        "payload": payload,
        "ts": "2024-01-01T00:00:00"
    }

    controller._on_comms_entry(entry)

    # Verify metrics updated
    assert controller.session_usage["input_tokens"] == 100
    assert controller.session_usage["output_tokens"] == 50
    assert controller.session_usage["cache_read_input_tokens"] == 10
    assert controller.session_usage["cache_creation_input_tokens"] == 5
    assert controller.session_usage["total_tokens"] == 165

    # Verify token history recorded
    assert len(controller._token_history) == 1
    assert controller._token_history[0]["input"] == 100
    assert controller._token_history[0]["output"] == 50
    assert controller._token_history[0]["model"] == "test-model"

def test_on_comms_entry_accumulates_metrics(controller: AppController):
    # First response
    controller._on_comms_entry({
        "kind": "response",
        "payload": {"usage": {"input_tokens": 100, "output_tokens": 50}}
    })
    # Second response
    controller._on_comms_entry({
        "kind": "response",
        "payload": {"usage": {"input_tokens": 200, "output_tokens": 20}}
    })

    assert controller.session_usage["input_tokens"] == 300
    assert controller.session_usage["output_tokens"] == 70
    assert len(controller._token_history) == 2
