"""Make the Tallyfield practice data. Everything here is made up.

Tallyfield is a fictional pay-data company. Its customers upload employee pay
and offers; it sends back market benchmarks. This script writes six CSV files
with deliberate mess: nulls, one duplicated offer, one duplicated snapshot,
small cells, a new customer that shifts the mix, and one customer (C07) where
Simpson's paradox is real.

Run:  python make_data.py   (numpy and pandas; seed fixed, so output is stable)
"""
import numpy as np
import pandas as pd

rng = np.random.default_rng(2026)

FAMILIES = ["Software Engineering", "Data", "Product", "Sales"]
LEVELS = ["Junior", "Mid", "Senior", "Lead"]
LOCS = {"London": "GBP", "Dublin": "EUR", "Berlin": "EUR", "New York": "USD"}
# market base midpoint in local currency, Senior Software Engineering
LOC_BASE = {"London": 85000, "Dublin": 80000, "Berlin": 75000, "New York": 150000}
LEVEL_X = {"Junior": 0.60, "Mid": 0.80, "Senior": 1.00, "Lead": 1.25}
FAM_X = {"Software Engineering": 1.00, "Data": 0.95, "Product": 0.97, "Sales": 0.80}
SNAPS = ["2025-06-30", "2025-12-31", "2026-06-30"]


def mid(fam, lvl, loc, year):
    m = LOC_BASE[loc] * LEVEL_X[lvl] * FAM_X[fam]
    return m * (1.03 if year == 2026 else 1.0)


# ---- companies -------------------------------------------------------------
n_co = 26
stages = ["Seed", "Series A", "Series B", "Series C+"]
companies = pd.DataFrame({
    "company_id": [f"C{i:02d}" for i in range(1, n_co + 1)],
    "industry": rng.choice(["Fintech", "Health", "Retail", "SaaS", "Media"], n_co),
    "headcount_band": rng.choice(["1-50", "51-200", "201-1000"], n_co, p=[.3, .45, .25]),
    "funding_stage": rng.choice(stages, n_co, p=[.15, .3, .3, .25]),
    "hq_country": "",
    "joined_date": "2024-11-01",
})
# each company has a home location, and some a second one
home = rng.choice(list(LOCS), n_co, p=[.4, .25, .2, .15])
home[6] = "London"  # C07, the Simpson's customer
home[2] = "London"
companies["hq_country"] = [{"London": "GB", "Dublin": "IE", "Berlin": "DE", "New York": "US"}[h] for h in home]
companies.loc[companies.company_id == "C07", "funding_stage"] = "Series B"
companies.loc[companies.company_id == "C26", "joined_date"] = "2026-10-20"  # new customer
companies.loc[companies.company_id == "C25", "joined_date"] = "2026-01-15"  # joins in 2026
co_locs = {}
for i, c in enumerate(companies.company_id):
    locs = [home[i]]
    if rng.random() < 0.45:
        locs.append(rng.choice([l for l in LOCS if l != home[i]]))
    co_locs[c] = locs
co_locs["C25"] = ["Berlin"]
companies.loc[companies.company_id == "C25", "hq_country"] = "DE"
co_pay = {c: rng.normal(1.0, 0.07) for c in companies.company_id}  # some pay more
stage_eq = {"Seed": 0.22, "Series A": 0.18, "Series B": 0.14, "Series C+": 0.10}

# ---- pay bands: one per company x family x level x location x year -----------
bands = []
for c in companies.company_id:
    for loc in co_locs[c]:
        for fam in FAMILIES:
            for lvl in LEVELS:
                for yr in (2025, 2026):
                    m = mid(fam, lvl, loc, yr) * co_pay[c]
                    m = round(m / 500) * 500
                    bands.append((c, fam, lvl, loc, round(m * .85 / 500) * 500, m,
                                  round(m * 1.15 / 500) * 500, f"{yr}-01-01"))
pay_bands = pd.DataFrame(bands, columns=["company_id", "job_family", "level", "location",
                                         "band_min", "band_mid", "band_max", "effective_date"])
# C25 joined in 2026, so it has 2026 bands only
pay_bands = pay_bands[~((pay_bands.company_id == "C25") & (pay_bands.effective_date == "2025-01-01"))]

# ---- employees and snapshots ----------------------------------------------
emps, snaps = [], []
eid = 1000


