"""Tests for SEO -> SDR autonomous lead generation pipeline."""

from __future__ import annotations

import tempfile
import unittest
from unittest.mock import patch

from kiessclaw.core.memory import MemoryEngine
from kiessclaw.pipeline import LeadGenPipeline
from kiessclaw.skills.sequence import SequenceSkill

from tests.test_helpers import base_config


class _FakeKrawl:
    """Stub crawler agent returning predefined audit payloads."""

    def __init__(self, audit_result: dict):
        self._audit_result = audit_result

    def run(self, task: str, **kwargs):  # noqa: ANN003
        if task != "audit":
            raise ValueError("Unsupported task")
        return self._audit_result


class _FakeProspectSkill:
    """Stub prospect scoring implementation."""

    def __init__(self, score: int):
        self._score = score

    def score_icp_fit(self, _: dict) -> dict:
        return {"score": self._score, "breakdown": {}, "qualified": self._score >= 60}


class _FakeKpro:
    """Stub KPRO wrapper exposing prospect skill."""

    def __init__(self, score: int):
        self.prospect_skill = _FakeProspectSkill(score)


class _FakeKseq:
    """Stub KSEQ wrapper exposing memory and sequence operations."""

    def __init__(self, config: dict, memory: MemoryEngine):
        self.memory = memory
        self.sequence_skill = SequenceSkill(config)


class LeadGenPipelineTest(unittest.TestCase):
    """Validate trigger rules and outputs for automated lead generation."""

    def test_low_seo_score_triggers_enroll_and_webhook(self) -> None:
        """Low-score SEO audits should auto-enroll qualified contacts and call webhook."""
        with tempfile.TemporaryDirectory() as tempdir:
            config = base_config()
            config["klytics"] = {
                "enabled": True,
                "webhook_url": "https://example.test/hook",
                "lead_threshold": 60,
            }
            memory = MemoryEngine(tempdir)
            registry = {
                "KRAWL": _FakeKrawl(
                    {
                        "domain": "clinic.com",
                        "technical_score": 42,
                        "owner_contact": "ceo@clinic.com",
                        "pages_crawled": 5,
                    }
                ),
                "KPRO": _FakeKpro(score=65),
                "KSEQ": _FakeKseq(config, memory),
            }

            with patch.object(LeadGenPipeline, "_dispatch_webhook") as dispatch_mock:
                pipeline = LeadGenPipeline(config=config, registry=registry)
                result = pipeline.run_audit("https://clinic.com", auto_enroll=True)

            pipeline_state = result["pipeline"]
            enrollments = memory.load_data("enrollments")
            leads_log = (memory.memory_dir / "shared" / "leads.md").read_text(encoding="utf-8")

            self.assertTrue(pipeline_state["qualified"])
            self.assertTrue(pipeline_state["enrolled"])
            self.assertEqual(1, len(enrollments))
            self.assertIn("clinic.com", leads_log)
            self.assertEqual(1, dispatch_mock.call_count)

    def test_high_seo_score_skips_lead_gen_path(self) -> None:
        """High technical SEO score should skip qualification and enrollment path."""
        with tempfile.TemporaryDirectory() as tempdir:
            config = base_config()
            config["klytics"] = {"enabled": True, "webhook_url": "https://example.test/hook", "lead_threshold": 60}
            memory = MemoryEngine(tempdir)
            registry = {
                "KRAWL": _FakeKrawl(
                    {
                        "domain": "healthy-seo.com",
                        "technical_score": 88,
                        "owner_contact": "owner@healthy-seo.com",
                        "pages_crawled": 8,
                    }
                ),
                "KPRO": _FakeKpro(score=80),
                "KSEQ": _FakeKseq(config, memory),
            }

            with patch.object(LeadGenPipeline, "_dispatch_webhook") as dispatch_mock:
                pipeline = LeadGenPipeline(config=config, registry=registry)
                result = pipeline.run_audit("https://healthy-seo.com", auto_enroll=True)

            pipeline_state = result["pipeline"]
            enrollments = memory.load_data("enrollments")

            self.assertFalse(pipeline_state["qualified"])
            self.assertFalse(pipeline_state["enrolled"])
            self.assertEqual(0, len(enrollments))
            self.assertEqual(0, dispatch_mock.call_count)


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