#!/usr/bin/env python3
"""Funnel and unit-economics model for the BigLife360 AI video ads offer.

Python twin of the model inside dashboard.html. Standard library only.
Run:  python3 model.py            -> prints the Base case, writes base-case.csv
All numbers are a Projection from simulated inputs (no outreach has been sent).
"""
import csv
import math
import os
import sys

PRICES = {1: 50, 3: 140, 5: 230}      # BigLife360 ads price list, USD
TOOL_COST_PER_WEEK = 0                 # free tiers only
LAG_PAID = 1                           # weeks from first email to first paid order
LAG_REPEAT = 4                         # weeks from first order to repeat order
WEEKS = 12
TARGET_MONTHLY = 1000
WEEKS_PER_MONTH = 52 / 12

# Same operating defaults in every preset (my own assumptions, not benchmarks).
OPERATING = {"emails": 100, "min_per_email": 2, "min_per_ad": 45, "hourly": 40}

# Market rates from cited public benchmarks (see dashboard sources list).
# Tier mix and repeat split are assumptions; repeat sits inside Klaviyo's 20 to 30% "good" range.
PRESETS = {
    "conservative": {"open": 0.21, "reply": 0.0209, "sample": 0.141, "paid": 0.182,
                     "mix3": 0.25, "mix5": 0.05, "repeat": 0.20},
    "base":         {"open": 0.277, "reply": 0.0343, "sample": 0.182, "paid": 0.20,
                     "mix3": 0.35, "mix5": 0.15, "repeat": 0.25},
    "strong":       {"open": 0.40, "reply": 0.055, "sample": 0.3005, "paid": 0.36,
                     "mix3": 0.45, "mix5": 0.25, "repeat": 0.30},
}


def clamp01(x):
    return max(0.0, min(1.0, float(x)))


def compute(p):
    """p: dict with emails, open, reply, sample, paid, mix3, mix5, repeat,
    min_per_ad, hourly, min_per_email. Rates are fractions 0..1."""
    E = max(0.0, float(p["emails"]))
    op, rp, sp, pd, rr = (clamp01(p[k]) for k in ("open", "reply", "sample", "paid", "repeat"))
    s3, s5 = clamp01(p["mix3"]), clamp01(p["mix5"])
    if s3 + s5 > 1:                       # guard: shares can't exceed 100%
        tot = s3 + s5
        s3, s5 = s3 / tot, s5 / tot
    s1 = 1 - s3 - s5
    m_ad, h, m_email = max(0.0, float(p["min_per_ad"])), max(0.0, float(p["hourly"])), max(0.0, float(p["min_per_email"]))

    aov = s1 * PRICES[1] + s3 * PRICES[3] + s5 * PRICES[5]
    ads_per_order = s1 * 1 + s3 * 3 + s5 * 5
    eff_reply = min(rp, op)               # guard: can't reply more than open
    opened = E * op
    replied = E * eff_reply
    samples = replied * sp                # requested = delivered (every request is fulfilled)
    new_paid = samples * pd               # new paying clients per week
    order_cost = ads_per_order * m_ad / 60 * h
    contrib_order = aov - order_cost
    monthly_rev = new_paid * (1 + rr) * aov * WEEKS_PER_MONTH
    rev_per_email_month = eff_reply * sp * pd * (1 + rr) * aov * WEEKS_PER_MONTH
    emails_needed = math.ceil(TARGET_MONTHLY / rev_per_email_month) if rev_per_email_month > 0 else None
    acq_cost_week = (E * m_email + samples * m_ad) / 60 * h + TOOL_COST_PER_WEEK
    cac = acq_cost_week / new_paid if new_paid > 0 else None
    life_contrib = (1 + rr) * contrib_order
    orders_to_payback = (cac / contrib_order) if (cac is not None and contrib_order > 0) else None
    hours_week = (E * m_email + samples * m_ad + new_paid * (1 + rr) * ads_per_order * m_ad) / 60

    tiers = []
    for k, price in PRICES.items():
        cost = k * m_ad / 60 * h
        tiers.append({"ads": k, "price": price, "minutes": k * m_ad, "time_cost": cost,
                      "margin": price - cost, "margin_pct": (price - cost) / price,
                      "breakeven_min_per_ad": (price / (k * h / 60)) if h > 0 else None})

    weeks, cum_rev, cum_cost, payback_week = [], 0.0, 0.0, None
    for t in range(1, WEEKS + 1):
        first = new_paid if t > LAG_PAID else 0.0
        rep = new_paid * rr if t > LAG_PAID + LAG_REPEAT else 0.0
        orders = first + rep
        rev = orders * aov
        minutes = E * m_email + samples * m_ad + orders * ads_per_order * m_ad
        cost = minutes / 60 * h + TOOL_COST_PER_WEEK
        cum_rev += rev
        cum_cost += cost
        if payback_week is None and cum_rev > 0 and cum_rev >= cum_cost:
            payback_week = t
        weeks.append({"week": t, "emails": E, "new_clients": first, "repeat_orders": rep,
                      "revenue": rev, "hours": minutes / 60, "time_cost": cost,
                      "cum_revenue": cum_rev, "cum_time_cost": cum_cost})

    return {
        "mix": (s1, s3, s5), "aov": aov, "ads_per_order": ads_per_order,
        "funnel_12wk": {"sent": E * WEEKS, "opened": opened * WEEKS, "replied": replied * WEEKS,
                        "sample_requested": samples * WEEKS, "sample_delivered": samples * WEEKS,
                        "paid": new_paid * WEEKS, "repeat": new_paid * rr * WEEKS},
        "new_paid_week": new_paid, "monthly_revenue": monthly_rev, "emails_needed": emails_needed,
        "cac": cac, "contrib_order": contrib_order, "life_contrib": life_contrib,
        "net_per_client": (life_contrib - cac) if cac is not None else None,
        "orders_to_payback": orders_to_payback, "hours_week": hours_week,
        "tiers": tiers, "weeks": weeks, "payback_week": payback_week,
        "total_revenue_12wk": cum_rev, "total_time_cost_12wk": cum_cost,
    }


