from pathlib import Path

from app.followup_service import FOLLOW_UP_CADENCES


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


def test_confirm_delivery_automation_is_disabled_by_default():
    config = read("app/config.py")
    assert "confirm_delivery_automation_enabled: bool = False" in config
    service = read("app/followup_service.py")
    assert 'status": "skipped_confirm_delivery_automation_disabled"' in service
    assert "allow_confirm_delivery: bool = False" in service


def test_automatic_cadences_never_materialize_confirm_delivery():
    for family in ("info", "quote", "payment", "generic"):
        assert all(step["action_code"] != "CONFIRM_DELIVERY" for step in FOLLOW_UP_CADENCES[family])


def test_manual_delivery_check_remains_available_without_cascade():
    service = read("app/followup_service.py")
    page = read("app/admin_ui/pages/opportunities.py")
    assert 'if key == "delivery":' in service
    assert 'action_code="CONFIRM_DELIVERY"' in service
    assert "allow_confirm_delivery=True" in service
    assert "cascade=False" in service
    assert '<option value="delivery">Verificar entrega (manual)</option>' in page
    assert "não cria confirmações de entrega automaticamente" in page


def test_backfill_filters_zero_value_and_any_pending_human_task_before_limit():
    script = read("scripts/sync_opportunity_followup_lifecycle.py")
    assert "COALESCE(o.value_amount, 0) > 0" in script
    assert "COALESCE(t.action_required, TRUE) = TRUE" in script
    assert "NOT EXISTS" in script
    assert "LIMIT :limit" in script
    assert script.index("NOT EXISTS") < script.index("LIMIT :limit")


def test_cleanup_script_is_dry_run_and_preserves_manual_checks():
    script = read("scripts/disable_automatic_confirm_delivery.py")
    assert 'parser.add_argument("--apply", action="store_true"' in script
    assert "Dry-run only" in script
    assert "MANUAL_DELIVERY_CHECK" in script
    assert "manual_delivery_check" in script
    assert "migration_v4928_1_5_127" in script
    assert "send_email" not in script


def test_cleanup_apply_qualifies_task_columns_in_update_from():
    script = read("scripts/disable_automatic_confirm_delivery.py")
    assert "done_at = COALESCE(t.done_at, now())" in script
    assert "metadata = COALESCE(t.metadata, '{}'::jsonb)" in script
