"""Dry-run integrity tests for sequencer sends."""

from __future__ import annotations

import copy
import tempfile
import unittest
from datetime import datetime, timedelta

from kiessclaw.agents.sequencer_agent import KiessSequencerAgent
from kiessclaw.core.memory import MemoryEngine
from kiessclaw.models.account import Account
from kiessclaw.models.contact import Contact

from tests.test_helpers import base_config


class DryRunIntegrityTest(unittest.TestCase):
    """Ensure dry-run sends never mutate persisted runtime state."""

    def test_send_dry_run_does_not_mutate_workspace_data(self) -> None:
        """Validate dry-run leaves enrollments, contacts, and messages untouched."""
        with tempfile.TemporaryDirectory() as tempdir:
            config = base_config()
            memory = MemoryEngine(tempdir)
            agent = KiessSequencerAgent(config, memory)

            account = Account(domain="acme.com", name="Acme Corp")
            contact = Contact(
                account_id=account.id,
                email="jane@acme.com",
                first_name="Jane",
                last_name="Doe",
                title="VP Sales",
            )

            sequence = agent.sequence_skill.create_sequence(
                name="Dry Run Seq",
                sender_email="rep@kiessclaw.dev",
                steps=[
                    {
                        "channel": "email",
                        "delay_days": 0,
                        "subject": "Hi {{first_name}}",
                        "body": "Hello {{first_name}} at {{company}}.",
                    }
                ],
            )
            sequence["status"] = "active"
            enrollment = agent.sequence_skill.enroll_contact(sequence["id"], contact.id, start_immediately=True)
            enrollment["next_send_at"] = (datetime.now() - timedelta(minutes=5)).isoformat()

            memory.save_data("accounts", [account.to_dict()])
            memory.save_data("contacts", [contact.to_dict()])
            memory.save_data("sequences", [sequence])
            memory.save_data("enrollments", [enrollment])
            memory.save_data("messages", [])

            before_contacts = copy.deepcopy(memory.load_data("contacts"))
            before_enrollments = copy.deepcopy(memory.load_data("enrollments"))
            before_messages = copy.deepcopy(memory.load_data("messages"))

            result = agent.run("send", dry_run=True, limit=10)

            after_contacts = memory.load_data("contacts")
            after_enrollments = memory.load_data("enrollments")
            after_messages = memory.load_data("messages")

            self.assertIn("[DRY RUN]", result)
            self.assertIn("No state was modified.", result)
            self.assertEqual(before_contacts, after_contacts)
            self.assertEqual(before_enrollments, after_enrollments)
            self.assertEqual(before_messages, after_messages)


if __name__ == "__main__":
    unittest.main()