def inputs_for(preset):
    return {**OPERATING, **PRESETS[preset]}


def money(x):
    if x is None:
        return "n/a"
    return f"-${-x:,.2f}" if x < 0 else f"${x:,.2f}"


def main():
    here = os.path.dirname(os.path.abspath(__file__))
    base = compute(inputs_for("base"))
    out = os.path.join(here, "base-case.csv")
    print("[1/3] Computing Base preset ...", flush=True)
    with open(out, "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["week", "emails", "new_clients", "repeat_orders", "revenue_usd", "hours",
                    "time_cost_usd", "cum_revenue_usd", "cum_time_cost_usd"])
        for r in base["weeks"]:
            w.writerow([r["week"], f"{r['emails']:.0f}", f"{r['new_clients']:.4f}", f"{r['repeat_orders']:.4f}",
                        f"{r['revenue']:.2f}", f"{r['hours']:.2f}", f"{r['time_cost']:.2f}",
                        f"{r['cum_revenue']:.2f}", f"{r['cum_time_cost']:.2f}"])
    print(f"[2/3] Wrote {os.path.relpath(out)}", flush=True)

    print("[3/3] Base case (Projection, simulated inputs):")
    f = base["funnel_12wk"]
    print("  Funnel over 12 weeks: " + " > ".join(f"{k} {v:,.2f}" for k, v in f.items()))
    print(f"  Tier mix 1/3/5 ads: {'/'.join(f'{x:.0%}' for x in base['mix'])}  avg order {money(base['aov'])}  ads/order {base['ads_per_order']:.2f}")
    print(f"  New paying clients per week: {base['new_paid_week']:.4f}")
    print(f"  Monthly revenue at steady state: {money(base['monthly_revenue'])}")
    print(f"  Emails per week for ${TARGET_MONTHLY:,}/month: {base['emails_needed']:,}")
    print(f"  Cost per acquired client (time at ${OPERATING['hourly']}/h + $0 tools): {money(base['cac'])}")
    print(f"  Contribution per order: {money(base['contrib_order'])}  per client incl. repeat: {money(base['life_contrib'])}")
    print(f"  Net value per client after acquisition: {money(base['net_per_client'])}")
    print(f"  Orders needed to pay back acquisition: {base['orders_to_payback']:.1f}")
    print(f"  Hours per week: {base['hours_week']:.2f}")
    print(f"  12-week revenue {money(base['total_revenue_12wk'])} vs time cost {money(base['total_time_cost_12wk'])}; payback week: {base['payback_week'] or 'not within 12 weeks'}")
    for t in base["tiers"]:
        print(f"  Tier {t['ads']} ad(s) ${t['price']}: time cost {money(t['time_cost'])}, margin {money(t['margin'])} ({t['margin_pct']:.1%}), break-even {t['breakeven_min_per_ad']:.1f} min/ad")
    print("  Emails per week needed for $1,000/month by preset:")
    for name in PRESETS:
        r = compute(inputs_for(name))
        print(f"    {name:<12} {r['emails_needed']:>6,}  (net per client {money(r['net_per_client'])}, CAC {money(r['cac'])})")
    print("  What-if scenarios (Base market rates unless noted):")
    for label, over in SCENARIOS:
        o = dict(over)
        r = compute({**inputs_for(o.pop("preset", "base")), **o})
        print(f"    {label:<44} net/client {money(r['net_per_client']):>11}  emails for $1k/mo {r['emails_needed']:>6,}  payback wk {r['payback_week'] or '-'}")
    print("  Reply-rate uncertainty (Wilson 95% interval if I observe the Base 3.43%):")
    for n in (200, 500, 1000):
        lo, hi = wilson(0.0343, n)
        print(f"    after {n:>5} emails: {lo:.1%} to {hi:.1%}")
    return 0


def wilson(p, n, z=1.96):
    """95% Wilson score interval for an observed rate p on n trials."""
    d = 1 + z * z / n
    c = (p + z * z / (2 * n)) / d
    m = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
    return c - m, c + m


SCENARIOS = [
    ("A. Base as set", {}),
    ("B. Base, all orders are 5-packs", {"mix3": 0, "mix5": 1}),
    ("C. Base, 15 min/ad, 0.5 min/email", {"min_per_ad": 15, "min_per_email": 0.5}),
    ("D. C plus mix 20/40/40", {"min_per_ad": 15, "min_per_email": 0.5, "mix3": 0.4, "mix5": 0.4}),
    ("E. Strong rates, 15 min/ad, 0.5 min/email", {"preset": "strong", "min_per_ad": 15, "min_per_email": 0.5}),
]


if __name__ == "__main__":
    sys.exit(main())
