#!/usr/bin/env python3
# FROZEN COPY of the round-1 engine (December 4, 2026). Kept only so eval.py can reproduce round-1 numbers. Do not edit.
"""Lead triage for the BigLife360.com contact form.

Reads leads (JSON lines or CSV), classifies each one, scores buyer intent,
sets a reply priority and deadline, drafts a reply where one is useful, and
writes out/triaged.csv, out/digest.md and out/run.log.

It never sends anything. Drafts wait for a human to approve and send them.

Engines:
  rules  transparent keyword and feature scoring, offline, every reason shown
  llm    any OpenAI-compatible chat endpoint (LLM_BASE_URL, LLM_API_KEY,
         LLM_MODEL); output is validated and falls back to rules on any error

Python 3 standard library only.
Usage: python3 triage.py sample/inbox.csv
"""
import argparse
import csv
import json
import os
import re
import sys
import urllib.error
import urllib.request
from dataclasses import dataclass, field
from datetime import date, datetime, time, timedelta, timezone
from pathlib import Path

HERE = Path(__file__).resolve().parent
CATEGORIES = ("buyer", "vendor_pitch", "partnership", "support", "spam")
LEAD_FIELDS = ("name", "email", "company", "need", "message", "received_at")
REPLY_CATEGORIES = ("buyer", "partnership", "support")
PRIORITY_TEXT = {
    "P1": "reply within 1 business hour",
    "P2": "reply today",
    "P3": "weekly batch (Friday)",
    "P4": "archive",
}
P1_INTENT = 60  # buyer_intent at or above this is P1

try:
    from zoneinfo import ZoneInfo
    BIZ_TZ = ZoneInfo("America/Chicago")
except Exception:  # tzdata missing (some Windows installs): fixed Central Standard Time
    BIZ_TZ = timezone(timedelta(hours=-6), "CST")
OPEN, CLOSE = time(9, 0), time(17, 0)


# ---------------------------------------------------------------- loading

def load_leads(path):
    """Load leads from .csv or .jsonl. Skips JSONL metadata lines ({"_meta": ...})."""
    path = Path(path)
    if not path.exists():
        raise FileNotFoundError(f"input not found: {path}")
    rows = []
    if path.suffix.lower() == ".csv":
        with path.open(newline="", encoding="utf-8-sig") as f:
            rows = list(csv.DictReader(f))
    else:
        with path.open(encoding="utf-8") as f:
            for n, line in enumerate(f, 1):
                line = line.strip()
                if not line:
                    continue
                try:
                    obj = json.loads(line)
                except json.JSONDecodeError as e:
                    raise ValueError(f"{path}:{n}: not valid JSON ({e.msg})") from None
                if isinstance(obj, dict) and "_meta" not in obj:
                    rows.append(obj)
    leads = []
    for i, row in enumerate(rows, 1):
        lead = {k: str(row.get(k) or "").strip() for k in LEAD_FIELDS}
        lead["id"] = str(row.get("id") or f"L{i:03d}")
        if not lead["message"] and not lead["need"]:
            lead["message"] = "(empty)"
        leads.append(lead)
    return leads


def parse_time(value):
    """ISO 8601 string to an aware datetime in business time, or None."""
    if not value:
        return None
    try:
        dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
    except ValueError:
        return None
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=BIZ_TZ)
    return dt.astimezone(BIZ_TZ)


# ---------------------------------------------------------------- rules engine
# Each signal: (category, weight, name, regex). Every hit becomes a reason line.

