from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]


def read_service() -> str:
    return (ROOT / "app/fiscal_enrichment_service.py").read_text(encoding="utf-8")


def test_v4928_1_5_11_weak_fiscal_tokens_are_not_strong_matches():
    source = read_service()
    assert "FISCAL_NAME_WEAK_TOKENS" in source
    assert '"portugal"' in source
    assert '"lda"' in source
    assert '"unipessoal"' in source
    assert "def _strong_company_tokens" in source
    assert "token not in FISCAL_NAME_WEAK_TOKENS" in source


def test_v4928_1_5_11_company_match_uses_strong_tokens_not_generic_overlap():
    source = read_service()
    block = source.split("def _company_name_matches_mention", 1)[1].split("def _has_manually_rejected_suggestion", 1)[0]
    assert "mention_tokens = _strong_company_tokens(mention_norm)" in block
    assert "candidate_tokens = _strong_company_tokens(candidate_norm)" in block
    assert "shared = mention_tokens & candidate_tokens" in block
    assert "unipessoal", "Legacy inline weak-token filtering should be replaced by shared weak-token guard"


def test_v4928_1_5_11_manual_rejection_prevents_reapply():
    source = read_service()
    assert "def _has_manually_rejected_suggestion" in source
    assert "status = 'rejected'" in source
    assert "manual_rejection_exists" in source
    # The guard must be checked before auto-application/suggestion paths.
    assert source.count("_has_manually_rejected_suggestion(") >= 4
