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_v490_has_shared_noise_detector_and_filters_operations_queue():
    noise = read("app/operation_noise.py")
    ops = read("app/operations_service.py")

    assert "SYSTEM_SENDER_PATTERNS" in noise
    assert "BOUNCE_NDR_PATTERNS" in noise
    assert "Mail Delivery System".casefold() in noise.casefold()
    assert "undeliverable" in noise
    assert "recipient" in noise
    assert "is_noise_operation_item" in ops
    assert "is_low_value_no_opportunity_item" in ops
    assert "not in the daily work queue" in ops


def test_v490_generic_review_and_marketing_are_not_high_priority_by_default():
    task_service = read("app/task_service.py")
    vm = read("app/admin_ui/view_models/operations.py")

    assert 'code in {"REVIEW_MANUALLY", "REMOVE_FROM_LIST", "MARK_NO_INTEREST", "IGNORE_SPAM", "NO_ACTION", "IGNORE_BOUNCE"}' in task_service
    assert 'return "baixa"' in task_service
    assert 'action_code in {"REMOVE_FROM_LIST", "IGNORE_SPAM", "NO_ACTION", "REVIEW_MANUALLY"}' in vm
    assert "return False" in vm.split('def is_high_priority', 1)[1].split('def is_blocked', 1)[0]


def test_v490_cleanup_script_marks_noise_tasks_skipped_dry_run_by_default():
    script = read("scripts/cleanup_operations_noise.py")

    assert "Dry-run only" in script
    assert "--apply" in script
    assert "task_skipped_noise_cleanup" in script
    assert "cleanup_operations_noise" in script
    assert "Marked" in script
    assert "Mail Delivery System".casefold() in script.casefold()


def test_v490_documentation_exists():
    doc = read("docs/CLIENTFLOW_V490_OPERATIONS_NOISE_CLEANUP.md")
    assert "Operations Noise Cleanup" in doc
    assert "postmaster" in doc
    assert "Mail Delivery" in doc
    assert "Não requer migração de base de dados" in doc
