import importlib
import sys
from pathlib import Path


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

priority_mod = importlib.import_module("contexthub.priority")
types_mod = importlib.import_module("contexthub.types")
select_by_priority = priority_mod.select_by_priority
trim_to_fit = priority_mod.trim_to_fit
ContextItem = types_mod.ContextItem
Priority = types_mod.Priority


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


def test_select_by_priority_mixed():
    items = [
        ContextItem("low text", priority=Priority.LOW),
        ContextItem("critical content", priority=Priority.CRITICAL),
        ContextItem("high value", priority=Priority.HIGH),
        ContextItem("medium content", priority=Priority.MEDIUM),
    ]

    selected = select_by_priority(items, max_tokens=5, tokenizer=word_tokenizer)
    assert [item.priority for item in selected] == [Priority.CRITICAL, Priority.HIGH]


def test_select_includes_critical_even_if_exceeds_budget():
    items = [
        ContextItem("one two three four five six", priority=Priority.CRITICAL),
        ContextItem("extra", priority=Priority.HIGH),
    ]
    selected = select_by_priority(items, max_tokens=3, tokenizer=word_tokenizer)
    assert len(selected) == 1
    assert selected[0].priority == Priority.CRITICAL


def test_trim_to_fit_behaviors():
    text = "one two three four"
    assert (
        trim_to_fit(text, max_tokens=3, tokenizer=word_tokenizer) == "one two three..."
    )
    assert trim_to_fit("short", max_tokens=3, tokenizer=word_tokenizer) == "short"
    assert trim_to_fit("", max_tokens=3, tokenizer=word_tokenizer) == ""
    assert trim_to_fit("data", max_tokens=0, tokenizer=word_tokenizer) == ""
