"""Tests for variable rendering and analytics calculations."""

from __future__ import annotations

import tempfile
import unittest

from kiessclaw.agents.sequencer_agent import KiessSequencerAgent
from kiessclaw.core.memory import MemoryEngine
from kiessclaw.skills.analytics import AnalyticsSkill

from tests.test_helpers import base_config


class RenderAndAnalyticsTest(unittest.TestCase):
    """Validate deterministic template rendering and funnel math."""

    def test_render_company_variable_uses_account_name(self) -> None:
        """`{{company}}` should fallback to account.name when absent on contact."""
        with tempfile.TemporaryDirectory() as tempdir:
            agent = KiessSequencerAgent(base_config(), MemoryEngine(tempdir))
            rendered = agent._render_variables(  # pylint: disable=protected-access
                "Hi {{first_name}} from {{company}}",
                contact={"first_name": "Jane", "company": "", "title": "VP"},
                sequence={},
                account={"name": "Acme Holdings"},
            )
            self.assertEqual("Hi Jane from Acme Holdings", rendered)

    def test_analytics_reply_metrics_use_reply_records(self) -> None:
        """Funnel reply/positive/meeting metrics should align with reply data."""
        skill = AnalyticsSkill(base_config())
        sequence_id = "seq-1"
        enrollments = [
            {"sequence_id": sequence_id, "contact_id": "c-1", "status": "active"},
            {"sequence_id": sequence_id, "contact_id": "c-2", "status": "active"},
        ]
        messages = [
            {"id": "m-1", "sequence_id": sequence_id, "bounced": False},
            {"id": "m-2", "sequence_id": sequence_id, "bounced": False},
        ]
        replies = [
            {"contact_id": "c-1", "sent_message_id": "m-1", "intent": "interested", "meeting_requested": True},
            {"contact_id": "c-2", "sent_message_id": "m-2", "intent": "not_now", "meeting_requested": False},
        ]

        funnel = skill.calculate_sequence_funnel(sequence_id, enrollments, messages, replies)
        self.assertEqual(2, funnel["replied"])
        self.assertEqual(1, funnel["positive_replies"])
        self.assertEqual(1, funnel["meetings"])


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