from pathlib import Path


def test_backfill_apply_path_imports_engine_and_creates_normal_followup(monkeypatch):
    import importlib
    import importlib.util
    import sys

    script_path = Path("scripts/sync_opportunity_followup_lifecycle.py")
    spec = importlib.util.spec_from_file_location("sync_opportunity_followup_lifecycle_test", script_path)
    assert spec and spec.loader
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)

    candidate = {
        "id": "11111111-1111-1111-1111-111111111111",
        "customer_name": "Cliente Teste",
        "title": "Orçamento teste",
        "stage": "QUOTE_SENT",
        "value_amount": 100.0,
        "lifecycle_state": "active",
        "last_customer_activity_at": None,
        "last_operator_activity_at": None,
        "last_commercial_activity_at": None,
        "last_message_at": None,
        "next_follow_up_at": None,
        "nurture_until": None,
        "follow_up_attempts": 0,
    }
    monkeypatch.setattr(module, "_rows", lambda limit, include_zero_value=False: [candidate])

    executed = []

    class FakeConnection:
        def execute(self, statement, params=None):
            executed.append((str(statement), params or {}))
            return None

    class FakeBegin:
        def __enter__(self):
            return FakeConnection()

        def __exit__(self, exc_type, exc, tb):
            return False

    class FakeEngine:
        def begin(self):
            return FakeBegin()

    app_db = importlib.import_module("app.db")
    followup_service = importlib.import_module("app.followup_service")

    created_kwargs = []
    monkeypatch.setattr(app_db, "engine", FakeEngine())
    monkeypatch.setattr(
        followup_service,
        "materialize_initial_follow_up_for_opportunity",
        lambda **kwargs: created_kwargs.append(kwargs) or {"status": "created"},
    )
    monkeypatch.setattr(sys, "argv", [str(script_path), "--apply", "--limit", "1"])

    assert module.main() == 0
    assert executed
    assert "v4928.1.5.127" in executed[0][0]
    assert created_kwargs[0]["family"] == "quote"
    assert created_kwargs[0]["due_at"] is None
    assert created_kwargs[0]["created_by"] == "migration_v4928_1_5_127"
