"""Generate the 4 example CSV files for the Kanoniv demo.

Run once:  python examples/generate_csvs.py
Creates:   examples/data/crm_contacts.csv
           examples/data/stripe_payments.csv
           examples/data/support_tickets.csv
           examples/data/ecommerce_orders.csv
"""
import csv
import os
import random
from pathlib import Path

random.seed(42)

DATA_DIR = Path(__file__).parent / "data"
DATA_DIR.mkdir(exist_ok=True)

# ── Shared identity pool ─────────────────────────────────────────────────
# 60 "real people" — some will appear across multiple sources with
# slightly different names, emails, typos, abbreviations, etc.

PEOPLE = [
    # (canonical_name, email_variants, phone_variants)
    ("Alice Smith",       ["alice.smith@gmail.com", "asmith@company.co"],            ["555-100-0001", "(555) 100-0001"]),
    ("Bob Johnson",       ["bob.johnson@yahoo.com", "bjohnson@work.io"],             ["555-100-0002", "5551000002"]),
    ("Carol Williams",    ["carol.w@outlook.com", "cwilliams@corp.net"],             ["555-100-0003", "555.100.0003"]),
    ("David Brown",       ["david.brown@gmail.com", "dbrown@enterprise.com"],        ["555-100-0004", "(555)100-0004"]),
    ("Eve Davis",         ["eve.davis@proton.me", "edavis@startup.co"],              ["555-100-0005", "555-100-0005"]),
    ("Frank Miller",      ["frank.miller@gmail.com", "fmiller@bigcorp.com"],         ["555-100-0006", "5551000006"]),
    ("Grace Wilson",      ["grace.wilson@icloud.com", "gwilson@agency.io"],          ["555-100-0007", "(555) 100-0007"]),
    ("Henry Moore",       ["henry.moore@gmail.com", "hmoore@consulting.biz"],        ["555-100-0008", "555.100.0008"]),
    ("Irene Taylor",      ["irene.t@yahoo.com", "itaylor@firm.com"],                 ["555-100-0009", "5551000009"]),
    ("Jack Anderson",     ["jack.anderson@gmail.com", "janderson@ltd.co"],           ["555-100-0010", "(555)100-0010"]),
    ("Karen Thomas",      ["karen.thomas@outlook.com", "kthomas@acme.com"],          ["555-100-0011", "555-100-0011"]),
    ("Leo Jackson",       ["leo.jackson@gmail.com", "ljackson@retail.io"],           ["555-100-0012", "555.100.0012"]),
    ("Mia White",         ["mia.white@icloud.com", "mwhite@design.co"],             ["555-100-0013", "(555) 100-0013"]),
    ("Nathan Harris",     ["nathan.harris@yahoo.com", "nharris@dev.com"],            ["555-100-0014", "5551000014"]),
    ("Olivia Martin",     ["olivia.martin@gmail.com", "omartin@media.io"],           ["555-100-0015", "(555)100-0015"]),
    ("Paul Garcia",       ["paul.garcia@proton.me", "pgarcia@auto.com"],             ["555-100-0016", "555-100-0016"]),
    ("Quinn Martinez",    ["quinn.m@outlook.com", "qmartinez@fin.co"],               ["555-100-0017", "555.100.0017"]),
    ("Rachel Robinson",   ["rachel.robinson@gmail.com", "rrobinson@law.com"],        ["555-100-0018", "(555) 100-0018"]),
    ("Sam Clark",         ["sam.clark@yahoo.com", "sclark@eng.io"],                  ["555-100-0019", "5551000019"]),
    ("Tina Rodriguez",    ["tina.rodriguez@gmail.com", "trodriguez@health.co"],      ["555-100-0020", "(555)100-0020"]),
    ("Uma Lewis",         ["uma.lewis@icloud.com", "ulewis@edu.org"],               ["555-100-0021", "555-100-0021"]),
    ("Victor Lee",        ["victor.lee@gmail.com", "vlee@tech.com"],                 ["555-100-0022", "555.100.0022"]),
    ("Wendy Walker",      ["wendy.walker@proton.me", "wwalker@bank.com"],            ["555-100-0023", "(555) 100-0023"]),
    ("Xavier Hall",       ["xavier.hall@yahoo.com", "xhall@gov.org"],                ["555-100-0024", "5551000024"]),
    ("Yara Allen",        ["yara.allen@gmail.com", "yallen@ngo.org"],                ["555-100-0025", "(555)100-0025"]),
    ("Zach Young",        ["zach.young@outlook.com", "zyoung@sport.co"],             ["555-100-0026", "555-100-0026"]),
    ("Amber King",        ["amber.king@gmail.com", "aking@pharma.io"],               ["555-100-0027", "555.100.0027"]),
    ("Brian Wright",      ["brian.wright@yahoo.com", "bwright@mfg.com"],             ["555-100-0028", "(555) 100-0028"]),
    ("Cindy Lopez",       ["cindy.lopez@icloud.com", "clopez@food.co"],              ["555-100-0029", "5551000029"]),
    ("Derek Hill",        ["derek.hill@gmail.com", "dhill@realty.com"],               ["555-100-0030", "(555)100-0030"]),
    ("Elena Scott",       ["elena.scott@proton.me", "escott@travel.io"],             ["555-100-0031", "555-100-0031"]),
    ("Felix Green",       ["felix.green@yahoo.com", "fgreen@art.co"],                ["555-100-0032", "555.100.0032"]),
    ("Gina Adams",        ["gina.adams@gmail.com", "gadams@fashion.com"],            ["555-100-0033", "(555) 100-0033"]),
    ("Hugo Baker",        ["hugo.baker@outlook.com", "hbaker@music.io"],             ["555-100-0034", "5551000034"]),
    ("Isla Gonzalez",     ["isla.gonzalez@gmail.com", "igonzalez@pub.com"],          ["555-100-0035", "(555)100-0035"]),
    ("Jason Nelson",      ["jason.nelson@icloud.com", "jnelson@security.co"],        ["555-100-0036", "555-100-0036"]),
    ("Kira Carter",       ["kira.carter@proton.me", "kcarter@logistics.io"],         ["555-100-0037", "555.100.0037"]),
    ("Liam Mitchell",     ["liam.mitchell@yahoo.com", "lmitchell@energy.com"],       ["555-100-0038", "(555) 100-0038"]),
    ("Maya Perez",        ["maya.perez@gmail.com", "mperez@beauty.co"],              ["555-100-0039", "5551000039"]),
    ("Noah Roberts",      ["noah.roberts@outlook.com", "nroberts@gaming.io"],        ["555-100-0040", "(555)100-0040"]),
    ("Opal Turner",       ["opal.turner@gmail.com", "oturner@pet.com"],              ["555-100-0041", "555-100-0041"]),
    ("Pete Phillips",     ["pete.phillips@yahoo.com", "pphillips@auto.co"],          ["555-100-0042", "555.100.0042"]),
    ("Ruby Campbell",     ["ruby.campbell@icloud.com", "rcampbell@wine.com"],        ["555-100-0043", "(555) 100-0043"]),
    ("Sean Parker",       ["sean.parker@gmail.com", "sparker@data.io"],              ["555-100-0044", "5551000044"]),
    ("Tara Evans",        ["tara.evans@proton.me", "tevans@hr.co"],                  ["555-100-0045", "(555)100-0045"]),
    ("Umar Edwards",      ["umar.edwards@yahoo.com", "uedwards@ops.com"],           ["555-100-0046", "555-100-0046"]),
    ("Vera Collins",      ["vera.collins@gmail.com", "vcollins@sales.io"],           ["555-100-0047", "555.100.0047"]),
    ("Wade Stewart",      ["wade.stewart@outlook.com", "wstewart@legal.co"],         ["555-100-0048", "(555) 100-0048"]),
    ("Xena Sanchez",      ["xena.sanchez@gmail.com", "xsanchez@mkt.com"],           ["555-100-0049", "5551000049"]),
    ("Yuri Morris",       ["yuri.morris@icloud.com", "ymorris@arch.io"],             ["555-100-0050", "(555)100-0050"]),
    ("Zoe Rogers",        ["zoe.rogers@gmail.com", "zrogers@bio.co"],               ["555-100-0051", "555-100-0051"]),
    ("Aaron Reed",        ["aaron.reed@yahoo.com", "areed@chem.com"],               ["555-100-0052", "555.100.0052"]),
    ("Bella Cook",        ["bella.cook@gmail.com", "bcook@edtech.io"],               ["555-100-0053", "(555) 100-0053"]),
    ("Caleb Morgan",      ["caleb.morgan@proton.me", "cmorgan@fintech.co"],          ["555-100-0054", "5551000054"]),
    ("Diana Bell",        ["diana.bell@outlook.com", "dbell@insure.com"],            ["555-100-0055", "(555)100-0055"]),
    ("Ethan Murphy",      ["ethan.murphy@gmail.com", "emurphy@cloud.io"],            ["555-100-0056", "555-100-0056"]),
    ("Fiona Bailey",      ["fiona.bailey@yahoo.com", "fbailey@supply.co"],           ["555-100-0057", "555.100.0057"]),
    ("Gavin Rivera",      ["gavin.rivera@gmail.com", "grivera@telecom.com"],         ["555-100-0058", "(555) 100-0058"]),
    ("Hailey Cooper",     ["hailey.cooper@icloud.com", "hcooper@media.io"],          ["555-100-0059", "5551000059"]),
    ("Ian Richardson",    ["ian.richardson@gmail.com", "irichardson@consult.co"],     ["555-100-0060", "(555)100-0060"]),
]

