"""5-stage message validation pipeline.

Ensures every outreach message passes quality checks before sending.
From the spec: "Your 56 prompt versions and 5-stage validation pipeline
are not features — they are THE product."

Stages:
1. Length check (≤200 chars for regular LinkedIn)
2. Salesy language detection
3. AI-tell patterns detection
4. Voice consistency check
5. Generic phrase detection
"""

from __future__ import annotations

import logging
import re
from typing import Any

logger = logging.getLogger(__name__)

# ──────────────────────────────────────────────
# Stage 2: Salesy language blocklist
# ──────────────────────────────────────────────

SALESY_PHRASES = [
    "leverage",
    "synergy",
    "exciting opportunity",
    "game-changer",
    "cutting-edge",
    "revolutionary",
    "transform your",
    "skyrocket",
    "unlock the power",
    "world-class",
    "best-in-class",
    "take your business to the next level",
    "scale your",
    "maximize your",
    "disruptive",
    "paradigm shift",
    "thought leader",
    "low-hanging fruit",
    "value proposition",
    "circle back",
    "move the needle",
    "boil the ocean",
    "deep dive",
    "hop on a call",
    "hop on a quick call",
    "let's connect",
    "would love to connect",
    "pick your brain",
    "touch base",
    "quick chat",
    "quick question",
    "no-brainer",
]

# ──────────────────────────────────────────────
# Stage 3: AI-tell patterns
# ──────────────────────────────────────────────

AI_TELL_PATTERNS = [
    r"^I noticed (you|your|that you)",
    r"^I came across your",
    r"^I saw your (profile|post|article)",
    r"^I was impressed by",
    r"^Hope this message finds you",
    r"^I'm reaching out because",
    r"^I'd love to",
    r"^I stumbled upon",
    r"^Your work on .+ caught my (eye|attention)",
    r"^As a fellow",
    r"I believe (we|our|I) can",
    r"I'm confident that",
    r"I'm sure you're busy",
    r"Don't hesitate to",
    r"Feel free to",
    r"Looking forward to",
    r"Best regards",
    r"Warm regards",
    r"Kind regards",
]

# ──────────────────────────────────────────────
# Stage 5: Generic phrases
# ──────────────────────────────────────────────

GENERIC_PHRASES = [
    "in your industry",
    "in your field",
    "in your space",
    "professionals like you",
    "leaders like you",
    "people like you",
    "your company",  # Too vague — should name the company
    "your role",
    "your position",
    "mutual connections",
    "shared interests",
]


class ValidationResult:
    """Result of the 5-stage message validation."""

    def __init__(self) -> None:
        self.is_valid = True
        self.issues: list[str] = []
        self.warnings: list[str] = []
        self.stage_results: dict[str, bool] = {}

    def fail(self, stage: str, reason: str) -> None:
        self.is_valid = False
        self.issues.append(f"[{stage}] {reason}")
        self.stage_results[stage] = False

    def warn(self, stage: str, reason: str) -> None:
        self.warnings.append(f"[{stage}] {reason}")

    def pass_stage(self, stage: str) -> None:
        self.stage_results[stage] = True


def validate_message(
    message: str,
    voice_signature: dict[str, Any] | None = None,
    max_chars: int = 200,
) -> ValidationResult:
    """Run the 5-stage validation pipeline on a message.

    Args:
        message: The generated message text
        voice_signature: User's voice analysis (for stage 4)
        max_chars: Character limit (200 regular, 300 Sales Nav)

    Returns:
        ValidationResult with pass/fail and details
    """
    result = ValidationResult()
    msg_lower = message.lower().strip()

    # ── Stage 1: Length check ──
    if len(message) > max_chars:
        result.fail("Length", f"Message is {len(message)} chars (max {max_chars})")
    elif len(message) < 20:
        result.fail("Length", f"Message is too short ({len(message)} chars) — needs personalization")
    else:
        result.pass_stage("Length")

    # ── Stage 2: Salesy language ──
    found_salesy = [phrase for phrase in SALESY_PHRASES if phrase in msg_lower]
    if found_salesy:
        result.fail("Salesy", f"Contains salesy phrases: {', '.join(found_salesy[:3])}")
    else:
        result.pass_stage("Salesy")

    # ── Stage 3: AI-tell patterns ──
    found_ai_tells = []
    for pattern in AI_TELL_PATTERNS:
        if re.search(pattern, message, re.IGNORECASE):
            found_ai_tells.append(pattern.replace(r"^", "").replace("\\", ""))
    if found_ai_tells:
        result.fail("AI-tells", f"Sounds AI-generated: matches {len(found_ai_tells)} known patterns")
    else:
        result.pass_stage("AI-tells")

    # ── Stage 4: Voice consistency ──
    if voice_signature:
        formality = voice_signature.get("formality_level", 5)
        no_go = voice_signature.get("no_go", "").lower()

        # Check formality mismatch
        has_exclamation = "!" in message
        has_emoji = bool(re.search(r"[\U0001f600-\U0001f650]", message))

        if formality >= 8 and (has_exclamation or has_emoji):
            result.warn("Voice", "Message is too casual for this user's formal tone")

        if formality <= 3 and not has_exclamation and len(message) > 150:
            result.warn("Voice", "Message is too formal for this user's casual tone")

        # Check no-go words
        if no_go:
            no_go_words = [w.strip() for w in no_go.split(",")]
            found_nogo = [w for w in no_go_words if w and w in msg_lower]
            if found_nogo:
                result.fail("Voice", f"Uses no-go words: {', '.join(found_nogo)}")
            else:
                result.pass_stage("Voice")
        else:
            result.pass_stage("Voice")
    else:
        result.pass_stage("Voice")

    # ── Stage 5: Generic phrases ──
    found_generic = [phrase for phrase in GENERIC_PHRASES if phrase in msg_lower]
    if found_generic:
        result.warn("Generic", f"Contains generic phrases: {', '.join(found_generic[:2])}")
    result.pass_stage("Generic")

    return result
