#!/usr/bin/env python3
"""Normalize, deduplicate and qualify leads from a CSV export (stdlib only)."""
import argparse
import csv
import json
import re
from pathlib import Path

URGENT = {"urgent", "alta", "high", "yes", "si", "sí", "1", "true"}
ADULT = {"auto", "autos", "vehiculo", "vehículo", "carro", "car", "camioneta"}


def normalize_email(value):
    return (value or "").strip().lower()


def normalize_phone(value):
    digits = re.sub(r"\D", "", value or "")
    return digits[-10:] if len(digits) >= 10 else ""


def classify(row):
    service = row.get("service", "").lower()
    if "permuta" in service or "trade" in service:
        category = "trade_in"
    elif any(word in service for word in ADULT):
        category = "vehicle_purchase"
    elif "ads" in service or "google" in service:
        category = "paid_media"
    elif "seo" in service:
        category = "seo"
    elif "web" in service or "landing" in service:
        category = "web"
    else:
        category = "other"
    urgent = row.get("urgency", "").strip().lower() in URGENT
    sale = float(row.get("sale_value") or 0)
    return {
        "category": category,
        "priority": "high" if urgent or sale > 0 else "review",
        "qualified": "yes" if sale > 0 else "pending",
        "sale_value": f"{sale:.2f}",
    }


def process(rows):
    unique = {}
    duplicates = 0
    invalid = 0
    for row in rows:
        email = normalize_email(row.get("email"))
        phone = normalize_phone(row.get("phone"))
        if not email and not phone:
            invalid += 1
            continue
        key = email or phone
        if key in unique:
            duplicates += 1
            continue
        normalized = {
            "name": (row.get("name") or "").strip(),
            "email": email,
            "phone": phone,
            "city": (row.get("city") or "").strip(),
            "source": (row.get("source") or "").strip(),
            "utm_campaign": (row.get("utm_campaign") or "").strip(),
            "gclid": (row.get("gclid") or "").strip(),
        }
        normalized.update(classify(row))
        unique[key] = normalized
    return list(unique.values()), {"duplicates": duplicates, "invalid": invalid}


def write_csv(rows, path):
    fields = ["name", "email", "phone", "city", "source", "utm_campaign", "gclid", "category", "priority", "qualified", "sale_value"]
    with Path(path).open("w", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields)
        writer.writeheader()
        writer.writerows(rows)


def report(rows, stats):
    linked = sum(1 for row in rows if row["qualified"] == "yes")
    value = sum(float(row["sale_value"]) for row in rows)
    return "\n".join([
        "# Lead Ops QA report",
        "",
        f"- Unique qualified records: {len(rows)}",
        f"- Duplicates removed: {stats['duplicates']}",
        f"- Invalid contacts skipped: {stats['invalid']}",
        f"- Leads linked to a sale: {linked}",
        f"- Linked sale value: {value:.2f}",
        f"- GCLID preserved: {sum(1 for row in rows if row['gclid'])} of {len(rows)}",
        "",
        "Validation is structural only: no claim is made about email deliverability, consent or real-world identity.",
        "",
    ])


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("input")
    parser.add_argument("--output", default="normalized.csv")
    parser.add_argument("--report", default="qa-report.md")
    parser.add_argument("--json", action="store_true")
    args = parser.parse_args()
    with Path(args.input).open(newline="") as handle:
        rows, stats = process(csv.DictReader(handle))
    if args.json:
        print(json.dumps({"rows": rows, "stats": stats}, indent=2))
    else:
        write_csv(rows, args.output)
        Path(args.report).write_text(report(rows, stats))
        print(f"Wrote {len(rows)} unique leads to {args.output}; QA report to {args.report}")


if __name__ == "__main__":
    main()