COMPANIES = [
    "Acme Corp", "GlobalTech", "Pinnacle Inc", "Vertex LLC", "Nimbus Co",
    "Summit Group", "Catalyst Labs", "Horizon Ventures", "Atlas Corp", "Forge Inc",
    "Beacon Systems", "Apex Solutions", "Nova Digital", "Prism Analytics", "Pulse Media",
]

TICKET_SUBJECTS = [
    "Cannot login to account", "Billing discrepancy on last invoice",
    "Feature request: dark mode", "API rate limiting issue",
    "Data export not working", "SSO integration broken",
    "Need to update payment method", "Account merge request",
    "Performance degradation observed", "Webhook delivery failures",
    "Missing data in dashboard", "Permission error on admin panel",
    "Integration with Slack failing", "Request for SLA upgrade",
    "Password reset not received", "Two-factor auth locked out",
    "Subscription cancellation request", "Custom report not generating",
    "Mobile app crash on login", "GDPR data deletion request",
]

PRODUCTS = [
    "Pro Plan Monthly", "Enterprise Annual", "Starter Monthly",
    "Pro Plan Annual", "API Add-on", "Storage Upgrade",
    "Support Premium", "Team Plan Monthly", "Custom Enterprise",
    "Developer Plan", "Agency License", "White-label Add-on",
]


