"""Merge the results of the E5-E10 batch (several result folders) into results/summary.md, paired against `base`."""
import glob
import os
import sys
import time

import numpy as np
import pandas as pd

HERE = os.path.dirname(os.path.abspath(__file__))
dirs = sys.argv[1:] or sorted(d for d in glob.glob(os.path.join(HERE, "results_*")) if "smoke" not in d)
fold = pd.concat([pd.read_csv(os.path.join(d, "scores_by_fold.csv")) for d in dirs if os.path.exists(os.path.join(d, "scores_by_fold.csv"))])
per = pd.concat([pd.read_csv(os.path.join(d, "scores_by_recording.csv")) for d in dirs if os.path.exists(os.path.join(d, "scores_by_recording.csv"))])
pub = pd.concat([pd.read_csv(os.path.join(d, "public", "scores_by_fold.csv")) for d in dirs if os.path.exists(os.path.join(d, "public", "scores_by_fold.csv"))])
order = [v for v in ["base", "e5a_flags", "e5b_zero", "e5c_dropout", "e6_emarm", "e7a_af7", "e7b_relspec", "e7c_band40",
                     "e9a_nfft512", "e9b_nfft128", "e10_ea", "e11_combo"] if v in set(fold.variant)]
cv = fold[fold.split == "cv"]
pr = per[per.split == "cv"].pivot_table(index=["fold", "group", "rec"], columns="variant", values="wbmae", aggfunc="mean")
pc = per[per.split == "cv"].pivot_table(index=["fold", "group", "rec"], columns="variant", values="wbmae_cropstart", aggfunc="mean")
L = ["# E5-E10 (và E11): kết quả", "", f"Tạo lúc {time.strftime('%Y-%m-%d %H:%M')}. W-bMAE bằng giây, thấp hơn là tốt hơn. Nền: low-pass 45 Hz + E4 "
     "(1 s đầu = 0, cửa sổ đầu không tính loss, random start 0-3 phút) + 217 feature + head `dist_w`. CV 5 fold theo người × seed 0-2; "
     "test công khai seed 42-46. So cặp với `base` (chạy lại cùng phiên) trên từng bản ghi, đã lấy trung bình qua seed.", "",
     "## CV 5 fold", "", "| Biến thể | Seen | Unseen | **Macro** | Hiệu so với `base` ± SE | Tốt hơn ở | Khi cắt đầu bản ghi | MAE phút đầu | Epoch tốt nhất |",
     "|---|---|---|---|---|---|---|---|---|"]
for v in order:
    g = cv[cv.variant == v]
    t = g.pivot_table(index=["fold", "seed"], columns="group", values="wbmae"); m = t.mean(1)
    c = g.pivot_table(index=["fold", "seed"], columns="group", values="wbmae_cropstart").mean(1)
    n_pairs = int((g.groupby(["fold", "seed"]).group.nunique() == 2).sum())
    if v != "base" and "base" in pr and v in pr:
        d = (pr[v] - pr["base"]).dropna(); diff = f"{d.mean():+.2f} ± {d.std() / np.sqrt(len(d)):.2f} s"; better = f"{100 * (d < 0).mean():.0f}%"
    else:
        diff, better = "", ""
    tag = f" ({n_pairs}/15)" if n_pairs < 15 else ""
    L.append(f"| {v}{tag} | {t['seen'].mean():.2f} | {t['unseen'].mean():.2f} | **{m.mean():.2f} ± {m.std():.2f}** | {diff} | {better} | "
             f"{c.mean():.2f} | {g.mae_first60s.mean():.1f} | {g.best_epoch.mean():.0f} |")
L += ["", "MAE theo bin (CV, gộp mọi cửa sổ giữ ngoài):", "", "| Biến thể | 0-40 s | 40-90 s | 90-300 s | 300-600 s |", "|---|---|---|---|---|"]
for v in order:
    g = cv[cv.variant == v]
    L.append(f"| {v} | " + " | ".join(f"{g[c].mean():.1f}" for c in ("mae_0_40", "mae_40_90", "mae_90_300", "mae_300_600")) + " |")
L += ["", "## Test công khai (train 500 bản ghi, chấm 40 bản ghi; SE khoảng 4 s; một lần chạy lẻ dao động khoảng ±2 s)", "",
      "| Biến thể | seed 42 | seed 43 | seed 44 | seed 45 | seed 46 | Trung bình | **Seed 42** |", "|---|---|---|---|---|---|---|---|"]
for v in order:
    g = pub[pub.variant == v].sort_values("seed")
    if len(g):
        L.append(f"| {v} | " + " | ".join(f"{x:.1f}" for x in g.wbmae) + " |" + " |" * (5 - len(g)) + f" {g.wbmae.mean():.1f} | **{g.wbmae.iloc[0]:.1f}** |")
os.makedirs(os.path.join(HERE, "results"), exist_ok=True)
open(os.path.join(HERE, "results", "summary.md"), "w").write("\n".join(L) + "\n")
print("\n".join(L))