def add_emp(c, fam, lvl, loc, gender, start, pay_x=1.0, promote=False, jump=False, leave=None):
    """One employee, plus a pay snapshot on each date they were employed."""
    global eid
    eid += 1
    e = f"E{eid}"
    emps.append((e, c, fam, lvl, loc, gender, start, leave))
    cur = LEVELS.index(lvl)
    first_lvl = LEVELS[max(cur - 1, 0)] if promote else lvl
    base_x = co_pay[c] * pay_x * rng.normal(0.97, 0.08)
    stage = companies.set_index("company_id").loc[c, "funding_stage"]
    for k, d in enumerate(SNAPS):
        if d < start or (leave and d > leave):
            continue
        yr = int(d[:4])
        this_lvl = first_lvl if (promote and k == 0) else lvl
        b = mid(fam, this_lvl, loc, yr) * base_x * (1 + 0.012 * k)
        if jump and k == 2:
            b *= 1.19  # big rise, same level
        eq_rate = stage_eq[stage] * (0.82 if (yr == 2026 and stage in ("Seed", "Series A")) else 1.0)
        eq = None if fam == "Sales" and rng.random() < .5 else round(b * eq_rate * rng.normal(1, .25), -2)
        bonus = None if rng.random() < .06 else {"Sales": 30.0}.get(fam, float(rng.choice([0, 5, 10, 10, 15])))
        snaps.append((e, d, this_lvl, round(b, -2), bonus, eq, LOCS[loc]))
    return e


for c in companies.company_id:
    if c in ("C07",):
        continue
    n = int(rng.integers(8, 22))
    start_floor = "2026-01-01" if c == "C25" else "2019-01-01"
    for _ in range(n):
        loc = rng.choice(co_locs[c])
        fam = rng.choice(FAMILIES, p=[.4, .2, .15, .25])
        lvl = rng.choice(LEVELS, p=[.25, .35, .28, .12])
        start = str(pd.Timestamp(start_floor) + pd.Timedelta(days=int(rng.integers(0, 2000 if c != "C25" else 60))))[:10]
        if start > "2026-06-30":
            start = "2026-03-01"
        g = rng.choice(["F", "M", None], p=[.44, .52, .04])
        leave = "2026-01-31" if rng.random() < .08 else None
        add_emp(c, fam, lvl, loc, g, start, promote=rng.random() < .1, jump=rng.random() < .01,
                leave=leave, pay_x=1.18 if c == "C25" else 1.0)

# London Senior Software Engineers: enough companies to pass the privacy rule
for c in ["C01", "C02", "C03", "C05", "C08", "C10", "C11", "C13", "C14"]:
    if "London" not in co_locs[c]:
        co_locs[c].append("London")
        for fam in FAMILIES:
            for lvl in LEVELS:
                for yr in (2025, 2026):
                    m = round(mid(fam, lvl, "London", yr) * co_pay[c] / 500) * 500
                    pay_bands = pd.concat([pay_bands, pd.DataFrame([(c, fam, lvl, "London", round(m * .85 / 500) * 500, m,
                        round(m * 1.15 / 500) * 500, f"{yr}-01-01")], columns=pay_bands.columns)], ignore_index=True)
    for _ in range(int(rng.integers(2, 5))):
        add_emp(c, "Software Engineering", "Senior", "London", rng.choice(["F", "M"]), "2022-04-01")

# A few clear "jump without promotion" cases
for c in ["C04", "C09", "C12"]:
    add_emp(c, "Data", "Mid", co_locs[c][0], "F", "2023-02-01", jump=True)

# C07: women are concentrated in senior levels; within each level men earn more.
mix = {"F": {"Junior": 3, "Mid": 6, "Senior": 12, "Lead": 9},
       "M": {"Junior": 12, "Mid": 12, "Senior": 5, "Lead": 3}}
for g, by in mix.items():
    for lvl, n in by.items():
        for _ in range(n):
            add_emp("C07", "Software Engineering", lvl, "London", g, "2021-05-01",
                    pay_x=1.05 if g == "M" else 0.99)

employees = pd.DataFrame(emps, columns=["employee_id", "company_id", "job_family", "level",
                                        "location", "gender", "start_date", "end_date"])
employees.loc[employees.sample(3, random_state=1).index, "location"] = None  # messy
comp = pd.DataFrame(snaps, columns=["employee_id", "snapshot_date", "level", "base_salary",
                                    "target_bonus_pct", "equity_annual_value", "currency"])
