"""
make_data.py -- builds the MADE-UP practice data for
davidcarr.me/guides/sql-and-python-practice/

Every company, offer and number here is invented. The seed is fixed, so
running this again gives exactly the same files.

    python make_data.py

Writes: companies.csv, offers.csv, roles.csv, offers_2026.json

Traps planted on purpose (the tasks find them):
  * Q3 2025: five high-paying AI labs start hiring Data Scientists, so the
    average jumps while pay at the same companies barely moves (mix shift).
  * Entry errors: one base_salary of 1,500,000 and one of 15.
  * Three offers exported twice (exact duplicate rows).
  * Declined offers (status = 'declined', accepted_at empty).
  * Five offers with no level.
  * One company with no offers at all.
"""
import json
import numpy as np
import pandas as pd


rng = np.random.default_rng(20)

CITIES = ["Dublin", "Cork", "Galway", "Berlin", "Amsterdam", "Lisbon"]
FAMILIES = {  # median base for a Mid-level hire, in euro
    "Data Analyst": 56000, "Data Scientist": 72000, "Software Engineer": 76000,
    "Product Manager": 74000, "Designer": 58000,
}
LEVELS = ["Junior", "Mid", "Senior", "Lead"]
LEVEL_MULT = {"Junior": 0.76, "Mid": 1.0, "Senior": 1.3, "Lead": 1.6}
LEVEL_P = [0.25, 0.35, 0.28, 0.12]

regular = [
    ("Brackenwood Software", "Software"), ("Mossgate Retail", "Retail"),
    ("Thimble Health", "Health"), ("Larkspur Pay", "Fintech"),
    ("Copperline Logistics", "Logistics"), ("Saltmarsh Media", "Media"),
    ("Pebblebrook Insurance", "Fintech"), ("Wrenfield Games", "Software"),
    ("Kilnworth Energy", "Energy"), ("Ashgrove Analytics", "Software"),
    ("Driftwood Travel", "Travel"), ("Hollowfern Foods", "Retail"),
    ("Marrowby Bank", "Fintech"), ("Quayside Cloud", "Software"),
    ("Tallowmere Pharma", "Health"), ("Gorsehill Telecom", "Telecom"),
    ("Brindle Robotics", "Software"), ("Fernhollow Fashion", "Retail"),
    ("Oakum Freight", "Logistics"), ("Rookery Learning", "Education"),
    ("Sedgewick Security", "Software"), ("Cobbler Lane Shops", "Retail"),
    ("Heronsgate Clinics", "Health"), ("Juniper Ledger", "Fintech"),
    ("Millrace Data", "Software"), ("Northgale Airlines", "Travel"),
    ("Pipistrelle Studios", "Media"), ("Quernstone Property", "Property"),
    ("Riverlight Energy", "Energy"), ("Starling Row Insurance", "Fintech"),
    ("Tumbleweed Mobility", "Software"), ("Umberfield Grocers", "Retail"),
    ("Vellum Publishing", "Media"), ("Whinmoor Health", "Health"),
    ("Yarrowby Payroll", "Software"), ("Zephyr Lane Bikes", "Retail"),
]
labs = ["Kestrel Minds", "Orrery Labs", "Fennel Intelligence",
        "Tidewater AI Lab", "Quarry Neural"]

rows = []
for i, (name, ind) in enumerate(regular):
    rows.append(dict(name=name, industry=ind, city=CITIES[i % len(CITIES)],
                     size_band=["1-50", "51-200", "201-1000", "1000+"][rng.integers(0, 4)]))
for i, name in enumerate(labs):
    rows.append(dict(name=name, industry="AI lab", city=["Dublin", "Berlin", "Amsterdam"][i % 3],
                     size_band="201-1000"))
rows.append(dict(name="Lanternfly Ceramics", industry="Retail", city="Galway", size_band="1-50"))  # never hires
companies = pd.DataFrame(rows)
companies.insert(0, "company_id", [f"C{n:03d}" for n in range(1, len(companies) + 1)])

# Which families each regular company hires for, and how well it pays.
pay_factor, hires = {}, {}
ds_hirers = set(rng.choice(len(regular), 12, replace=False))
for i in range(len(regular)):
    cid = f"C{i+1:03d}"
    pay_factor[cid] = float(rng.uniform(0.88, 1.18))
    fams = ["Software Engineer", "Data Analyst"] + list(rng.choice(["Product Manager", "Designer"], int(rng.integers(0, 3)), replace=False))
    if i in ds_hirers:
        fams.append("Data Scientist")
    hires[cid] = fams
lab_ids = [f"C{len(regular)+k+1:03d}" for k in range(len(labs))]
for cid in lab_ids:
    pay_factor[cid] = float(rng.uniform(1.85, 2.05))

QUARTERS = [(y, q) for y in (2024, 2025) for q in (1, 2, 3, 4)]
LAM = {"Software Engineer": 0.55, "Data Analyst": 0.45, "Data Scientist": 2.5,
       "Product Manager": 0.35, "Designer": 0.35}

