"""
How much more does the debt snowball cost than the debt avalanche?
WhenDebtFree research note: https://whendebtfree.com/research/snowball-vs-avalanche-cost/

Standard-library Python 3. Running it reproduces every published figure exactly:
    python3 simulate_snowball_vs_avalanche.py
It writes portfolios.csv (one row per simulated portfolio) and the summary tables.

Payoff rules match the site's published methodology (https://whendebtfree.com/methodology/):
  * Interest is charged monthly at APR / 12 on each balance.
  * Each debt's minimum payment is that month's interest plus 1% of the balance
    before interest, never less than $25 (or the remaining balance).
  * The household pays a fixed monthly budget. Each month every debt gets its minimum;
    whatever is left goes to one target debt, then the next, until the budget is used.
    When a debt is paid off its minimum is freed up, so the total payment never falls.
  * Avalanche targets the highest APR first (ties: smaller balance first).
    Snowball targets the smallest current balance first (ties: higher APR first).
"""
import csv, math, random, statistics

SEED = 20261121
N_PORTFOLIOS = 10_000
DEBTS_MIN, DEBTS_MAX = 2, 6
BAL_MEDIAN, BAL_SIGMA, BAL_MIN, BAL_MAX = 3_500, 0.9, 500, 25_000      # log-normal balances
APR_MAIN_SHARE, APR_MAIN_MEAN, APR_MAIN_SD = 0.70, 22.0, 2.5           # most cards: around 18-26%
APR_MIN, APR_MAX = 0.0, 29.0                                           # the rest: uniform 0-29%
BUDGET_MIN_MULT, BUDGET_MAX_MULT = 1.0, 3.0                            # budget = minimums x U(1, 3)
MIN_PCT, MIN_FLOOR, MAX_MONTHS = 0.01, 25.0, 1200

def draw_balance(rng):
    while True:
        b = math.exp(rng.gauss(math.log(BAL_MEDIAN), BAL_SIGMA))
        if BAL_MIN <= b <= BAL_MAX: return round(b, 2)

def draw_apr(rng):
    if rng.random() < APR_MAIN_SHARE:
        a = rng.gauss(APR_MAIN_MEAN, APR_MAIN_SD)
    else:
        a = rng.uniform(APR_MIN, APR_MAX)
    return round(min(APR_MAX, max(APR_MIN, a)), 1)

def minimum(balance, apr):
    interest = balance * apr / 1200
    return min(balance + interest, max(MIN_FLOOR, interest + MIN_PCT * balance))

def payoff(debts, budget, strategy):
    """debts: list of (balance, apr). Returns (months, total_interest)."""
    bal = [b for b, _ in debts]; apr = [a for _, a in debts]
    months = 0; total_interest = 0.0
    while any(b > 0.005 for b in bal):
        months += 1
        if months > MAX_MONTHS: raise RuntimeError("did not amortize")
        mins = [minimum(b, a) if b > 0.005 else 0.0 for b, a in zip(bal, apr)]
        for i in range(len(bal)):
            if bal[i] > 0.005:
                it = bal[i] * apr[i] / 1200; bal[i] += it; total_interest += it
        left = budget
        for i in range(len(bal)):
            if bal[i] > 0.005:
                p = min(mins[i], bal[i], left); bal[i] -= p; left -= p
        live = [i for i in range(len(bal)) if bal[i] > 0.005]
        if strategy == "avalanche": live.sort(key=lambda i: (-apr[i], bal[i]))
        else:                       live.sort(key=lambda i: (bal[i], -apr[i]))
        for i in live:
            if left <= 0: break
            p = min(left, bal[i]); bal[i] -= p; left -= p
    return months, total_interest

