from pathlib import Path

from app.fiscal_enrichment_service import (
    VERY_STRONG_MATCH_TYPES,
    _company_name_matches_mention,
    _is_likely_company_name_signal,
    _is_valid_company_lookup_value,
    _looks_like_person_name,
    _should_auto_apply,
)
from app.commercial_service import normalize_fiscal_name

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


def n(value: str) -> str:
    return normalize_fiscal_name(value)


def test_v4928_1_5_12_sector_tokens_do_not_link_unrelated_companies():
    assert not _company_name_matches_mention(n("Feteira e Torrão Engenharia"), n("HUASI - Engenharia e Construções, Unipessoal, LDA"))
    assert not _company_name_matches_mention(n("DS Seguros GAC Porto"), n("Carlos Reis - Mediação de Seguros, LDA"))
    assert not _company_name_matches_mention(n("Verifone Portugal"), n("ERT Têxtil Portugal, S.A."))


def test_v4928_1_5_12_keeps_real_company_matches():
    assert _company_name_matches_mention(n("Dietimport S.A."), n("DIETIMPORT, S.A."))
    assert _company_name_matches_mention(n("Sementenergias"), n("SEMENTENERGIAS, UNIPESSOAL, LDA"))
    assert _company_name_matches_mention(n("Europneumaq"), n("EUROPNEUMAQ - SOLUÇÕES INDUSTRIAIS, LDA"))


def test_v4928_1_5_12_blocks_person_and_invalid_name_lookups():
    assert _looks_like_person_name("Nuno Silva")
    assert _looks_like_person_name("Bárbara Gonçalves")
    assert not _is_likely_company_name_signal("Nuno Silva")
    assert not _is_valid_company_lookup_value("pt")
    assert not _is_valid_company_lookup_value("geral")
    assert not _is_valid_company_lookup_value("info")


def test_v4928_1_5_12_email_identity_company_internal_is_not_auto_strong():
    assert "email_identity_company_internal" not in VERY_STRONG_MATCH_TYPES
    opportunity = {"linked_customer_id": None, "local_customer_id": None, "linked_customer_tax_id": ""}
    company = {"nif": "513812032", "nome": "HUASI - ENGENHARIA E CONSTRUÇÕES, UNIPESSOAL, LDA", "match_type": "email_identity_company_internal"}
    assert not _should_auto_apply(opportunity, company, confidence=99.0)
    exact_company = {"nif": "510664709", "nome": "Verifone Portugal, Lda", "match_type": "email_identity_company_internal_exact"}
    assert not _should_auto_apply(opportunity, exact_company, confidence=99.0)
    domain_company = {"nif": "510664709", "nome": "Verifone Portugal, Lda", "match_type": "email_identity_company_internal_domain"}
    assert _should_auto_apply(opportunity, domain_company, confidence=96.0)