def name_variant(name: str) -> str:
    """Return a realistic name variant (abbreviation, typo, reorder)."""
    parts = name.split()
    r = random.random()
    if r < 0.15:
        return f"{parts[0][0]}. {parts[1]}"          # "A. Smith"
    if r < 0.30:
        return f"{parts[0]} {parts[1][0]}."           # "Alice S."
    if r < 0.40:
        return parts[0]                                # "Alice"
    if r < 0.50:
        return f"{parts[1]}, {parts[0]}"              # "Smith, Alice"
    return name                                        # unchanged


# ── 1. CRM Contacts (100 rows) ───────────────────────────────────────────
# Columns: customer_id, full_name, email_address, phone_number, company, signup_date

crm_rows = []
# First 50 people all appear in CRM
for i, (name, emails, phones) in enumerate(PEOPLE[:50]):
    crm_rows.append({
        "customer_id": f"CRM-{10000 + i}",
        "full_name": name,
        "email_address": emails[0],          # primary email
        "phone_number": phones[0],           # canonical phone
        "company": random.choice(COMPANIES),
        "signup_date": f"2024-{random.randint(1,12):02d}-{random.randint(1,28):02d}",
    })

# 50 more CRM-only contacts (no cross-source overlap)
EXTRA_CRM = [
    "Julia Foster", "Kevin Howard", "Laura Ward", "Mike Torres", "Nancy Cox",
    "Oscar Flores", "Patricia Long", "Roger Diaz", "Sandra Hayes", "Tom Bryant",
    "Ursula Russell", "Vince Griffin", "Whitney Hayes", "Ximena Ortiz", "Yosef Banks",
    "Zara Weaver", "Adam Nichols", "Beth Hunt", "Carlos Stone", "Debra Hart",
    "Edgar Ross", "Frances Perry", "Greg Powell", "Helen Stevens", "Ivan Tucker",
    "Janet Ford", "Kyle Webb", "Lisa Ryan", "Martin Grant", "Nina Price",
    "Omar Vargas", "Penny Wood", "Rex Fisher", "Sonia Reyes", "Tyler Fox",
    "Ulysses Dean", "Vivian Arnold", "Walter Hicks", "Yara Owens", "Zeke Mills",
    "Abby Lane", "Blake Duncan", "Cathy Bishop", "Dante Hale", "Edna Moran",
    "Fred McBride", "Gail Sparks", "Hank Greer", "Iris Whitaker", "Jesse Nolan",
]
for i, name in enumerate(EXTRA_CRM):
    crm_rows.append({
        "customer_id": f"CRM-{10050 + i}",
        "full_name": name,
        "email_address": f"{name.split()[0].lower()}.{name.split()[1].lower()}@personal.com",
        "phone_number": f"555-200-{1000 + i:04d}",
        "company": random.choice(COMPANIES),
        "signup_date": f"2025-{random.randint(1,12):02d}-{random.randint(1,28):02d}",
    })

