"""Chains only (exact, cheap). Reproduces section 25's deployed row, then checks:
  a. the funded pick and its plateau edge,
  b. the tooth formula against the chain's own jumps (parity of j and n),
  c. the 3-day minimum in the assessment,
  d. the payout clock in trades (6..14) at the deployed cost: pick, P(any), cash/fee, G,
  e. the plateau width, which sets the pick.
"""
import json
import time

import numpy as np

from common import PA, G_COIN, G_SPREAD, G_COMM, cell, pick

t0 = time.time()
out = {}

# reproduce the deployed row (decision.json: rf 1.575%, pass 44.61%, any 52.88%, cash/fee 1.612)
c = cell(G_COIN, 7)
print(f"deployed row: g {G_COIN:.4%} rf {c['rf']:.3%} pass {c['p_pass']:.4%} any {c['p_any']:.4%} "
      f"cash/fee {c['cash_fee']:.4f} E[nA] {c['e_nA']:.2f} E[L_F] {c['e_life']:.2f} G ${c['G']:.1f}/yr "
      f"med first pay {c['med_first_pay']} trades")
out["deployed"] = c

# b. teeth: the formula with n = wait against the chain's jumps; the parity-corrected formula
m1 = 100 / 0.7 / 3000
pk, rows = pick(G_COIN, 7)
r = np.array([x["risk"] for x in rows]); p = np.array([x["p_any"] for x in rows])
jumps = [(r[i - 1], r[i], p[i] - p[i - 1]) for i in range(1, len(r)) if p[i] - p[i - 1] > 0.004]
print("chain jumps (risk interval, size):", [(f"{a:.3%}-{b:.3%}", f"{d:+.2%}") for a, b, d in jumps])
for j in range(3, 9):
    n_par = 7 if (j - 7) % 2 == 0 else 8
    print(f"  j={j}: formula n=7 {m1 / (j - 7 * G_COIN):.4%}   parity n={n_par} {m1 / (j - n_par * G_COIN):.4%}")
# fine check around the even-j tooth j=4
fine = [(rr_, PA.funded_chain(rr_, G_COIN * rr_, PA.payout_threshold(rr_, 1.0, 3000, 0.7), rr=1.0, clip_dn=True, wait=7)["p_any"])
        for rr_ in np.arange(0.01260, 0.01285, 0.00002)]
print("  fine scan near j=4:", " ".join(f"{a:.4%}:{b:.3%}" for a, b in fine))
out["teeth_fine_j4"] = fine

# c. 3-day minimum in the assessment: mass passing at trade <= 3
e = PA.eval_chain(0.03, G_COIN * 0.03, rr=1.0, clip_up=True, clip_dn=True)
print(f"assessment at 3%: P(pass at trade <= 3) = {e['pass_pmf'][:4].sum():.2e}, first pass trade "
      f"{int(np.flatnonzero(e['pass_pmf'] > 0)[0])}")

# a/e. plateau width sets the pick
for w in (0.0025, 0.005, 0.0075, 0.01, 0.015, 0.02):
    pk_w, _ = pick(G_COIN, 7, width=w)
    cw = cell(G_COIN, 7, rf=pk_w["risk"])
    print(f"plateau width {w:.2%}: pick {pk_w['risk']:.3%} any {cw['p_any']:.2%} cash/fee {cw['cash_fee']:.3f} G ${cw['G']:.1f}")
best = max(rows, key=lambda x: x["p_any"])
cb = cell(G_COIN, 7, rf=best["risk"])
print(f"argmax of P(any): {best['risk']:.3%} any {cb['p_any']:.2%} cash/fee {cb['cash_fee']:.3f} G ${cb['G']:.1f}; "
      f"best E[W] in line: {max(rows, key=lambda x: x['e_W'])['risk']:.3%}")
out["argmax"] = cb

# d. payout clock in trades
out["clock"] = []
for wait in (5, 6, 7, 8, 9, 10, 12, 14):
    cw = cell(G_COIN, wait)
    out["clock"].append(cw)
    print(f"clock {wait:2d} trades: pick {cw['rf']:.3%} any {cw['p_any']:.2%} E[W] {cw['e_W']:.4f} cash/fee {cw['cash_fee']:.3f} "
          f"G ${cw['G']:+.1f}/yr")
json.dump(out, open("/tmp/arena-prime-audit/candidate-1/out_s01.json", "w"), default=float, indent=1)
print(f"done {time.time() - t0:.0f}s")
