"""Do the new regime features separate the bins they were designed for? AUC per contrast, against the best existing feature."""
import os, sys, time
import numpy as np
import pandas as pd
from sklearn.metrics import roc_auc_score
import regime_features as G
R = G.R

X, names, win, rec, new = G.load()
print("causality check on", G.causality_check(X, names, win), "recordings: ok")
C, cn = R.core_matrix(X, names)
ctx = R.build_context(C, win)
old = np.concatenate([X, ctx], 1); old_names = names + R.context_names(cn)
y = win.y.to_numpy()
contrasts = {"A: 0-40 vs 40-90 s": (y < 40, (y >= 40) & (y < 90)),
             "B: 40-90 vs 90-300 s": ((y >= 40) & (y < 90), (y >= 90) & (y < 300)),
             "C: 90-300 vs 300-600 s": ((y >= 90) & (y < 300), y >= 300)}
def auc(v, lo, hi):
    m = lo | hi
    a = roc_auc_score(hi[m], v[m])
    return max(a, 1 - a)
# subsample old features for speed: all of them, it is only 445 x 3 AUCs
res_new = {n: {c: auc(new[:, j], *m) for c, m in contrasts.items()} for j, n in enumerate(G.NAMES)}
res_old = {n: {c: auc(old[:, j], *m) for c, m in contrasts.items()} for j, n in enumerate(old_names)}
best_old = {c: max(res_old.items(), key=lambda kv: kv[1][c]) for c in contrasts}
L = ["# Feature theo giai đoạn: AUC từng feature trên từng cặp bin", "",
     "AUC (không phân biệt chiều, 0.5 là ngẫu nhiên) để tách hai bin kề nhau, tính trên 80,975 cửa sổ, một cửa sổ đơn lẻ "
     "(các feature đã tự chứa ngữ cảnh causal). `Tốt nhất cũ` là feature tốt nhất trong 427 feature đang có cho cùng cặp bin.", "",
     "| Giai đoạn | Feature mới | " + " | ".join(contrasts) + " |", "|---|---|" + "---|" * len(contrasts)]
for n in G.NAMES:
    cells = []
    for c in contrasts:
        v = res_new[n][c]; b = best_old[c][1][c]
        cells.append(f"**{v:.3f}**" if v > b else f"{v:.3f}")
    L.append(f"| {G.REGIME[n]} | {n} | " + " | ".join(cells) + " |")
L += ["", "Tốt nhất cũ (in đậm ở trên nếu feature mới vượt):", "",
      "| Cặp bin | Feature cũ tốt nhất | AUC |", "|---|---|---|"]
for c in contrasts:
    L.append(f"| {c} | {best_old[c][0]} | {best_old[c][1][c]:.3f} |")
beat = {c: [n for n in G.NAMES if res_new[n][c] > best_old[c][1][c]] for c in contrasts}
L += ["", "Feature mới vượt feature cũ tốt nhất: " + "; ".join(f"{c}: {', '.join(v) if v else 'không có'}" for c, v in beat.items())]
os.makedirs("results", exist_ok=True)
open("results/diagnostics.md", "w").write("\n".join(L) + "\n")
print("\n".join(L))
