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_v483_opportunity_creation_guardrails_exist():
    service = read("app/opportunity_service.py")
    assert "OPPORTUNITY_CREATE_ACTION_CODES" in service
    assert "NEVER_CREATE_OPPORTUNITY_ACTION_CODES" in service
    assert "SYSTEM_SENDER_PATTERNS" in service
    assert "Mail Delivery" not in service  # patterns are normalized lower-case
    assert "mail delivery subsystem" in service
    assert "returned mail" in service
    assert "def can_create_new_opportunity_for_task" in service
    assert "system_or_bounce_message" in service
    assert "send_info_without_clear_commercial_intent" in service


def test_v483_operations_card_is_compact_and_does_not_use_contact_as_fiscal_customer():
    ops_page = read("app/admin_ui/pages/operations.py")
    ops_service = read("app/operations_service.py")
    vm = read("app/admin_ui/view_models/operations.py")
    guidance = read("app/admin_ui/guidance.py")
    assert "operation_card_title" in ops_page
    assert "operation_card_subtitle" in ops_page
    assert "Ver detalhes" not in ops_page
    assert "work_item_blockers" in ops_page
    assert "Cliente fiscal" in guidance and "show_fiscal" in guidance
    assert "COALESCE(cu.name, t.customer_id, t.contact_id, '') AS customer_name" not in ops_service
    assert "fiscal_customer_name" in ops_service
    assert "contact_display_name" in ops_service
    assert "_is_numeric_reference" in vm
    assert "Contacto Chatwoot #" in vm


def test_v483_blockers_are_journey_aware():
    guidance = read("app/admin_ui/guidance.py")
    assert "DOCUMENT_ACTION_CODES" in guidance
    assert "stage_requires_fiscal_customer" in guidance
    assert "Missing fiscal data is not automatically a blocker at the first contact" in guidance
    assert "def work_item_blockers" in guidance
    assert "item_requires_fiscal_customer" in guidance


def test_v483_priority_demotes_review_marketing_noise():
    vm = read("app/admin_ui/view_models/operations.py")
    assert "is_classification_failed" in vm
    assert "REMOVE_FROM_LIST" in vm
    assert "REVIEW_MANUALLY" in vm
    assert "queue == \"marketing\"" in vm
    assert "sem oportunidade comercial" in vm


def test_v483_cleanup_script_for_bad_opportunities_exists():
    script = read("scripts/cleanup_non_commercial_opportunities.py")
    assert "system_or_bounce_created_by_mistake" in script
    assert "--apply" in script
    assert "Dry-run" in script
    assert "mail delivery subsystem" in script
