from pathlib import Path


def test_task_detail_has_identity_guard_helpers():
    source = Path("app/admin_ui/pages/tasks.py").read_text(encoding="utf-8")

    assert "def _task_identity_context" in source
    assert "linked_fiscal_customer_mismatch_process_hint" in source
    assert "def _safe_fiscal_customer_for_task" in source
    assert "def _task_identity_warning_html" in source
    assert "Cliente fiscal por confirmar" in source


def test_task_detail_does_not_show_unsafe_fiscal_customer_as_ready():
    source = Path("app/admin_ui/pages/tasks.py").read_text(encoding="utf-8")

    assert "_safe_fiscal_customer_for_task(task, safe_customer_id)" in source
    assert "customer_href=f\"/customers/{esc(safe_customer_id)}\" if safe_customer_id and fiscal_customer else \"\"" in source
    assert "fiscal_missing_labels = [\"Cliente fiscal por confirmar\", *fiscal_missing_labels]" in source
    assert "_apply_identity_context_to_preparation(build_preparation_view_model(task, preparation), task)" in source


def test_task_detail_uses_contact_email_before_linked_customer_email():
    source = Path("app/admin_ui/pages/tasks.py").read_text(encoding="utf-8")

    email_fn = source.split("def _task_email", 1)[1].split("def _task_contact_person", 1)[0]
    assert "ctx.get(\"contact_email\")" in email_fn
    assert email_fn.index("ctx.get(\"contact_email\")") < email_fn.index("task.get(\"linked_customer_email\")")
