import pytest
import yaml
from pathlib import Path
from krrkt.engine.pipeline import proofread


FIXTURES_PATH = Path(__file__).parent.parent / "fixtures" / "texts.yaml"


def load_golden_tests():
    with open(FIXTURES_PATH, encoding="utf-8") as f:
        data = yaml.safe_load(f)
    return data["tests"]


golden_tests = load_golden_tests()


@pytest.mark.parametrize(
    "test_case",
    golden_tests,
    ids=[t["name"] for t in golden_tests],
)
@pytest.mark.asyncio
async def test_golden_score_range(test_case):
    """Verify score falls within expected range."""
    result = await proofread(test_case["text"], skip_llm=True)

    score_min = test_case.get("expected_score_min", 0)
    score_max = test_case.get("expected_score_max", 10)
    assert score_min <= result.score <= score_max, (
        f"Score {result.score} not in [{score_min}, {score_max}] for '{test_case['name']}'"
    )


@pytest.mark.parametrize(
    "test_case",
    [t for t in golden_tests if "must_find_rules" in t],
    ids=[t["name"] for t in golden_tests if "must_find_rules" in t],
)
@pytest.mark.asyncio
async def test_golden_must_find_rules(test_case):
    """Verify expected rule categories are detected."""
    result = await proofread(test_case["text"], skip_llm=True)
    found_rules = {f.rule for f in result.findings}

    for expected_rule in test_case["must_find_rules"]:
        assert expected_rule in found_rules, (
            f"Expected rule '{expected_rule}' not found in {found_rules} for '{test_case['name']}'"
        )


@pytest.mark.parametrize(
    "test_case",
    [t for t in golden_tests if "must_find" in t],
    ids=[t["name"] for t in golden_tests if "must_find" in t],
)
@pytest.mark.asyncio
async def test_golden_must_find_words(test_case):
    """Verify specific words/phrases are detected."""
    result = await proofread(test_case["text"], skip_llm=True)
    found_words = {f.word.lower() for f in result.findings}

    for expected_word in test_case["must_find"]:
        assert any(expected_word.lower() in w for w in found_words), (
            f"Expected word '{expected_word}' not found in {found_words} for '{test_case['name']}'"
        )


@pytest.mark.parametrize(
    "test_case",
    [t for t in golden_tests if "must_not_find_rules" in t],
    ids=[t["name"] for t in golden_tests if "must_not_find_rules" in t],
)
@pytest.mark.asyncio
async def test_golden_must_not_find_rules(test_case):
    """Verify certain rules are NOT triggered for clean text."""
    result = await proofread(test_case["text"], skip_llm=True)
    found_rules = {f.rule for f in result.findings}

    for unwanted_rule in test_case["must_not_find_rules"]:
        assert unwanted_rule not in found_rules, (
            f"Unexpected rule '{unwanted_rule}' found for '{test_case['name']}'"
        )