SIGNALS = [
    # buyer: someone who may pay BigLife360
    ("buyer", 20, "asks about price or budget",
     r"\bhow much\b|\bwhat (does|would|will) (that|it|this)\b.{0,25}\bcost\b|\bpric(e|es|ing)\b|\bquote\b|\bbudget\b|\bpackage\b"),
    ("buyer", 15, "names their own business",
     r"\b(my|our) (\w+ ){0,2}(business|shop|store|restaurant|taqueria|cafe|salon|practice|clinic|office|company|truck|firm|spa|bakery|gym|brokerage|location|menu)\b|\bi run a\b"),
    ("buyer", 12, "states a need or asks for the work",
     r"\b(i|we) (need|want)\b|\bneed (\d+|help)\b|\b(i|we) ?'?d like (to (try|get|order|buy|book|start)|them|some)\b|\b(we're|we are|i'm|i am) looking for\b|\b(can|could) you (make|build|create|do|look|help)\b|\bcan we talk\b|\bplease send\b"),
    ("buyer", 10, "mentions an ads service",
     r"\b(video )?ads?\b|\bshort videos?\b|\breels?\b|\bsample\b"),
    ("buyer", 10, "mentions an AI or automation service",
     r"\bai (assistant|tools?)\b|\bautomat\w*"),
    ("buyer", 15, "asks for the free sample",
     r"\b(first|free) sample\b|\btry one\b|\bwhat do you need from me\b"),
    ("buyer", 8, "asks to be contacted or for examples",
     r"\bcall me\b|\bdo you have (examples|samples)\b|\binterested in your\b"),
    ("buyer", 6, "gives a timeline",
     r"\bbefore (jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\w*\b|\bturnaround\b|\bopening\b"),

    # vendor_pitch: someone selling to BigLife360
    ("vendor_pitch", 18, "describes services they sell",
     r"\bwe (help|specialize|provide|offer|book|build|can help|work with|deliver)\b|\bour (team|agency|platform|software|tool|services?|network|virtual assistants?|developers|creators|ai chatbot|chatbot)\b"),
    ("vendor_pitch", 15, "critiques or audits BigLife360's own site",
     r"\b(noticed|came across)\b.{0,20}\b(your (website|site)|biglife360)\b|\byour (website|site) (isn'?t|is not|could|needs|has|is missing)\b"),
    ("vendor_pitch", 15, "addresses George as a prospect",
     r"\b(consultants|businesses|agencies|companies|owners) like (you|yours)\b|\bwho handles\b|\bdecision[- ]maker\b|\bare you (overwhelmed|struggling|tired)\b"),
    ("vendor_pitch", 12, "sales call-to-action",
     r"\b(quick|short|\d+[- ]minute) (call|chat)\b|\b(set up|book|schedule) a demo\b|\bcase studies\b|\brate card\b|\bfree trial\b|\binterested\?\s*$"),
    ("vendor_pitch", 12, "quotes their own price",
     r"\$\d+(\.\d+)?\s*(/|per\s*)(hr|hour|spot|month|post|meeting)\b|\bpay per\b|\bflat fee\b|\baffordable rates\b|\bstarts? at \$"),
    ("vendor_pitch", 12, "positions as a supplier",
     r"\bsupplier\b|\bgo-to\b|\boutsourc\w*|\bproject requirements\b|\bwe are a\b.{0,40}\b(company|agency)\b|\bi'?m a freelance\b|\b(we're|we are) a\b.{0,30}\bnetwork\b|\bi'?m with\b"),

    # partnership: two-way or no-money asks
    ("partnership", 25, "asks for a partnership, referral or resale",
     r"\bpartner\w*|\bcollab\w*|\bjoint (offer|venture)\b|\breferral\w*|\brefer (them|clients|you)\b|\bsend them to you\b|\brev(enue)? share\b|\bwhite[- ]label\b|\bwholesale\b|\bcross[- ]promot\w*|\bco-?present\w*|\bco-?host\w*|\bpodcast\b|\bas a guest\b|\bworkshop\b|\bbundle\w*|\baffiliate\b"),
    ("partnership", 10, "frames it as mutual benefit",
     r"\bboth of us\b|\bour (clients|members)\b|\bmy clients\b|\bfellow\b|\boverlap\b"),

    # support: an existing customer
    ("support", 22, "refers to work already delivered",
     r"\b(got|received|came through|delivered)\b.{0,20}\b(ads?|files?|video)\b|\bthe ad you made\b|\bour (sample )?ads?\b|\bin our ad\b|\bthe (first|second|third|last) one\b|\b(9:16|4:5)\b|\bthe \d+ ads?\b"),
    ("support", 22, "billing or payment question",
     r"\binvoice\b|\bcharged\b|\brefund\b|\bhow do i pay\b|\bpaid\b|\breceipt\b"),
    ("support", 18, "reports a problem or asks for a change",
     r"\b(change|fix|update|edit|correct)\b.{0,30}\b(number|price|caption|text|logo|phone|name|address)\b|\bwrong\b|\bcut off\b|\bnot working\b|\bbroken\b|\bflagged\b|\blicense\b|\bdownload\b|\bversion\b|\bfix\b"),

    # spam: bulk, scams, link drops
    ("spam", 30, "SEO or link-selling spam",
     r"\b(1st|first) page of google\b|\bguarantee\w*|\bbacklinks?\b|\bguest posts?\b|\bhigh da\b|\bmoney back\b|\breply with\W+yes\b"),
    ("spam", 35, "scam, phishing or gambling pattern",
     r"\bcongratulations\b|\byou have been selected\b|\bbtc\b|\bbitcoin\b|\bcrypto\b|\bclaim (within|now)\b|\bcasino\b|\bfree spins\b|\bwidow\b|\bmillion\b|\bbank details\b|\bexpires today\b|\brenew now\b|\bdear (website owner|sir|madam|friend)\b|\bhello dear\b"),
]
SIGNALS = [(c, w, n, re.compile(rx, re.I)) for c, w, n, rx in SIGNALS]

