"""DecenMind economics: a toy model. Draft v0.3.

Deterministic, no randomness, standard library only.
    python model.py        prints the tables and the end state of every run

It answers one question: what happens to operators' income and to the size of the
network when (a) the only money is what payers spend on jobs, and (b) the network
also hands out an asset whose value comes from speculative buyers.

Every number below is an input you can change. Sources are listed on the page
this file is published with.
"""
import math

H = 300.0        # hours a month an operator's machine is online (10 h a day)
KW_LOAD = 0.20   # kW drawn while working: an 8 GB card (~0.145 kW) plus the rest of the machine
SHARE = 0.70     # worker's share of what a payer pays
FEE_BURN = 0.05   # burned share of what a payer pays (proposed split; no share goes to the project)
JOB_PRICE = 0.01     # $ a payer pays for one reference job (one 3D asset)
JOBS_PER_HOUR = 15   # reference jobs one 8 GB card finishes in an hour (measured on the first test rig)
PRICE = JOB_PRICE * JOBS_PER_HOUR   # $ per reference card-hour = 0.15
TAU = 2.0        # $ a month below which a prospect does not bother
ELEC = [(0.08, 0.20), (0.13, 0.40), (0.20, 0.30), (0.30, 0.10)]  # ($ per kWh, share of prospects)
WAIT = [(0.01, 0.5), (0.06, 0.5)]  # extra kW while waiting: PC on anyway / PC left on for the network
POOL = 200_000   # people who would ever consider running a node
FOUNDER = 5      # the founder's cards; they never leave
MONTHS = 36


def sig(x):
    return 1.0 / (1.0 + math.exp(-max(-40.0, min(40.0, x))))


def net(e, w, u, sub_h=0.0, price=PRICE):
    """Operator's net $ for one month at utilisation u (share of online hours with paid work)."""
    return H * (SHARE * price * u + sub_h) - e * H * (KW_LOAD * u + w * (1.0 - u))


def demand(kind, t):
    """Paid reference card-hours bought in month t (t = 0 is the first month)."""
    base = 300.0  # one card's worth: a single customer
    if kind == "flat":
        return base
    if kind == "steady":
        return base * 1.15 ** t
    if kind == "fast":
        return base * 1.30 ** min(t, 18) * 1.10 ** max(0, t - 18)
    raise ValueError(kind)


def hype(t):
    """$ of speculative money entering in month t, in the 'emissions' regime.
    Ramps for 9 months to 150,000 a month, holds for 6, then loses 12 % a month."""
    peak = 150_000.0
    if t < 9:
        return peak * (t + 1) / 9.0
    if t < 15:
        return peak
    return peak * 0.88 ** (t - 14)


def run(kind, emissions=False):
    n = {(e, w): 0.0 for e, _ in ELEC for w, _ in WAIT}
    rows, left_at_loss, peak_n = [], 0.0, 0.0
    for t in range(MONTHS):
        N = FOUNDER + sum(n.values())
        C = N * H
        D = demand(kind, t)
        u = min(1.0, D / C)
        spec = hype(t) if emissions else 0.0
        sub_h = spec / C
        total = FOUNDER * net(0.13, 0.01, u, sub_h)
        consider = 25.0 + 0.5 * N     # word of mouth: more nodes, more people hear of it
        for e, pe in ELEC:
            for w, pw in WAIT:
                k, share = (e, w), pe * pw
                pi = net(e, w, u, sub_h)
                total += n[k] * pi
                room = max(0.0, POOL * share - n[k])
                join = min(room, consider * share * sig((pi - TAU) / 1.5))
                leave = n[k] * (0.03 + 0.45 * sig(-pi))
                if pi < 0:
                    left_at_loss += leave
                n[k] += join - leave
        peak_n = max(peak_n, N)
        rows.append({"month": t + 1, "operators": N, "util": u, "paid_hours": D,
                     "paid_usd": D * PRICE, "spec_usd": spec, "avg_net": total / N,
                     "burned_usd": D * PRICE * FEE_BURN})
    return {"rows": rows, "left_at_loss": left_at_loss, "peak": peak_n}


def month_table():
    """Net $ a month for the typical electricity price, by utilisation and by kind of operator."""
    utils = [0.05, 0.10, 0.30, 0.60, 1.00]
    return utils, [(w, [net(0.13, w, u) for u in utils]) for w, _ in WAIT]


def hour_table():
    """One busy hour: what the payer pays, what the worker gets, electricity, net."""
    return [(e, PRICE, SHARE * PRICE, e * KW_LOAD, SHARE * PRICE - e * KW_LOAD) for e, _ in ELEC]


def breakeven(e, w):
    """Utilisation at which a month nets zero."""
    return e * w / (SHARE * PRICE - e * KW_LOAD + e * w)


def scale_table():
    """What a level of paid spend supports."""
    out = []
    for spend in (1_000, 10_000, 100_000, 1_000_000, 10_000_000):
        hours = spend / PRICE
        out.append((spend, hours, hours / (H * 0.10), hours / (H * 0.30),
                    spend * SHARE, spend * FEE_BURN))
    return out


def bond_table():
    """Bond that makes faking unprofitable: B > g / (p * d). g = price of one job."""
    out = []
    for p in (0.01, 0.02, 0.05, 0.10):
        row = []
        for d in (1.0, 0.8, 0.5):
            b = JOB_PRICE / (p * d)
            row.append((b, b / (SHARE * PRICE)))   # $ and hours of paid work to fill it
        out.append((p, row))
    return out


if __name__ == "__main__":
    print("price per reference card-hour: $%.2f" % PRICE)
    for e, price, worker, elec, n_ in hour_table():
        print("  electricity $%.2f/kWh: worker gets $%.3f, power $%.3f, net $%.3f per busy hour" % (e, worker, elec, n_))
    utils, rows = month_table()
    for w, vals in rows:
        print("  wait %.2f kW:" % w, "  ".join("%3.0f%%: $%6.2f" % (u * 100, v) for u, v in zip(utils, vals)))
    for w, _ in WAIT:
        print("  break-even utilisation at $0.13/kWh, wait %.2f kW: %.1f%%" % (w, 100 * breakeven(0.13, w)))
    for kind in ("flat", "steady", "fast"):
        r = run(kind)
        last = r["rows"][-1]
        print("work-only %-6s month 36: %8.0f operators, util %5.1f%%, avg net $%6.2f, paid $%9.0f, burned $%8.0f"
              % (kind, last["operators"], 100 * last["util"], last["avg_net"], last["paid_usd"], last["burned_usd"]))
    r = run("steady", emissions=True)
    last = r["rows"][-1]
    low = min(r["rows"], key=lambda x: x["util"])
    print("emissions steady: peak %.0f operators, lowest util %.3f%% (month %d), month 36: %.0f operators, avg net $%.2f, left at a loss %.0f"
          % (r["peak"], 100 * low["util"], low["month"], last["operators"], last["avg_net"], r["left_at_loss"]))