comp = pd.concat([comp, comp.iloc[[40]]], ignore_index=True)  # one duplicated upload row

# ---- offers ---------------------------------------------------------------
offers = []
oid = 5000
months = pd.date_range("2025-01-01", "2026-11-30", freq="D")
for _ in range(640):
    c = rng.choice(companies.company_id[:-1])  # C26 is added below
    if c == "C25":
        d = pd.Timestamp("2026-01-20") + pd.Timedelta(days=int(rng.integers(0, 300)))
    else:
        d = rng.choice(months)
    d = pd.Timestamp(d)
    loc = rng.choice(co_locs[c])
    fam = rng.choice(FAMILIES, p=[.4, .2, .15, .25])
    lvl = rng.choice(LEVELS, p=[.3, .35, .25, .1])
    ratio = rng.normal(1.0, 0.08)
    base = round(mid(fam, lvl, loc, d.year) * co_pay[c] * ratio, -2)
    p = np.clip(0.82 + 1.6 * (ratio - 1.0), 0.3, 0.97)
    status = "accepted" if rng.random() < p else "declined"
    if rng.random() < 0.03:
        status = "rescinded"
    age = (pd.Timestamp("2026-11-30") - d).days
    if age < 21 and rng.random() < 0.4:
        status = "pending"
    rec = bool(d >= pd.Timestamp("2026-09-01") and rng.random() < 0.5)
    oid += 1
    offers.append((f"O{oid}", c, fam, lvl, loc, base, round(base * .15, -2) if fam != "Sales" else None,
                   str(d.date()), status, rec))
# C26: new customer in November 2026, many offers, low acceptance (pays under its bands)
for _ in range(36):
    d = pd.Timestamp("2026-11-01") + pd.Timedelta(days=int(rng.integers(0, 20)))
    loc = co_locs["C26"][0]
    fam = rng.choice(["Sales", "Software Engineering"], p=[.6, .4])
    lvl = rng.choice(["Junior", "Mid"])
    base = round(mid(fam, lvl, loc, 2026) * co_pay["C26"] * rng.normal(0.88, .04), -2)
    status = "accepted" if rng.random() < 0.5 else "declined"
    oid += 1
    offers.append((f"O{oid}", "C26", fam, lvl, loc, base, None, str(d.date()), status, False))
offers = pd.DataFrame(offers, columns=["offer_id", "company_id", "job_family", "level", "location",
                                       "base_offered", "equity_offered", "sent_date", "status",
                                       "used_recommendation"])
offers.loc[offers.sample(4, random_state=3).index, "location"] = "Remote"  # no band for Remote
offers = pd.concat([offers, offers.iloc[[123]]], ignore_index=True)  # duplicate offer row
offers = offers.sort_values("sent_date", kind="stable").reset_index(drop=True)

# ---- daily-ish FX: one rate per week, to USD --------------------------------
weeks = pd.date_range("2025-01-03", "2026-12-04", freq="W-FRI")
gbp = 1.26 + np.cumsum(rng.normal(0, 0.006, len(weeks)))
eur = 1.07 + np.cumsum(rng.normal(0, 0.005, len(weeks)))
fx = pd.concat([pd.DataFrame({"rate_date": weeks.date, "currency": "GBP", "usd_per_unit": gbp.round(4)}),
                pd.DataFrame({"rate_date": weeks.date, "currency": "EUR", "usd_per_unit": eur.round(4)}),
                pd.DataFrame({"rate_date": weeks.date, "currency": "USD", "usd_per_unit": 1.0})])

comp["base_salary"] = comp["base_salary"].astype(int)
comp["equity_annual_value"] = comp["equity_annual_value"].astype("Int64")
offers["base_offered"] = offers["base_offered"].astype(int)
offers["equity_offered"] = offers["equity_offered"].astype("Int64")
companies.to_csv("companies.csv", index=False)
employees.to_csv("employees.csv", index=False)
comp.to_csv("comp_snapshots.csv", index=False)
offers.to_csv("offers.csv", index=False)
pay_bands.to_csv("pay_bands.csv", index=False)
fx.to_csv("fx_rates.csv", index=False)
for n, d in [("companies", companies), ("employees", employees), ("comp_snapshots", comp),
             ("offers", offers), ("pay_bands", pay_bands), ("fx_rates", fx)]:
    print(f"{n:15s} {len(d):5d} rows")
