"""Reply processing tests that enforce sequence stop behavior."""

from __future__ import annotations

import tempfile
import unittest
from datetime import datetime, timedelta

from kiessclaw.agents.inbox_agent import KiessInboxAgent
from kiessclaw.core.memory import MemoryEngine
from kiessclaw.models.contact import Contact

from tests.test_helpers import base_config


class ReplyStopSequenceTest(unittest.TestCase):
    """Validate all reply classes stop future sends for enrolled contacts."""

    def _setup_contact_with_reply(self, memory: MemoryEngine, reply_text: str, email: str) -> str:
        """Create contact, active enrollment, and unprocessed reply; return contact id."""
        contact = Contact(email=email, first_name="A", last_name="B", title="VP")
        memory.save_data("contacts", [contact.to_dict()])
        memory.save_data(
            "enrollments",
            [
                {
                    "id": "enr-1",
                    "sequence_id": "seq-1",
                    "contact_id": contact.id,
                    "status": "active",
                    "current_step": 1,
                    "next_send_at": (datetime.now() + timedelta(days=2)).isoformat(),
                }
            ],
        )
        memory.save_data(
            "replies",
            [
                {
                    "id": "rep-1",
                    "contact_id": contact.id,
                    "sent_message_id": "msg-1",
                    "raw_text": reply_text,
                    "processed": False,
                    "created_at": datetime.now().isoformat(),
                    "received_at": datetime.now().isoformat(),
                }
            ],
        )
        return contact.id

    def test_positive_reply_marks_enrollment_replied(self) -> None:
        """Positive replies must halt sequence progression."""
        with tempfile.TemporaryDirectory() as tempdir:
            memory = MemoryEngine(tempdir)
            agent = KiessInboxAgent(base_config(), memory)
            contact_id = self._setup_contact_with_reply(memory, "Sounds good, let's chat next week.", "pos@test.com")

            agent.run("process")

            enrollments = memory.load_data("enrollments")
            contacts = memory.load_data("contacts")
            enrollment = enrollments[0]
            contact = contacts[0]

            self.assertEqual(contact_id, enrollment["contact_id"])
            self.assertEqual("replied", enrollment["status"])
            self.assertIsNone(enrollment["next_send_at"])
            self.assertEqual("qualified", contact["status"])

    def test_neutral_reply_marks_enrollment_replied(self) -> None:
        """Neutral timing replies still stop sequence sends."""
        with tempfile.TemporaryDirectory() as tempdir:
            memory = MemoryEngine(tempdir)
            agent = KiessInboxAgent(base_config(), memory)
            self._setup_contact_with_reply(memory, "This is not the right time, please check back later.", "neutral@test.com")

            agent.run("process")

            enrollments = memory.load_data("enrollments")
            self.assertEqual("replied", enrollments[0]["status"])
            self.assertIsNone(enrollments[0]["next_send_at"])

    def test_negative_reply_marks_enrollment_replied_and_dnc(self) -> None:
        """Unsubscribe replies must stop sequence and enforce DNC."""
        with tempfile.TemporaryDirectory() as tempdir:
            memory = MemoryEngine(tempdir)
            agent = KiessInboxAgent(base_config(), memory)
            self._setup_contact_with_reply(memory, "Please unsubscribe me immediately.", "neg@test.com")

            agent.run("process")

            enrollments = memory.load_data("enrollments")
            contacts = memory.load_data("contacts")
            self.assertEqual("replied", enrollments[0]["status"])
            self.assertIsNone(enrollments[0]["next_send_at"])
            self.assertTrue(contacts[0]["dnc"])
            self.assertEqual("disqualified", contacts[0]["status"])


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