with open(DATA_DIR / "crm_contacts.csv", "w", newline="") as f:
    w = csv.DictWriter(f, fieldnames=["customer_id", "full_name", "email_address", "phone_number", "company", "signup_date"])
    w.writeheader()
    w.writerows(crm_rows)

print(f"  crm_contacts.csv          : {len(crm_rows)} rows")


# ── 2. Stripe Payments (100 rows) ────────────────────────────────────────
# Columns: stripe_id, cust_email, customer_name, card_last4, amount, currency, payment_date
# Uses email variant 1 (work email) and name variants → fuzzy matches

stripe_rows = []
# 40 of the first 50 people appear in Stripe (with work emails + name variants)
stripe_people = random.sample(range(50), 40)
for i, idx in enumerate(stripe_people):
    name, emails, phones = PEOPLE[idx]
    stripe_rows.append({
        "stripe_id": f"ch_{200000 + i}",
        "cust_email": emails[1],                     # work email (different from CRM)
        "customer_name": name_variant(name),          # fuzzy name
        "card_last4": f"{random.randint(1000, 9999)}",
        "amount": f"{random.randint(10, 5000)}.{random.randint(0, 99):02d}",
        "currency": random.choice(["usd", "usd", "usd", "eur", "gbp"]),
        "payment_date": f"2025-{random.randint(1,12):02d}-{random.randint(1,28):02d}",
    })

# 60 Stripe-only transactions
for i in range(60):
    first = random.choice(["Amy", "Ben", "Cora", "Dan", "Ella", "Finn", "Gwen", "Hal", "Ida", "Jon",
                           "Kay", "Lou", "Max", "Nell", "Otto", "Pam", "Roy", "Sue", "Ted", "Val"])
    last = random.choice(["Burke", "Chase", "Drake", "Ellis", "Frost", "Gibbs", "Hayes", "Irwin",
                          "Joyce", "Keith", "Lowe", "Marsh", "Noel", "Odell", "Paine", "Quick"])
    stripe_rows.append({
        "stripe_id": f"ch_{200040 + i}",
        "cust_email": f"{first.lower()}.{last.lower()}@{random.choice(['gmail.com', 'yahoo.com', 'outlook.com'])}",
        "customer_name": f"{first} {last}",
        "card_last4": f"{random.randint(1000, 9999)}",
        "amount": f"{random.randint(5, 2000)}.{random.randint(0, 99):02d}",
        "currency": "usd",
        "payment_date": f"2025-{random.randint(1,12):02d}-{random.randint(1,28):02d}",
    })

with open(DATA_DIR / "stripe_payments.csv", "w", newline="") as f:
    w = csv.DictWriter(f, fieldnames=["stripe_id", "cust_email", "customer_name", "card_last4", "amount", "currency", "payment_date"])
    w.writeheader()
    w.writerows(stripe_rows)

print(f"  stripe_payments.csv       : {len(stripe_rows)} rows")


# ── 3. Support Tickets (100 rows) ────────────────────────────────────────
# Columns: ticket_id, reporter_email, reporter_name, reporter_phone, subject, priority, created_at
# Uses primary email but phone variant → phone-based matching

ticket_rows = []
# 35 of the first 50 people filed tickets (primary email, phone variant)
ticket_people = random.sample(range(50), 35)
for i, idx in enumerate(ticket_people):
    name, emails, phones = PEOPLE[idx]
    ticket_rows.append({
        "ticket_id": f"TKT-{30000 + i}",
        "reporter_email": emails[0],                  # same as CRM
        "reporter_name": name_variant(name),           # fuzzy name
        "reporter_phone": phones[1],                   # phone variant (different format)
        "subject": random.choice(TICKET_SUBJECTS),
        "priority": random.choice(["low", "medium", "medium", "high", "critical"]),
        "created_at": f"2025-{random.randint(1,12):02d}-{random.randint(1,28):02d}T{random.randint(8,18):02d}:{random.randint(0,59):02d}:00Z",
    })

