"""AC-transplant of soft_hp50(stem) into AccFuse↔hp30 tip — NOT stem_hp alone.

out = tip + α · (HP_τ(soft_hp50(stem)) − tip_hp_τ)

Distinct from soft-w tip↔soft_hp50 (injects soft DC) and from ac_transplant
of raw stem_hp. Soft_hp50 spectrum differs from pure stem_hp.

Also screens: tip + α·HP(soft_hp50)  [= soft-w tip↔soft_hp50_hp]
Select: prefer p=0.996/0.8 among LODO H>0.85 Acc>75; else Acc→H.
"""
from __future__ import annotations

import json
import os
import time
from pathlib import Path

import numpy as np

import ensemble_clf_transformer_v4 as V4
import eval_external as E
from common import DS_KEYS
from common_exp import EXP
from dual_hp30_sw2_bmms import LOOKAHEAD, TEST_NAMES, blend_ev, load_ext_mean4, score_lodo
from accfuse_hp30_hselect import align_hp, load_accfuse
from multitau_stem_hp_accfuse import soft_hp
from stem_hp30_accfuse import (
    TIP_ALPHA,
    apply_hp30_signed,
    emis_from,
    ev_to_signed,
    load_stem_ext,
    load_stem_honest,
)
from ac_transplant_tip_stem import build_ext_tip_and_stem, signed_to_ev

RUN_ID = "ac_transplant_softhp50_20261109"
RUN_DIR = os.path.join(EXP, "experiments", "multi_agent_opt", "runs", RUN_ID)
OUT_JSON = os.path.join(EXP, "results", "research", "ac_transplant_softhp50.json")
RESULTS_MD = os.path.join(EXP, "multi_agent_opt", "results_ac_transplant_softhp50.md")
ALPHAS = (0.05, 0.08, 0.10, 0.12, 0.15, 0.18, 0.20, 0.25, 0.30, 0.40, 0.50)
TAUS = (30, 50)
P_CANDS = [(0.994, 0.8), (0.996, 0.8), (0.998, 0.8), (0.998, 1.0)]


def log(m):
    print(f"{time.strftime('%F %T')} {m}", flush=True)
    os.makedirs(RUN_DIR, exist_ok=True)
    with open(os.path.join(RUN_DIR, "run.log"), "a") as fh:
        fh.write(m + "\n")


def make(tip_s, soft_hp_s, tip_hp, a, mode):
    """mode: acresid = tip+a*(soft_hp_hp - tip_hp); purehp = tip+a*soft_hp_hp"""
    soft_h = apply_hp30_signed(soft_hp_s, tau=tip_hp["_tau"]) if False else None
    # tip_hp already computed at tau; soft_hp_hp passed in
    out = {}
    for ds in tip_s:
        out[ds] = {}
        for k in tip_s[ds]:
            if k not in soft_hp_s[ds] or k not in tip_hp[ds]:
                continue
            n = min(len(tip_s[ds][k]), len(soft_hp_s[ds][k]), len(tip_hp[ds][k]))
            tip = tip_s[ds][k][:n]
            sh = soft_hp_s[ds][k][:n]
            th = tip_hp[ds][k][:n]
            if mode == "acresid":
                out[ds][k] = tip + a * (sh - th)
            else:
                out[ds][k] = tip + a * sh
    return out