URL_RX = re.compile(r"https?://[^\s)>\]]+|\bwww\.[^\s)>\]]+", re.I)
URGENT_RX = re.compile(r"\burgent\b|\basap\b|\brunning (right )?now\b|\bcharged twice\b|\bwrong price\b|\bemergency\b", re.I)

# Prompt-injection patterns (common public patterns: instruction override,
# role change, prompt extraction, fake role headers, requests to set outputs).
INJECTION_RX = re.compile(
    r"\b(ignore|disregard|forget|override)\b.{0,30}\b(previous|prior|above|all|earlier|your)\b.{0,20}\b(instructions?|rules|prompts?|messages?)\b"
    r"|\byou are now\b|\bact as (an? )?(admin|system|developer)\b|\b(admin|developer|god|jailbreak) mode\b"
    r"|\b(reveal|print|show|repeat)\b.{0,20}\b(system )?prompt\b|\bsystem prompt\b"
    r"|(^|\n|\.\s)\s*(system|assistant|developer)\s*:"
    r"|\b(mark|classify|label|flag|set|tag)\b.{0,40}\b(as|to)\b.{0,15}\b(p1|priority|buyer|hot lead|urgent)\b"
    r"|\b(note to|message for|attention) (any |the )?(ai|assistant|llm|model|bot)\b"
    r"|\bforward (all|every|these)\b.{0,20}\b(leads?|emails?|messages?)\b",
    re.I,
)

STOPWORDS = set("""a an the i we you my our your me us it is are was be to of in on for and or
not no yes how what when can could do does need please hi hello thanks this that with
from at by as so if""".split())


def _snippet(m):
    s = " ".join(m.group(0).split())
    return s if len(s) <= 32 else s[:29] + "..."


def detect_injection(text):
    m = INJECTION_RX.search(text)
    return _snippet(m) if m else None


