#!/usr/bin/env python3
"""Small, auditable proof-of-work for a lead follow-up automation.

The demo is intentionally local and simple. It does not call any external
service. It receives lead-like JSON data, validates the input, prevents a
duplicate record, stores the lead in SQLite, routes it by service type, and
creates a follow-up task. The goal is to demonstrate workflow logic and
verification, not to claim production CRM experience.
"""
from __future__ import annotations

import hashlib
import json
import re
import sqlite3
import tempfile
from dataclasses import asdict, dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path

EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")


@dataclass(frozen=True)
class Lead:
    name: str
    email: str
    source: str
    service: str
    message: str = ""

    @property
    def key(self) -> str:
        normalized = f"{self.email.strip().lower()}|{self.service.strip().lower()}"
        return hashlib.sha256(normalized.encode("utf-8")).hexdigest()[:16]


def validate(lead: Lead) -> list[str]:
    """Return validation errors instead of silently correcting bad input."""
    errors: list[str] = []
    if len(lead.name.strip()) < 2:
        errors.append("name_too_short")
    if not EMAIL_RE.match(lead.email.strip()):
        errors.append("invalid_email")
    if not lead.source.strip():
        errors.append("missing_source")
    if not lead.service.strip():
        errors.append("missing_service")
    return errors


def route(service: str) -> str:
    """Small routing rule that could later become n8n/Make branches."""
    normalized = service.strip().lower()
    if any(term in normalized for term in ("website", "landing", "wordpress")):
        return "web-ops"
    if any(term in normalized for term in ("automation", "crm", "follow-up")):
        return "automation"
    return "marketing-ops"


def init_db(conn: sqlite3.Connection) -> None:
    conn.executescript(
        """
        CREATE TABLE IF NOT EXISTS leads (
            lead_key TEXT PRIMARY KEY,
            name TEXT NOT NULL,
            email TEXT NOT NULL,
            source TEXT NOT NULL,
            service TEXT NOT NULL,
            message TEXT NOT NULL,
            route TEXT NOT NULL,
            created_at TEXT NOT NULL
        );

        CREATE TABLE IF NOT EXISTS followups (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            lead_key TEXT NOT NULL,
            due_at TEXT NOT NULL,
            status TEXT NOT NULL,
            note TEXT NOT NULL
        );
        """
    )


def process(payload: dict[str, str], conn: sqlite3.Connection) -> dict:
    lead = Lead(**payload)
    errors = validate(lead)
    if errors:
        return {"status": "rejected", "errors": errors}

    duplicate = conn.execute(
        "SELECT 1 FROM leads WHERE lead_key = ?", (lead.key,)
    ).fetchone()
    if duplicate:
        return {"status": "duplicate", "lead_key": lead.key}

    now = datetime.now(timezone.utc)
    assigned_route = route(lead.service)

    conn.execute(
        "INSERT INTO leads VALUES (?,?,?,?,?,?,?,?)",
        (
            lead.key,
            lead.name.strip(),
            lead.email.strip().lower(),
            lead.source.strip(),
            lead.service.strip(),
            lead.message.strip(),
            assigned_route,
            now.isoformat(),
        ),
    )

    followup_due = now + timedelta(hours=24)
    conn.execute(
        "INSERT INTO followups (lead_key, due_at, status, note) VALUES (?,?,?,?)",
        (
            lead.key,
            followup_due.isoformat(),
            "queued",
            f"Review lead and prepare a context-aware follow-up for {lead.service}.",
        ),
    )
    conn.commit()

    return {
        "status": "accepted",
        "lead_key": lead.key,
        "route": assigned_route,
        "followup_due_utc": followup_due.isoformat(timespec="seconds"),
        "record": asdict(lead),
    }


def run_demo() -> dict:
    """Run one valid submission and the same submission again as a duplicate."""
    sample = {
        "name": "Demo Venue Manager",
        "email": "manager@example.com",
        "source": "landing-page",
        "service": "CRM automation",
        "message": "Need a follow-up workflow for event inquiries.",
    }

    with tempfile.TemporaryDirectory(prefix="sazvara-automation-demo-") as tmp:
        db_path = Path(tmp) / "demo.sqlite3"
        conn = sqlite3.connect(db_path)
        init_db(conn)

        first = process(sample, conn)
        second = process(sample, conn)
        lead_rows = conn.execute("SELECT COUNT(*) FROM leads").fetchone()[0]
        followup_rows = conn.execute("SELECT COUNT(*) FROM followups").fetchone()[0]
        conn.close()

    return {
        "first_submission": first,
        "duplicate_check": second,
        "lead_rows": lead_rows,
        "followup_rows": followup_rows,
        "checks": {
            "first_accepted": first.get("status") == "accepted",
            "duplicate_blocked": second.get("status") == "duplicate",
            "single_lead_record": lead_rows == 1,
            "single_followup_created": followup_rows == 1,
        },
    }


if __name__ == "__main__":
    print(json.dumps(run_demo(), ensure_ascii=False, indent=2))
