from pathlib import Path

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


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


def test_v484_operations_uses_opportunity_fiscal_customer_before_task_customer_id():
    service = read("app/operations_service.py")
    assert "LEFT JOIN customers cu_opp ON cu_opp.id = o.local_customer_id" in service
    assert "LEFT JOIN customers cu_task ON cu_task.id::text = t.customer_id" in service
    assert "COALESCE(cu_opp.name, cu_task.name, '') AS fiscal_customer_name" in service
    assert "COALESCE(NULLIF(re.payload->'sender'->>'name',''), NULLIF(re.payload->'sender'->>'email',''), NULLIF(t.contact_id,''), '') AS customer_name" in service
    assert "cu.name AS fiscal_customer_name" not in service.split("UNION ALL", 1)[0]


def test_v484_operations_blockers_use_actual_fiscal_missing_fields_not_only_association():
    guidance = read("app/admin_ui/guidance.py")
    assert "def work_item_fiscal_customer" in guidance
    assert "The work queue must not infer a fiscal customer from Chatwoot contact_id" in guidance
    assert "for missing in fiscal_customer_missing_fields(customer)" in guidance
    assert "Cliente fiscal sem {missing}" in guidance


def test_v484_task_detail_does_not_say_no_critical_data_when_fiscal_readiness_has_warnings():
    service = read("app/task_service.py")
    tasks = read("app/admin_ui/pages/tasks.py")
    assert "cu.street_name AS linked_customer_street_name" in service
    assert "cu.postal_zone AS linked_customer_postal_zone" in service
    assert "cu.city_name AS linked_customer_city_name" in service
    assert "fiscal_missing_labels = fiscal_customer_missing_fields" in tasks
    assert "Cliente fiscal: {label}" in tasks
    assert "_effective_missing_items_for_task" in tasks
    assert "fiscal_missing_labels=fiscal_missing_labels" in tasks


def test_v484_opportunity_queries_carry_full_fiscal_customer_fields():
    opp_service = read("app/opportunity_service.py")
    guidance = read("app/admin_ui/guidance.py")
    assert "c.street_name AS linked_customer_street_name" in opp_service
    assert "c.postal_zone AS linked_customer_postal_zone" in opp_service
    assert "c.city_name AS linked_customer_city_name" in opp_service
    assert "opportunity.get(\"linked_customer_street_name\")" in guidance
