# OID_analysis/li22b/phase_synth_final.py
"""Final synthesis report — run inline after all phases complete."""
import json, os, numpy as np

BASE = os.path.join(os.path.dirname(__file__), "..", "data_li22b", "derived")

lse = json.load(open(f"{BASE}/lse/lse_results.json"))
pod = json.load(open(f"{BASE}/pod/energy.json"))

cmap_file = f"{BASE}/oid_li22b/crossmap.npz"
crossmap = np.load(cmap_file)["overlap"] if os.path.isfile(cmap_file) else None

lines = []
lines.append("=" * 70)
lines.append("Three-Framework Synthesis: SR + Li22b + OID")
lines.append("=" * 70)

lines.append(f"\n--- 1. Li22b LSE ---")
lines.append(f"  E = {lse['E']:.4f}  (Li22b: 0.15-0.25)")
lines.append(f"  Mean eps_a = {lse['mean_eps_a']:.4f} +/- {lse['std_eps_a']:.4f}")

lines.append(f"\n--- 2. Li22b POD ---")
lines.append(f"  Commands={pod['n_cmds']}, Snaps={pod['n_snaps']}, DOF={pod['dof']}")
lines.append(f"  E1+2={pod['e2']*100:.1f}%, E1-10={pod['e10']*100:.1f}%, r99={pod['r99']}")
lines.append(f"  Li22b: E2=44.9%, E10=78.9%, r99=78")

if crossmap is not None:
    lines.append(f"\n--- 3. Cross-Map ---")
    for i in range(min(6, crossmap.shape[0])):
        top = int(np.argmax(crossmap[i]))
        lines.append(f"  Li22b mode {i} -> OID mode {top} ({crossmap[i,top]:.3f})")

lines.append(f"\n--- 4. Key Conclusions ---")
if lse['E'] < 0.20:
    lines.append("  LSE E={:.3f}: Strong LINEAR component. SR's clean formulas".format(lse['E']))
    lines.append("  are plausible because obs->act shares sensor-channel structure.")
if crossmap is not None and float(np.max(crossmap)) > 0.7:
    lines.append(f"  Cross-map max overlap={float(np.max(crossmap)):.3f}:")
    lines.append("  steady & dynamic control corrections SHARE POD subspace.")
lines.append(f"  Pinball response is LOW-DIMENSIONAL (r99={pod['r99']} modes)")
lines.append(f"  confirming PPO operates in compact correction space.")

report = "\n".join(lines)
print(report)

with open(f"{BASE}/synthesis/results.txt", "w") as f:
    f.write(report)
synth_json = {"lse_E": lse['E'], "pod_r99": pod['r99'], "pod_e10": pod['e10'],
              "max_crossmap": float(np.max(crossmap)) if crossmap is not None else None}
os.makedirs(f"{BASE}/synthesis", exist_ok=True)
json.dump(synth_json, open(f"{BASE}/synthesis/synthesis.json","w"), indent=2)
print(f"\nSaved: {BASE}/synthesis/")
