from pathlib import Path

from app.reply_recipient_utils import resolve_reply_recipient, apply_preferred_greeting


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

AMORASUB_MESSAGE = """Boa tarde,

Teve oportunidade de ver o email que lhe enviei sobre a morada?

Cumprimentos,

Alexandra Silvestre

Amorasub – Engenharia Hidráulica, Lda

Rua Manuel Teixeira Gomes, 9A

Paivas

2845-378 Amora
"""


def read(path: str) -> str:
    return (ROOT / path).read_text(encoding="utf-8")


def test_recipient_signature_person_has_priority_over_company_name():
    task = {
        "customer_name": "AMORASUB - ENGENHARIA HIDRÁULICA, UNIPESSOAL, LDA",
        "linked_customer_name": "AMORASUB - ENGENHARIA HIDRÁULICA, UNIPESSOAL, LDA",
        "request_text": AMORASUB_MESSAGE,
    }

    recipient = resolve_reply_recipient(task)

    assert recipient["person_name"] == "Alexandra Silvestre"
    assert recipient["company_name"] == "AMORASUB - ENGENHARIA HIDRÁULICA, UNIPESSOAL, LDA"
    assert recipient["preferred_greeting"] == "Boa tarde Sra. Alexandra Silvestre,"
    assert recipient["greeting_source"] == "signature"


def test_apply_preferred_greeting_replaces_company_greeting():
    message = apply_preferred_greeting(
        "Boa tarde Amorasub,\n\nConfirmamos a receção.",
        "Boa tarde Sra. Alexandra Silvestre,",
    )

    assert message.startswith("Boa tarde Sra. Alexandra Silvestre,")
    assert "Boa tarde Amorasub" not in message


def test_openrouter_context_contains_recipient_person_rules_static():
    source = read("app/llm_reply_generator.py")
    assert "recipient.person_name" in source
    assert "não cumprimentar com nome de empresa" in source
    assert "preferred_greeting" in source


def test_openai_agent_context_contains_recipient_person_rules_static():
    source = read("app/email_reply_agent_service.py")
    assert "destinatario_resposta" in source
    assert "A pessoa que assina a última mensagem tem prioridade" in source
    assert "preferred_greeting" in source or "cumprimento_preferido" in source


def test_prompt_instructs_address_followup_not_generic_analysis():
    source = read("app/llm_reply_generator.py")
    assert "follow-up sobre morada" in source
    assert "não responder genericamente" in source


def test_recipient_can_infer_person_from_personal_email_without_using_company_name():
    task = {
        "customer_name": "Verifone Portugal, Lda",
        "linked_customer_name": "Verifone Portugal, Lda",
        "customer_email": "nuno.silva@verifone.com",
    }

    recipient = resolve_reply_recipient(task)

    assert recipient["person_name"] == "Nuno Silva"
    assert recipient["person_first_name"] == "Nuno"
    assert recipient["greeting_source"] == "email"
    assert recipient["person_confidence"] == "alto"
    assert recipient["preferred_greeting"] == "Bom dia Sr. Nuno,"


def test_recipient_does_not_infer_person_from_generic_mailbox():
    task = {
        "customer_name": "Eficen",
        "customer_email": "escritorio@eficen.pt",
    }

    recipient = resolve_reply_recipient(task)

    assert recipient["person_name"] == ""
    assert recipient["preferred_greeting"] == "Bom dia,"