def is_gibberish(text):
    words = re.findall(r"[a-z']+", text.lower())
    if len(words) < 3 or any(w in STOPWORDS for w in words):
        return False
    return sum(bool(re.search(r"[bcdfghjklmnpqrstvwxz]{4,}", w)) for w in words) >= max(2, len(words) // 2)


@dataclass
class Result:
    category: str
    buyer_intent: int
    reasons: list
    injection_suspected: bool = False
    need_summary: str = ""
    engine: str = "rules"
    priority: str = ""
    reply_by: str = ""
    status: str = ""
    draft_subject: str = ""
    draft_body: str = ""
    scores: dict = field(default_factory=dict)


def classify_rules(lead):
    """Score every category with explained signals. Returns a Result (no priority yet)."""
    text = f"{lead.get('need', '')}\n{lead.get('message', '')}".strip()
    scores = {c: 0 for c in CATEGORIES}
    reasons = []
    for cat, weight, name, rx in SIGNALS:
        m = rx.search(text)
        if m:
            scores[cat] += weight
            reasons.append(f"+{weight} {cat}: {name} ('{_snippet(m)}')")

    urls = [u for u in URL_RX.findall(text) if "biglife360.com" not in u.lower()]
    if urls:
        w = min(36, 12 * len(urls))
        scores["spam"] += w
        reasons.append(f"+{w} spam: {len(urls)} outside link(s)")
    if is_gibberish(text):
        scores["spam"] += 40
        reasons.append("+40 spam: no recognizable words")
    inj = detect_injection(text)
    if inj:
        scores["spam"] += 20
        reasons.append(f"+20 spam: prompt-injection attempt ('{inj}')")

    best = max(scores.values())
    if best < 10:
        category = "buyer"  # unknown goes to a human, never to the archive
        reasons.append("no strong signal: treated as a possible buyer so a person reads it")
    else:
        # ties resolve toward the category whose miss costs most
        category = next(c for c in ("buyer", "support", "partnership", "vendor_pitch", "spam") if scores[c] == best)

    buyer_points = scores["buyer"]
    if category == "buyer":
        intent = 25 + buyer_points - scores["vendor_pitch"] // 2
        intent = max(20, min(100, intent))
    else:
        intent = min(15, buyer_points // 4)
    return Result(category=category, buyer_intent=int(intent), reasons=reasons,
                  injection_suspected=bool(inj), scores=scores)


# ---------------------------------------------------------------- priority and deadlines

def _open_at(dt):
    """Move dt forward to the next moment inside business hours (Mon to Fri, 9 to 5)."""
    for _ in range(10):
        if dt.weekday() >= 5 or dt.time() >= CLOSE:
            dt = (dt + timedelta(days=1)).replace(hour=OPEN.hour, minute=0, second=0, microsecond=0)
        elif dt.time() < OPEN:
            return dt.replace(hour=OPEN.hour, minute=0, second=0, microsecond=0)
        else:
            return dt
    return dt


def reply_deadline(received, priority):
    """Deadline as an aware datetime, or None for P4 or unknown time. Ignores public holidays."""
    if received is None or priority == "P4":
        return None
    start = _open_at(received)
    close = start.replace(hour=CLOSE.hour, minute=0, second=0, microsecond=0)
    if priority == "P1":
        due = start + timedelta(hours=1)
        if due > close:
            due = _open_at(close) + (due - close)
        return due
    if priority == "P2":
        return close
    days_to_friday = (4 - start.weekday()) % 7
    return (start + timedelta(days=days_to_friday)).replace(hour=CLOSE.hour, minute=0, second=0, microsecond=0)


def set_priority(lead, res):
    text = f"{lead.get('need', '')} {lead.get('message', '')}"
    if res.category == "buyer":
        p = "P1" if res.buyer_intent >= P1_INTENT else "P2"
    elif res.category == "support":
        p = "P1" if URGENT_RX.search(text) else "P2"
        if p == "P1":
            res.reasons.append("support marked urgent: P1")
    elif res.category == "partnership":
        p = "P3"
    else:
        p = "P4"
    if res.injection_suspected and p in ("P1", "P2"):
        p = "P3"
        res.reasons.append("priority capped at P3: prompt injection suspected")
    res.priority = p
    due = reply_deadline(parse_time(lead.get("received_at")), p)
    res.reply_by = due.isoformat(timespec="minutes") if due else ""
    return res


# ---------------------------------------------------------------- replies (templates)

TITLES = {"dr", "dr.", "mr", "mr.", "mrs", "mrs.", "ms", "ms.", "mx", "mx."}


def first_name(name):
    parts = [p for p in name.split() if p.lower() not in TITLES]
    first = parts[0] if parts else ""
    return first if first.replace("-", "").replace("'", "").isalpha() else "there"


def service_of(lead):
    text = f"{lead.get('need', '')} {lead.get('message', '')}".lower()
    if re.search(r"\bads?\b|video|reel|tiktok|sample|instagram|facebook", text):
        return "ads"
    if re.search(r"\bai\b|automat|assistant|email|repl(y|ies)", text):
        return "automation"
    return "general"


def template_reply(lead, res):
    who = first_name(lead.get("name", ""))
    biz = lead.get("company") or "your business"
    if res.category == "buyer":
        if service_of(lead) == "ads":
            subject = f"Re: video ads for {biz}"[:70]
            body = (f"Hi {who},\n\nThanks for reaching out. I make 15 to 30 second vertical ads for Reels, "
                    f"TikTok and Shorts, with captions burned in. Pricing is $50 for 1 ad, $140 for 3 and $230 for 5, "
                    f"and the first sample ad is free so you can see the style before you pay.\n\n"
                    f"Could you send 5 to 10 photos or a short clip, plus the one offer you want to push? "
                    f"I'll take it from there.\n\nGeorge")
        else:
            subject = "Re: your BigLife360 inquiry"
            body = (f"Hi {who},\n\nThanks for the note. This is the kind of work I do: I look at how the task runs "
                    f"today, then build the simplest AI setup that takes the repetitive part off your plate.\n\n"
                    f"Are you open to a 20-minute call this week? Send me two times that work and I'll confirm one.\n\nGeorge")
    elif res.category == "partnership":
        subject = "Re: working together"
        body = (f"Hi {who},\n\nThanks for thinking of me. I'm open to hearing more. Could you send a short outline "
                f"of how you see it working: who does what, and how clients or credit are shared? "
                f"If it fits, we can set up a call.\n\nGeorge")
    else:  # support
        when = "within the hour" if res.priority == "P1" else "later today"
        subject = "Re: your ad"
        body = (f"Hi {who},\n\nThanks for letting me know. I'm on it and will get back to you {when}. "
                f"If you have a screenshot or file that shows the issue, reply with it here and I'll use it.\n\nGeorge")
    return subject, body


# ---------------------------------------------------------------- LLM engine

class LLMError(Exception):
    pass


def load_prompt(filename):
    text = (HERE / "prompts" / filename).read_text(encoding="utf-8")
    m = re.search(r"<!-- PROMPT START -->\s*(.*?)\s*<!-- PROMPT END -->", text, re.S)
    if not m:
        raise LLMError(f"prompt markers missing in prompts/{filename}")
    return m.group(1)


EMAIL_RX = re.compile(r"[\w.+-]+@[\w-]+(\.[\w-]+)+")
PHONE_RX = re.compile(r"\+?\d[\d\s().-]{7,}\d")


def redact(text):
    return PHONE_RX.sub("[phone]", EMAIL_RX.sub("[email]", text))


def lead_block(lead, *, include_first_name=False, do_redact=True):
    """The only lead data sent to an LLM: no email address, no full name."""
    data = {"company": lead.get("company", ""), "need": lead.get("need", ""), "message": lead.get("message", "")}
    if include_first_name:
        data["first_name"] = first_name(lead.get("name", ""))
    if do_redact:
        data = {k: redact(v) for k, v in data.items()}
    return "<lead>\n" + json.dumps(data, ensure_ascii=False) + "\n</lead>"


def http_chat(messages, *, base_url, api_key, model, timeout=30):
    """POST to an OpenAI-compatible /chat/completions endpoint and return the message text."""
    url = base_url.rstrip("/") + "/chat/completions"
    body = json.dumps({"model": model, "messages": messages, "temperature": 0}).encode()
    req = urllib.request.Request(url, data=body, method="POST", headers={
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key or 'none'}",
    })
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            payload = json.loads(resp.read().decode("utf-8"))
        return payload["choices"][0]["message"]["content"]
    except (urllib.error.URLError, TimeoutError, KeyError, IndexError, TypeError, json.JSONDecodeError) as e:
        raise LLMError(f"endpoint call failed: {type(e).__name__}: {e}") from None


def parse_json_object(text):
    if not isinstance(text, str):
        raise LLMError("model returned no text")
    t = re.sub(r"^```(?:json)?\s*|\s*```$", "", text.strip(), flags=re.I)
    start, end = t.find("{"), t.rfind("}")
    if start < 0 or end <= start:
        raise LLMError("no JSON object in model output")
    try:
        obj = json.loads(t[start:end + 1])
    except json.JSONDecodeError as e:
        raise LLMError(f"invalid JSON from model: {e.msg}") from None
    if not isinstance(obj, dict):
        raise LLMError("model output is not a JSON object")
    return obj


def validate_classification(obj):
    cat = obj.get("category")
    if cat not in CATEGORIES:
        raise LLMError(f"bad category: {cat!r}")
    intent = obj.get("buyer_intent")
    if isinstance(intent, bool) or not isinstance(intent, (int, float)) or not 0 <= intent <= 100 or intent != int(intent):
        raise LLMError(f"bad buyer_intent: {intent!r}")
    reasons = obj.get("reasons")
    if not isinstance(reasons, list) or not 1 <= len(reasons) <= 6 or not all(isinstance(r, str) and r.strip() for r in reasons):
        raise LLMError("bad reasons: need 1 to 6 non-empty strings")
    inj = obj.get("injection_suspected", False)
    if not isinstance(inj, bool):
        raise LLMError("bad injection_suspected: must be true or false")
    summary = obj.get("need_summary", "")
    if not isinstance(summary, str):
        raise LLMError("bad need_summary")
    if cat != "buyer":
        intent = min(intent, 15)
    return {"category": cat, "buyer_intent": int(intent), "reasons": [r.strip()[:160] for r in reasons],
            "injection_suspected": inj, "need_summary": summary.strip()[:120]}


ALLOWED_PRICES = {"50", "140", "230"}


def validate_reply(obj):
    subject, body = obj.get("subject"), obj.get("body")
    if not isinstance(subject, str) or not isinstance(body, str) or not subject.strip() or not body.strip():
        raise LLMError("reply needs non-empty subject and body")
    words = len(body.split())
    if not 25 <= words <= 130:
        raise LLMError(f"reply length {words} words is outside 25 to 130")
    if re.search("[\u2013\u2014]", subject + body):
        raise LLMError("reply contains a dash character")
    for url in URL_RX.findall(body) + re.findall(r"\b[\w-]+\.(?:com|net|org|io|co)\b\S*", body):
        if "biglife360.com" not in url.lower():
            raise LLMError(f"reply contains a link that is not allowed: {url}")
    bad_prices = set(re.findall(r"\$(\d+)", body)) - ALLOWED_PRICES
    if bad_prices:
        raise LLMError(f"reply contains prices that are not on the price list: {sorted(bad_prices)}")
    if "george" not in body.lower():
        raise LLMError("reply is not signed by George")
    return subject.strip()[:80], body.strip()


class LLMEngine:
    """Calls an OpenAI-compatible endpoint. `transport(messages) -> str` can be injected for tests."""

    def __init__(self, transport=None, do_redact=True):
        self.do_redact = do_redact
        if transport is None:
            base = os.environ.get("LLM_BASE_URL", "").strip()
            model = os.environ.get("LLM_MODEL", "").strip()
            if not base or not model:
                raise LLMError("set LLM_BASE_URL and LLM_MODEL to use the llm engine")
            key = os.environ.get("LLM_API_KEY", "")
            transport = lambda msgs: http_chat(msgs, base_url=base, api_key=key, model=model)
        self.transport = transport
        self.classify_prompt = load_prompt("classify.md")
        self.reply_prompt = load_prompt("reply.md")

    def classify(self, lead):
        msgs = [{"role": "system", "content": self.classify_prompt},
                {"role": "user", "content": "Classify this lead.\n" + lead_block(lead, do_redact=self.do_redact)}]
        v = validate_classification(parse_json_object(self.transport(msgs)))
        return Result(category=v["category"], buyer_intent=v["buyer_intent"],
                      reasons=["llm: " + r for r in v["reasons"]],
                      injection_suspected=v["injection_suspected"], need_summary=v["need_summary"], engine="llm")

    def reply(self, lead, res):
        msgs = [{"role": "system", "content": self.reply_prompt},
                {"role": "user", "content": (f"Category: {res.category}. Priority: {res.priority}. "
                                             f"Draft the first reply.\n"
                                             + lead_block(lead, include_first_name=True, do_redact=self.do_redact))}]
        return validate_reply(parse_json_object(self.transport(msgs)))


# ---------------------------------------------------------------- pipeline

def triage_lead(lead, llm=None, log=lambda msg: None):
    """Classify, prioritize and draft for one lead. Never raises on LLM problems."""
    rules = classify_rules(lead)
    res = rules
    if llm is not None:
        try:
            res = llm.classify(lead)
            if rules.injection_suspected and not res.injection_suspected:
                res.injection_suspected = True
                res.reasons.append("rules detector found a prompt-injection pattern")
            if rules.category != res.category:
                res.reasons.append(f"rules engine would say {rules.category}")
        except Exception as e:  # any LLM failure: fall back, keep going
            log(f"  {lead['id']}: llm classify failed ({str(e)[:120]}); using rules engine")
            res = rules
            res.engine = "rules (llm fallback)"
    set_priority(lead, res)

    if res.injection_suspected:
        res.status = "needs_review"
    elif res.category in REPLY_CATEGORIES:
        res.status = "draft_pending_approval"
        res.draft_subject, res.draft_body = template_reply(lead, res)
        if llm is not None and res.engine == "llm":
            try:
                res.draft_subject, res.draft_body = llm.reply(lead, res)
            except Exception as e:
                log(f"  {lead['id']}: llm reply rejected ({str(e)[:120]}); using template")
    else:
        res.status = "no_reply_needed"
    return res


CSV_COLUMNS = ["id", "received_at", "name", "email", "company", "category", "buyer_intent", "priority",
               "reply_by", "status", "injection_suspected", "engine", "reasons", "draft_subject", "draft_reply"]


def write_csv(path, pairs):
    with open(path, "w", newline="", encoding="utf-8") as f:
        w = csv.writer(f)
        w.writerow(CSV_COLUMNS)
        for lead, r in pairs:
            w.writerow([lead["id"], lead["received_at"], lead["name"], lead["email"], lead["company"],
                        r.category, r.buyer_intent, r.priority, r.reply_by, r.status,
                        "yes" if r.injection_suspected else "no", r.engine, " | ".join(r.reasons),
                        r.draft_subject, r.draft_body])


def _cell(s):
    return " ".join(str(s).split()).replace("|", "/") or "-"


def _when(iso):
    if not iso:
        return "-"
    dt = datetime.fromisoformat(iso)
    hour = dt.strftime("%I").lstrip("0")
    return f"{dt.strftime('%a %b')} {dt.day}, {hour}:{dt.strftime('%M %p')} {dt.tzname() or ''}".strip()


def _long_date(d):
    return f"{d.strftime('%B')} {d.day}, {d.year}"


def render_digest(pairs, as_of, engine_label):
    by_p = {p: [(l, r) for l, r in pairs if r.priority == p] for p in PRIORITY_TEXT}
    flagged = [(l, r) for l, r in pairs if r.injection_suspected]
    out = [f"# BigLife360 lead digest: {_long_date(as_of)}", "",
           f"Engine: {engine_label}. Leads: {len(pairs)}. **Nothing was sent.** Every draft below waits for your approval.", "",
           "## Counts", "", "| Category | Leads |", "|---|---|"]
    for c in CATEGORIES:
        out.append(f"| {c} | {sum(r.category == c for _, r in pairs)} |")
    out += ["", "| Priority | Meaning | Leads |", "|---|---|---|"]
    for p, txt in PRIORITY_TEXT.items():
        out.append(f"| {p} | {txt} | {len(by_p[p])} |")

    for p, title in (("P1", "P1: reply within 1 business hour"), ("P2", "P2: reply today"),
                     ("P3", "P3: weekly batch")):
        out += ["", f"## {title}", ""]
        if not by_p[p]:
            out.append("None.")
        for lead, r in sorted(by_p[p], key=lambda x: (-x[1].buyer_intent, x[1].reply_by)):
            who = _cell(lead["name"]) + (f", {_cell(lead['company'])}" if lead["company"] else "")
            out += [f"### {lead['id']}: {who}",
                    f"- **{r.category}**, buyer intent {r.buyer_intent}/100, reply by {_when(r.reply_by)}",
                    f"- From: {lead['email'] or '-'}",
                    f"- Message: \"{_cell(lead['message'])}\"",
                    f"- Why: {'; '.join(r.reasons[:3]) or '-'}"]
            if r.draft_body:
                out += [f"- Draft (not sent), subject \"{r.draft_subject}\":", ""]
                out += ["  > " + line if line else "  >" for line in r.draft_body.split("\n")]
            elif r.injection_suspected:
                out.append("- No draft: prompt injection suspected. Read it yourself before replying.")
            out.append("")

    out += ["## Flagged for review: prompt injection suspected", ""]
    if flagged:
        out += ["| Lead | From | Category | Priority | Pattern |", "|---|---|---|---|---|"]
        for lead, r in flagged:
            pat = next((x for x in r.reasons if "injection" in x), "-")
            out.append(f"| {lead['id']} | {_cell(lead['name'])} | {r.category} | {r.priority} | {_cell(pat)} |")
    else:
        out.append("None.")

    out += ["", "## Archived (P4)", "", "| Lead | From | Company | Category | Top reason |", "|---|---|---|---|---|"]
    for lead, r in by_p["P4"]:
        out.append(f"| {lead['id']} | {_cell(lead['name'])} | {_cell(lead['company'])} | {r.category} | {_cell(r.reasons[0] if r.reasons else '-')} |")
    out += ["", "## Approve and send", "",
            "1. Read each draft against the original message.",
            "2. Edit it in your mail client and send it yourself. This tool has no send function.",
            "3. Skim the archived list once; move anything misfiled into the right section of `triaged.csv`.", ""]
    return "\n".join(out)


def main(argv=None):
    ap = argparse.ArgumentParser(description="Triage BigLife360 contact-form leads. Never sends anything.")
    ap.add_argument("input", help="leads file: .jsonl or .csv with name,email,company,need,message,received_at")
    ap.add_argument("--engine", choices=("auto", "rules", "llm"), default="auto",
                    help="auto = llm if LLM_BASE_URL is set, else rules (default)")
    ap.add_argument("--out", default=str(HERE / "out"), help="output folder (default: out/)")
    ap.add_argument("--as-of", help="digest date YYYY-MM-DD (default: today, Central time)")
    ap.add_argument("--no-redact", action="store_true", help="send emails and phone numbers to the LLM unmasked")
    args = ap.parse_args(argv)

    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    log_file = open(out / "run.log", "w", encoding="utf-8")

    def log(msg):
        line = f"{datetime.now(BIZ_TZ).strftime('%H:%M:%S')} {msg}"
        print(line, file=sys.stderr, flush=True)
        log_file.write(line + "\n")

    try:
        log(f"step 1/4: loading leads from {args.input}")
        try:
            leads = load_leads(args.input)
        except (FileNotFoundError, ValueError) as e:
            log(f"error: {e}")
            return 2
        log(f"  loaded {len(leads)} leads")

        llm, engine_label = None, "rules"
        if args.engine == "llm" or (args.engine == "auto" and os.environ.get("LLM_BASE_URL")):
            try:
                llm = LLMEngine(do_redact=not args.no_redact)
                engine_label = f"llm ({os.environ.get('LLM_MODEL')}) with rules fallback"
            except LLMError as e:
                log(f"  llm engine unavailable ({e}); using rules engine")
        log(f"step 2/4: classifying with the {engine_label} engine")

        pairs = []
        for i, lead in enumerate(leads, 1):
            r = triage_lead(lead, llm=llm, log=log)
            pairs.append((lead, r))
            flag = " INJECTION-FLAGGED" if r.injection_suspected else ""
            log(f"  [{i}/{len(leads)}] {lead['id']} -> {r.category:<12} intent {r.buyer_intent:>3} "
                f"{r.priority} ({r.engine}){flag}")

        log("step 3/4: writing triaged.csv")
        write_csv(out / "triaged.csv", pairs)
        as_of = date.fromisoformat(args.as_of) if args.as_of else datetime.now(BIZ_TZ).date()
        log("step 4/4: writing digest.md")
        (out / "digest.md").write_text(render_digest(pairs, as_of, engine_label), encoding="utf-8")

        counts = {p: sum(r.priority == p for _, r in pairs) for p in PRIORITY_TEXT}
        log("done: " + ", ".join(f"{p}={n}" for p, n in counts.items())
            + f". Outputs in {out}. Nothing was sent.")
        return 0
    finally:
        log_file.close()


if __name__ == "__main__":
    sys.exit(main())
