from pathlib import Path

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


def test_document_reference_guard_is_before_contact_and_creation():
    source = (ROOT / "app" / "opportunity_service.py").read_text()
    assert "find_document_owner_opportunity_for_task" in source
    assert "document_reference" in source
    assert source.index("by_document_reference = find_document_owner_opportunity_for_task") < source.index("contact_matches = _open_opportunities_for_contact")
    assert "multiple_company_domain_or_document_candidates" in source


def test_linking_helper_normalizes_orc_and_fa_formats():
    source = (ROOT / "app" / "company_opportunity_linking.py").read_text()
    assert "Orçamento 2026/193" in source
    assert "ORC.ORC" in source
    assert "FA.FA" in source
    assert "PUBLIC_EMAIL_DOMAINS" in source
    assert "find_unique_company_domain_opportunity_for_task" in source
    assert "manual_link_candidates_for_task" in source


def test_operator_manual_association_ui_and_endpoint_exist():
    source = (ROOT / "app" / "admin_ui" / "pages" / "tasks.py").read_text()
    assert "Associar a oportunidade existente" in source
    assert "/tasks/{task_id}/associate-opportunity" in source
    assert "associate_task_to_opportunity" in source
    assert "opportunity_linking_candidates" in source


def test_repair_script_is_read_only_by_default_and_closes_empty_duplicates_only_on_apply():
    source = (ROOT / "scripts" / "repair_cross_conversation_company_links.py").read_text()
    assert "dry_run=True" in source
    assert "STRONG_DOCUMENT_MATCH" in source
    assert "AMBIGUOUS_COMPANY_MATCH" in source
    assert "close_empty_duplicate" in source
    assert "source_opportunity_document_count" in source