# 65 ticket-only reporters
for i in range(65):
    first = random.choice(["Ava", "Blake", "Cody", "Dina", "Eli", "Faith", "Grant", "Hope",
                           "Iris", "Joel", "Kate", "Levi", "Mona", "Nick", "Opal", "Phil"])
    last = random.choice(["Barton", "Crane", "Doyle", "Eaton", "Floyd", "Grant", "Howell",
                          "Ingram", "Johns", "Klein", "Lance", "Mercer", "Noble", "Osborn", "Pratt"])
    ticket_rows.append({
        "ticket_id": f"TKT-{30035 + i}",
        "reporter_email": f"{first.lower()}{last.lower()[:3]}@{random.choice(['gmail.com', 'company.co', 'work.io'])}",
        "reporter_name": f"{first} {last}",
        "reporter_phone": f"555-300-{2000 + i:04d}",
        "subject": random.choice(TICKET_SUBJECTS),
        "priority": random.choice(["low", "medium", "high"]),
        "created_at": f"2025-{random.randint(1,12):02d}-{random.randint(1,28):02d}T{random.randint(8,18):02d}:{random.randint(0,59):02d}:00Z",
    })

with open(DATA_DIR / "support_tickets.csv", "w", newline="") as f:
    w = csv.DictWriter(f, fieldnames=["ticket_id", "reporter_email", "reporter_name", "reporter_phone", "subject", "priority", "created_at"])
    w.writeheader()
    w.writerows(ticket_rows)

print(f"  support_tickets.csv       : {len(ticket_rows)} rows")


# ── 4. Ecommerce Orders (100 rows) ───────────────────────────────────────
# Columns: order_id, buyer_email, buyer_first_name, buyer_last_name, buyer_phone, product, total, order_date
# Splits name into first/last, uses yet another email variant, includes phone

order_rows = []
# 45 of the first 50 people placed orders (split names, mixed emails)
order_people = random.sample(range(50), 45)
for i, idx in enumerate(order_people):
    name, emails, phones = PEOPLE[idx]
    parts = name.split()
    # Some use personal email, some use work email
    email = emails[random.randint(0, 1)]
    order_rows.append({
        "order_id": f"ORD-{40000 + i}",
        "buyer_email": email,
        "buyer_first_name": parts[0],
        "buyer_last_name": parts[1],
        "buyer_phone": phones[0],                     # canonical phone (same as CRM)
        "product": random.choice(PRODUCTS),
        "total": f"{random.randint(15, 3000)}.{random.randint(0, 99):02d}",
        "order_date": f"2025-{random.randint(1,12):02d}-{random.randint(1,28):02d}",
    })

# 55 ecommerce-only buyers
for i in range(55):
    first = random.choice(["Aria", "Beau", "Cara", "Drew", "Esme", "Flint", "Gail", "Heath",
                           "Ivy", "Jude", "Kaia", "Lane", "Milo", "Nora", "Owen", "Piper"])
    last = random.choice(["Banks", "Clay", "Dunn", "Emery", "Frost", "Glass", "Hart",
                          "Ivory", "Jade", "Knox", "Lloyd", "Moss", "Nash", "Pace", "Quinn"])
    order_rows.append({
        "order_id": f"ORD-{40045 + i}",
        "buyer_email": f"{first.lower()}.{last.lower()}@{random.choice(['gmail.com', 'yahoo.com', 'hotmail.com'])}",
        "buyer_first_name": first,
        "buyer_last_name": last,
        "buyer_phone": f"555-400-{3000 + i:04d}",
        "product": random.choice(PRODUCTS),
        "total": f"{random.randint(10, 1500)}.{random.randint(0, 99):02d}",
        "order_date": f"2025-{random.randint(1,12):02d}-{random.randint(1,28):02d}",
    })

with open(DATA_DIR / "ecommerce_orders.csv", "w", newline="") as f:
    w = csv.DictWriter(f, fieldnames=["order_id", "buyer_email", "buyer_first_name", "buyer_last_name", "buyer_phone", "product", "total", "order_date"])
    w.writeheader()
    w.writerows(order_rows)

print(f"  ecommerce_orders.csv      : {len(order_rows)} rows")
print(f"\nAll files written to {DATA_DIR}/")