def run():
    rng = random.Random(SEED); rows = []
    for pid in range(1, N_PORTFOLIOS + 1):
        k = rng.randint(DEBTS_MIN, DEBTS_MAX)
        debts = [(draw_balance(rng), draw_apr(rng)) for _ in range(k)]
        min_sum = sum(minimum(b, a) for b, a in debts)
        mult = rng.uniform(BUDGET_MIN_MULT, BUDGET_MAX_MULT)
        budget = round(min_sum * mult, 2)
        am, ai = payoff(debts, budget, "avalanche")
        sm, si = payoff(debts, budget, "snowball")
        aprs = [a for _, a in debts]
        rows.append({"portfolio": pid, "debts": k, "total_balance": round(sum(b for b, _ in debts), 2),
                     "monthly_budget": budget, "budget_to_minimums": round(mult, 3),
                     "apr_min": min(aprs), "apr_max": max(aprs), "apr_spread": round(max(aprs) - min(aprs), 1),
                     "avalanche_interest": round(ai, 2), "snowball_interest": round(si, 2),
                     "extra_cost": round(si - ai, 2), "avalanche_months": am, "snowball_months": sm,
                     "extra_months": sm - am})
    return rows

def pct(xs, q):
    xs = sorted(xs); k = (len(xs) - 1) * q; f = math.floor(k); c = math.ceil(k)
    return xs[f] if f == c else xs[f] + (xs[c] - xs[f]) * (k - f)

def summarize(rows):
    x = [r["extra_cost"] for r in rows]; m = [r["extra_months"] for r in rows]
    rel = [r["extra_cost"] / r["avalanche_interest"] if r["avalanche_interest"] > 0 else 0.0 for r in rows]
    return {"portfolios": len(rows), "median_extra_cost": round(statistics.median(x), 2),
            "p25_extra_cost": round(pct(x, .25), 2), "p75_extra_cost": round(pct(x, .75), 2),
            "p90_extra_cost": round(pct(x, .90), 2), "mean_extra_cost": round(statistics.mean(x), 2),
            "share_under_100": round(sum(v < 100 for v in x) / len(x), 4),
            "share_over_1000": round(sum(v > 1000 for v in x) / len(x), 4),
            "share_snowball_cheaper": round(sum(v < -0.005 for v in x) / len(x), 4),
            "median_extra_pct_of_interest": round(statistics.median(rel) * 100, 2),
            "median_extra_months": float(statistics.median(m)), "p90_extra_months": round(pct(m, .90), 1),
            "share_same_finish": round(sum(v == 0 for v in m) / len(m), 4)}

SPREAD_BUCKETS = [(0, 5), (5, 10), (10, 15), (15, 20), (20, 30)]
BUDGET_BUCKETS = [(1.0, 1.5, "1.0–1.5×"), (1.5, 2.0, "1.5–2.0×"), (2.0, 2.5, "2.0–2.5×"), (2.5, 3.01, "2.5–3.0×")]
def spread_bucket(s):
    for lo, hi in SPREAD_BUCKETS:
        if lo <= s < hi: return f"{lo}-{hi} pts" if hi < 30 else "20+ pts"

if __name__ == "__main__":
    rows = run()
    with open("portfolios.csv", "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0])); w.writeheader(); w.writerows(rows)
    tables = {"overall": [("all", summarize(rows))],
              "by_apr_spread": [(lab, summarize([r for r in rows if spread_bucket(r["apr_spread"]) == lab]))
                                for lab in [spread_bucket(lo) for lo, _ in SPREAD_BUCKETS]],
              "by_budget": [(lab, summarize([r for r in rows if lo <= r["budget_to_minimums"] < hi])) for lo, hi, lab in BUDGET_BUCKETS],
              "by_number_of_debts": [(str(k), summarize([r for r in rows if r["debts"] == k])) for k in range(DEBTS_MIN, DEBTS_MAX + 1)]}
    with open("summary.csv", "w", newline="") as f:
        fields = ["breakdown", "group"] + list(summarize(rows))
        w = csv.DictWriter(f, fieldnames=fields); w.writeheader()
        for name, groups in tables.items():
            for g, s in groups: w.writerow({"breakdown": name, "group": g, **s})
    print(summarize(rows))