def main():
    t0 = time.time()
    os.makedirs(RUN_DIR, exist_ok=True)
    open(os.path.join(RUN_DIR, "run.log"), "w").close()
    log("=== AC-transplant soft_hp50 into tip ===")

    af = load_accfuse()
    _, lin_hp, _ = V4._mean_and_hp_from_folds()
    lin_al = align_hp(af, lin_hp)
    tip_ev = {ds: blend_ev(af[ds], lin_al[ds], TIP_ALPHA) for ds in DS_KEYS}
    tip_s = ev_to_signed(tip_ev)
    stem_s = load_stem_honest()
    soft50 = soft_hp(stem_s, 50)

    tip_ext, tip_ext_s, stem_ext_s = build_ext_tip_and_stem()
    soft50_e = soft_hp(stem_ext_s, 50)

    rows = []
    any_pass = False
    for tau in TAUS:
        tip_hp = apply_hp30_signed(tip_s, tau=tau)
        soft_hp_hp = apply_hp30_signed(soft50, tau=tau)
        tip_hp_e = apply_hp30_signed(tip_ext_s, tau=tau)
        soft_hp_hp_e = apply_hp30_signed(soft50_e, tau=tau)
        for mode in ("acresid", "purehp"):
            for a in ALPHAS:
                name = f"{mode}_t{tau}_a{a:.2f}"
                signed = make(tip_s, soft_hp_hp, tip_hp, a, mode)
                ev = signed_to_ev(signed, af)
                grid = []
                for p, sc in P_CANDS:
                    per, mH, mA = score_lodo(ev, p_stay=p, scale=sc)
                    grid.append(dict(p=p, sc=sc, H=mH, Acc=mA))
                ok = [r for r in grid if r["H"] > 0.85 and r["Acc"] > 75]
                mild = next(r for r in grid if r["p"] == 0.996 and r["sc"] == 0.8)
                if mild["H"] > 0.85 and mild["Acc"] > 75:
                    best = mild
                elif ok:
                    best = sorted(ok, key=lambda r: (r["H"], r["Acc"]), reverse=True)[0]
                else:
                    best = sorted(grid, key=lambda r: (r["Acc"], r["H"]), reverse=True)[0]

                signed_e = make(tip_ext_s, soft_hp_hp_e, tip_hp_e, a, mode)
                ext_ev = signed_to_ev(signed_e, tip_ext)
                mu, sd = emis_from(ev)
                ext = {}
                for ds in TEST_NAMES:
                    r = E.score(ext_ev[ds], mu, sd * best["sc"], best["p"], LOOKAHEAD)
                    ext[ds] = {k: float(r[k]) for k in ("H", "Acc", "L", "SDT") if k in r}
                # also @996
                ext996 = {}
                for ds in TEST_NAMES:
                    r = E.score(ext_ev[ds], mu, sd * 0.8, 0.996, LOOKAHEAD)
                    ext996[ds] = {k: float(r[k]) for k in ("H", "Acc", "L", "SDT") if k in r}
                gate = (
                    best["H"] > 0.85 and best["Acc"] > 75
                    and ext["AASD"]["H"] >= 0.65 and ext["Carta2026"]["H"] >= 0.65
                )
                gate996 = (
                    mild["H"] > 0.85 and mild["Acc"] > 75
                    and ext996["AASD"]["H"] >= 0.65 and ext996["Carta2026"]["H"] >= 0.65
                )
                any_pass |= gate or gate996
                row = dict(
                    name=name, mode=mode, tau=tau, a=a, best=best, mild=mild,
                    external=ext, external_996=ext996, pass_op=gate, pass_996=gate996,
                )
                rows.append(row)
                log(
                    f"  {name} LODO {best['H']:.4f}/{best['Acc']:.2f}@p{best['p']}/{best['sc']} "
                    f"A {ext['AASD']['H']:.4f} C {ext['Carta2026']['H']:.4f} "
                    f"|996 A {ext996['AASD']['H']:.4f} C {ext996['Carta2026']['H']:.4f} "
                    f"pass={gate or gate996}"
                )

    # best LODO-pass by min external H @996
    lodo_ok = [r for r in rows if r["mild"]["H"] > 0.85 and r["mild"]["Acc"] > 75]
    champ = None
    if lodo_ok:
        champ = sorted(
            lodo_ok,
            key=lambda r: (
                min(r["external_996"]["AASD"]["H"], r["external_996"]["Carta2026"]["H"]),
                r["mild"]["H"],
            ),
            reverse=True,
        )[0]

    out = dict(
        method="ac_transplant_softhp50",
        pass_any=any_pass,
        champ=champ,
        rows=rows,
        elapsed_s=time.time() - t0,
    )
    with open(OUT_JSON, "w") as fh:
        json.dump(out, fh, indent=1, default=float)

    lines = [
        "# results_ac_transplant_softhp50\n\n",
        "tip + α·(HP(soft_hp50)−tip_hp) or tip + α·HP(soft_hp50).\n\n",
        f"pass_any={any_pass}\n\n",
        "| Name | LODO@op | AASD | Carta | @996 AASD | @996 Carta |\n",
        "|---|---:|---:|---:|---:|---:|\n",
    ]
    show = sorted(
        rows,
        key=lambda r: min(r["external_996"]["AASD"]["H"], r["external_996"]["Carta2026"]["H"]),
        reverse=True,
    )[:25]
    for r in show:
        b, e, e9 = r["best"], r["external"], r["external_996"]
        lines.append(
            f"| `{r['name']}` | {b['H']:.4f}/{b['Acc']:.2f} | {e['AASD']['H']:.4f} | "
            f"{e['Carta2026']['H']:.4f} | {e9['AASD']['H']:.4f} | {e9['Carta2026']['H']:.4f} |\n"
        )
    Path(RESULTS_MD).write_text("".join(lines))
    log(f"DONE pass_any={any_pass} elapsed={time.time()-t0:.0f}s")
    return 0 if any_pass else 1


if __name__ == "__main__":
    raise SystemExit(main())
