"""Print the full field tree of one subject (neural + stim, raw + pre_) per CND dataset."""
import os
import sys

import numpy as np

ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
sys.path.insert(0, os.path.join(ROOT, "tools"))
from convert_cnd_to_superhuge import _load_classic, _load_v73, mat_version  # noqa: E402

FILES = {
    "AVGCAAD2024": ("dataSub1.mat", "dataStim1.mat", "pre_dataSub1.mat", "pre_dataStim1.mat"),
    "DTU2018": ("dataSub1.mat", "dataStim1.mat", "pre_dataSub1.mat", "pre_dataStim1.mat"),
    "KUL2016": ("dataSub1.mat", "dataStim1.mat", "pre_dataSub1.mat", "pre_dataStim1.mat"),
    "KUL_AAD_UltraHD2021": ("dataSub1.mat", "dataStim.mat", "pre_dataSub1.mat", "pre_dataStim1.mat"),
    "USTC2026": ("dataSub1.mat", "dataStim1.mat", "pre_dataSub1.mat", "pre_dataStim1.mat"),
}


def describe(x, depth=0, name="", maxdepth=4, out=None):
    pad = "  " * depth
    if isinstance(x, dict):
        out.append(f"{pad}{name}: struct{{{', '.join(x.keys())}}}")
        if depth < maxdepth:
            for k, v in x.items():
                describe(v, depth + 1, k, maxdepth, out)
    elif isinstance(x, np.ndarray) and x.dtype == object:
        out.append(f"{pad}{name}: cell{x.shape}")
        if x.size and depth < maxdepth:
            describe(x.flat[0], depth + 1, "[0]", maxdepth, out)
            if x.size > 1:
                describe(x.flat[-1], depth + 1, "[-1]", maxdepth, out)
    elif isinstance(x, np.ndarray):
        s = f"{pad}{name}: {x.dtype}{x.shape}"
        if x.dtype.kind in "iuf" and x.size:
            xf = x.astype(float).ravel()
            u = np.unique(xf[: 200000])
            s += f" min={np.nanmin(xf):.4g} max={np.nanmax(xf):.4g}"
            if len(u) <= 8:
                s += f" uniq={u.tolist()}"
        elif x.dtype.kind in "US":
            s += f" = {x.ravel()[:6].tolist()}"
        elif x.dtype == np.uint16 and x.size < 200:
            s += " = '" + "".join(chr(c) for c in x.ravel()) + "'"
        out.append(s)
    else:
        r = repr(x)
        out.append(f"{pad}{name}: {type(x).__name__} = {r[:120]}")


def load(path):
    return _load_v73(path) if mat_version(path) == "73" else _load_classic(path)


if __name__ == "__main__":
    lines = []
    for ds, files in FILES.items():
        for f in files:
            p = os.path.join(ROOT, "data", "cnd", ds, "dataCND", f)
            lines.append(f"\n##### {ds}/{f}  ({mat_version(p)})")
            d = load(p)
            for k, v in d.items():
                describe(v, 0, k, 4, lines)
            print("\n".join(lines[-80:]), flush=True)
    with open(os.path.join(ROOT, "reports", "eda_full", "logs", "cnd_field_tree.txt"), "w") as fh:
        fh.write("\n".join(lines))