def one_offer(cid, fam, t, y, q, level=None, lab=False):
    level = level or rng.choice(LEVELS, p=LEVEL_P)
    base = FAMILIES[fam] * LEVEL_MULT[level] * pay_factor[cid] * 1.006 ** t * rng.lognormal(0, 0.06)
    base = int(round(base / 500) * 500)
    if lab:
        equity = int(round(base * rng.uniform(0.6, 1.2) / 1000) * 1000)
    elif rng.random() < 0.45:
        equity = int(round(base * rng.uniform(0.05, 0.3) / 1000) * 1000)
    else:
        equity = 0
    start = pd.Timestamp(y, 3 * q - 2, 1)
    offered = start + pd.Timedelta(days=int(rng.integers(0, 88)))
    p_decline = 0.05 if lab else 0.30 - 0.2 * (pay_factor[cid] - 0.88) / 0.30
    accepted = rng.random() > p_decline
    return dict(company_id=cid, job_family=fam, level=level, base_salary=base,
                equity_value=equity, offered_at=offered.date(),
                accepted_at=(offered + pd.Timedelta(days=int(rng.integers(2, 15)))).date() if accepted else None,
                status="accepted" if accepted else "declined")

offers = []
for t, (y, q) in enumerate(QUARTERS):
    for cid, fams in hires.items():
        for fam in fams:
            for _ in range(rng.poisson(LAM[fam])):
                offers.append(one_offer(cid, fam, t, y, q))
    if (y, q) >= (2025, 3):  # the AI labs arrive
        for cid in lab_ids:
            for _ in range(int(rng.integers(2, 4))):
                offers.append(one_offer(cid, "Data Scientist", t, y, q,
                                        level=rng.choice(["Mid", "Senior", "Lead"], p=[0.3, 0.5, 0.2]), lab=True))

offers = pd.DataFrame(offers).sort_values("offered_at").reset_index(drop=True)
offers.insert(0, "offer_id", [f"O{n:04d}" for n in range(1, len(offers) + 1)])

# --- plant the entry errors ---------------------------------------------
da25 = offers.index[(offers.job_family == "Data Analyst") & (offers.status == "accepted")
                    & (pd.to_datetime(offers.offered_at).dt.year == 2025)]
offers.loc[da25[7], "base_salary"] = 1500000          # extra zeros
pm24 = offers.index[(offers.job_family == "Product Manager") & (pd.to_datetime(offers.offered_at).dt.year == 2024)]
offers.loc[pm24[3], "base_salary"] = 15               # typed in thousands
no_level = rng.choice(offers.index, 5, replace=False)
offers.loc[no_level, "level"] = None
dupes = [da25[12], offers.index[40], offers.index[200]]
offers = pd.concat([offers, offers.loc[dupes]]).sort_values(["offered_at", "offer_id"]).reset_index(drop=True)

# --- roles.csv: open roles per company, job family and quarter -----------
offers["quarter"] = pd.to_datetime(offers.offered_at).dt.year.astype(str) + "-Q" + pd.to_datetime(offers.offered_at).dt.quarter.astype(str)
acc = offers.drop_duplicates("offer_id")
acc = acc[acc.status == "accepted"].groupby(["company_id", "job_family", "quarter"]).size()
roles = []
for (cid, fam, qtr), n in acc.items():
    roles.append(dict(company_id=cid, job_family=fam, quarter=qtr, open_roles=int(n + rng.integers(0, 3))))
for _ in range(25):  # roles opened that got no accepted offer at all
    cid = f"C{int(rng.integers(1, len(regular)+1)):03d}"
    fam = rng.choice(hires[cid]); y, q = QUARTERS[int(rng.integers(0, 8))]
    if (cid, fam, f"{y}-Q{q}") not in acc.index:
        roles.append(dict(company_id=cid, job_family=fam, quarter=f"{y}-Q{q}", open_roles=int(rng.integers(1, 3))))
roles = pd.DataFrame(roles).drop_duplicates(["company_id", "job_family", "quarter"]).sort_values(["quarter", "company_id", "job_family"])
offers = offers.drop(columns="quarter")

companies.to_csv("companies.csv", index=False)
offers.to_csv("offers.csv", index=False)
roles.to_csv("roles.csv", index=False)

# --- offers_2026.json: a nested export from a "new recruiting system" ---------
PERKS = ["remote", "learning budget", "pension", "health cover", "relocation"]
cmap = companies.set_index("company_id")
out = []
for n in range(60):
    cid = f"C{int(rng.integers(1, len(regular)+1)):03d}"
    fam = rng.choice(hires[cid])
    o = one_offer(cid, fam, 8, 2026, 1)
    bonus = int(round(o["base_salary"] * rng.choice([0, 0, 0.05, 0.1, 0.15]) / 500) * 500)
    perks = sorted(rng.choice(PERKS, int(rng.integers(0, 4)), replace=False).tolist())
    out.append({
        "offer_id": f"N{n+1:03d}",
        "job_family": fam,
        "level": o["level"],
        "status": o["status"],
        "offered_at": str(o["offered_at"]),
        "company": {"id": cid, "name": cmap.loc[cid, "name"], "city": cmap.loc[cid, "city"]},
        "comp": {"base": o["base_salary"], "equity": o["equity_value"], "bonus": bonus},
        "perks": perks,
    })
with open("offers_2026.json", "w") as f:
    json.dump(out, f, indent=2)

print(len(companies), "companies,", len(offers), "offer rows,", len(roles), "role rows,", len(out), "JSON offers")
