"""Full untruncated single-log tables and restrained descriptive interpretation."""
from __future__ import annotations
import json
import sys
import numpy as np
import pandas as pd
from s34_data import json_default


def note(tag, row=None, **kwargs):
    value = dict(row or {}, **kwargs)
    print(f"[{tag}] "+json.dumps(value, default=json_default, ensure_ascii=False, sort_keys=True), flush=True)


def print_table(name, frame, definitions=None, stream=None):
    stream = stream or sys.stdout
    if not isinstance(frame, pd.DataFrame):
        frame = pd.DataFrame(frame)
    personal = {"student_id", "course_id", "IDSV", "IDMH", "row_index"}
    if personal.intersection(frame.columns):
        raise ValueError(f"Personal identifiers forbidden in aggregate log table {name}")
    print(f"\n[{name}] rows={len(frame)} columns={len(frame.columns)}", file=stream)
    known = dict(ap="whole-cell AP; undefined without failures",
                 auc="whole-cell ROC-AUC; requires both classes",
                 bce="mean binary log loss", brier="mean squared probability error",
                 ece="10 equal-width probability bins",
                 mean_delta_ap="paired seed-averaged faculty-fold AP difference",
                 fold="canonical rolling-origin fold", seed="model initialization seed",
                 arm="prespecified model/control", faculty="faculty cache key")
    known.update(definitions or {})
    column_defs = {c: known.get(c, c.replace("_", " ")) for c in frame.columns}
    print("column_definitions="+json.dumps(column_defs, ensure_ascii=False), file=stream)
    if frame.empty:
        print("STATUS=UNAVAILABLE_OR_NOT_REQUESTED; inspect configuration and coverage.", file=stream)
    else:
        print(frame.to_string(index=False, max_rows=None, max_cols=None,
                              line_width=10000, float_format=lambda x: f"{x:.8f}"), file=stream)
    stream.flush()


def conclusions(contrasts, decision, metrics):
    messages = [f"Frozen development hypothesis: {decision['hypothesis']}.",
                f"Development research promotion: {decision['research_promotion']}; deployment not certified."]
    effects = {}
    if not contrasts.empty:
        effects = {(r.stage, r.contrast): r.mean_delta_ap for r in contrasts.itertuples()}
    for stage in ("development", "retrospective"):
        a, placebo = effects.get((stage, "A2-A1")), effects.get((stage, "A2-P1"))
        if a is not None:
            messages.append(f"{stage}: A2-A1 AP={a:+.6f}; this is the trained interaction contrast.")
        if placebo is not None and placebo <= .005:
            messages.append(f"{stage}: A2 does not clear the prespecified .005 placebo margin; semantic partition value is not established.")
    dev, late = effects.get(("development", "A2-A1")), effects.get(("retrospective", "A2-A1"))
    if dev is None or late is None:
        chronological = "INCONCLUSIVE_INCOMPLETE_PERIODS"
    elif dev > 0 and late > 0:
        chronological = "POSITIVE_ON_BOTH_OBSERVED_STAGES"
    elif dev*late < 0:
        chronological = "SIGN_REVERSAL"
    else:
        chronological = "MIXED_OR_NONPOSITIVE"
    messages.append("Chronological behavior: "+chronological+"; F6/F7 remain repeatedly inspected retrospective periods.")
    if decision["research_promotion"] == "INCONCLUSIVE":
        recommendation = "REFINE — pilot/software validation only; no primary scientific conclusion."
    elif decision["research_promotion"] == "PASS" and late is not None and late > 0:
        hgb = effects.get(("retrospective", "A2-HGB"))
        mechanism_consistent = all(effects.get(("retrospective", c), -np.inf) > 0
                                   for c in ("A2-A0", "A2-A0M", "A2-P1"))
        recommendation = ("CONTINUE — observed mechanism and chronological advantage; later confirmation needed."
                          if hgb is not None and hgb > 0 and mechanism_consistent else
                          "REFINE — interaction evidence needs a competitive standalone result.")
    elif dev is not None and dev > 0 and late is not None and late > 0:
        recommendation = "REFINE — localized effects did not pass the complete development guard."
    else:
        recommendation = "CLOSE — principal evidence insufficient under the frozen controls."
    messages += [recommendation,
                 "Embedding norms, gradients and zeroing sensitivities describe fitted behavior; they do not prove causal utility.",
                 "Archived leaderboard differences are metrics-only unless exact matching is explicitly reported.",
                 "Faculty bootstrap intervals condition on fitted models and observed periods; seeds are not independent semesters."]
    if "final_train_ap" in metrics:
        compare = metrics.pivot_table(index=["faculty", "fold", "seed"], columns="arm",
                                     values=["ap", "final_train_ap"], aggfunc="first")
        if ("ap", "A2") in compare and ("ap", "A1") in compare:
            target = compare[("ap", "A2")]-compare[("ap", "A1")]
            train = compare[("final_train_ap", "A2")]-compare[("final_train_ap", "A1")]
            n = int(((train > 0) & (target < 0)).sum())
            messages.append(f"Cells with higher A2 training AP but lower target AP than A1: {n}; apparent generalization failures, not causal diagnoses.")
    return messages
