#!/usr/bin/env python3
"""
AA Deal Desk | Sample lead router (Python, standard library only)

Takes a new lead (from a webhook, form or CSV), scores it, decides hot / warm / cold,
writes a log line and builds the alert text. Sending to Telegram or a CRM is shown as a
function but is not called in demo mode. Sample code with invented leads.

Run:  python3 AA-Deal-Desk_Sample-Lead-Router.py --demo
"""
import argparse, csv, json, re, sys, urllib.request
from datetime import datetime, timezone

RULES = [  # (label, test, points)
    ("budget over $1,000", lambda l: l.get("budget", 0) >= 1000, 30),
    ("timeline under 30 days", lambda l: l.get("days_to_start", 99) < 30, 25),
    ("referral", lambda l: l.get("source") == "referral", 20),
    ("business email", lambda l: not re.search(r"@(gmail|yahoo|hotmail)\.", l.get("email", "")), 10),
    ("has phone", lambda l: bool(l.get("phone")), 0),
]
PENALTY_NO_PHONE = -10
HOT, WARM = 60, 30


def score(lead: dict):
    pts, why = 0, []
    for label, test, p in RULES:
        if test(lead) and p:
            pts += p
            why.append(f"+{p} {label}")
    if not lead.get("phone"):
        pts += PENALTY_NO_PHONE
        why.append(f"{PENALTY_NO_PHONE} no phone")
    return pts, why


def route(points: int) -> str:
    return "hot" if points >= HOT else "warm" if points >= WARM else "cold"


def alert_text(lead, points, tier, why):
    return (f"{tier.upper()} lead: {lead['name']} ({points} pts)\n"
            f"Source: {lead.get('source', '?')} | Budget: ${lead.get('budget', 0):,}\n"
            f"Why: {', '.join(why)}")


def send_telegram(token: str, chat_id: str, text: str):
    """Not called in demo mode. Needs a bot token from @BotFather."""
    data = json.dumps({"chat_id": chat_id, "text": text}).encode()
    req = urllib.request.Request(f"https://api.telegram.org/bot{token}/sendMessage", data, {"Content-Type": "application/json"})
    return urllib.request.urlopen(req, timeout=10).read()


def handle(lead, log_path="lead_log.csv"):
    points, why = score(lead)
    tier = route(points)
    with open(log_path, "a", newline="") as f:
        csv.writer(f).writerow([datetime.now(timezone.utc).isoformat(timespec="seconds"), lead["name"], points, tier])
    return tier, alert_text(lead, points, tier, why)


DEMO = [
    {"name": "Sample Lead A", "email": "a@acme-sample.com", "phone": "555-0100", "budget": 3000, "days_to_start": 10, "source": "referral"},
    {"name": "Sample Lead B", "email": "b@gmail.com", "phone": "", "budget": 1500, "days_to_start": 45, "source": "web form"},
    {"name": "Sample Lead C", "email": "c@gmail.com", "phone": "", "budget": 200, "days_to_start": 90, "source": "ad"},
]

if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--demo", action="store_true")
    if not ap.parse_args().demo:
        sys.exit("Use --demo to run the sample leads.")
    for lead in DEMO:
        tier, text = handle(lead, "/dev/null")
        print(text, "\n" + "-" * 40)
