import importlib
import sys
from pathlib import Path


sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))

contexthub = importlib.import_module("contexthub")
ContextWindow = contexthub.ContextWindow
Priority = contexthub.Priority


def simple_tokenizer(text: str) -> int:
    return len(text.split())


def test_add_and_items_exposed():
    window = ContextWindow(max_tokens=10, tokenizer=simple_tokenizer)
    item = window.add(
        "hello world", priority=Priority.HIGH, role="user", metadata={"id": 1}
    )

    assert item.content == "hello world"
    assert item.priority == Priority.HIGH
    assert item.role == "user"
    assert item.metadata == {"id": 1}
    assert len(window.items) == 1


def test_build_respects_limits_and_priority():
    window = ContextWindow(max_tokens=5, tokenizer=simple_tokenizer)
    window.add("alpha beta gamma", priority=Priority.MEDIUM)
    window.add("system rule", priority=Priority.CRITICAL, role="system")
    window.add("high note", priority=Priority.HIGH)

    built = window.build()
    assert [item.priority for item in built] == [Priority.CRITICAL, Priority.HIGH]
    assert sum(i.token_count or 0 for i in built) <= 5


def test_to_messages_structure():
    window = ContextWindow(max_tokens=20, tokenizer=simple_tokenizer)
    window.add("system directive", priority=Priority.CRITICAL, role="system")
    window.add("user question", role="user")

    messages = window.to_messages()
    assert messages[0] == {"role": "system", "content": "system directive"}
    assert messages[1] == {"role": "user", "content": "user question"}


def test_totals_remaining_and_clear():
    window = ContextWindow(max_tokens=6, tokenizer=simple_tokenizer)
    window.add("one two")
    window.add("three four")

    assert window.total_tokens == 4
    assert window.remaining_tokens == 2

    window.clear()
    assert window.total_tokens == 0
    assert window.items == []
