#!/usr/bin/env python3
"""Derive a Jupyter notebook from the package scripts by executing them cell by cell.

    python make_notebook.py <package_dir> <scratch_dir> <out.ipynb> <build_date>

The package is copied to <scratch_dir>/pkg and the scripts run THERE, so the original package is never written to.
Each script is split into cells at its own top-level banner comments ("# ----"); the code text of every cell is
taken verbatim from the script, and the cells of one script share one namespace, exactly as when the script runs.
Outputs recorded per cell: captured stdout/stderr, and any figure PNG the cell wrote (attached as image output
and labelled as a file written by the cell). Nothing else is added to the outputs.

After the run, every file under data/curated, results, figures and REPORT.md in the copy is hashed and compared
with the original package. The result is written next to the notebook as <out>.check.json.
"""
import ast, base64, contextlib, hashlib, io, json, os, pathlib, shutil, sys, time, traceback

pkg, scratch, out, build_date = pathlib.Path(sys.argv[1]).resolve(), pathlib.Path(sys.argv[2]).resolve(), pathlib.Path(sys.argv[3]).resolve(), sys.argv[4]
RUN = ("01_build_curated_data.py", "02_verify_sources.py", "03_analysis.py", "04_figures.py", "05_build_report.py")
SHOWN_ONLY = {"00_parse_pires_branco_table7.py": "Not executed here: optional step whose input (a pdftotext extract of Pires and Branco 2010) is not redistributed with the package.",
              "06_check_determinism.py": "Not executed here: it re-runs the whole pipeline twice; its recorded result is results/reproducibility_check.json."}


def sha(p):
    return hashlib.sha256(pathlib.Path(p).read_bytes()).hexdigest()


def split_cells(src):
    """Split at column-0 banner comments that lie outside every top-level statement."""
    lines = src.split("\n")
    inside = set()
    for node in ast.parse(src).body:
        for ln in range(node.lineno + 1, (node.end_lineno or node.lineno) + 1):
            inside.add(ln)                       # 1-based lines strictly after a statement's first line
    cuts = [i for i, l in enumerate(lines) if (l.startswith("# ---") or l.startswith("# ===")) and (i + 1) not in inside and i > 0]
    bounds = [0] + cuts + [len(lines)]
    cells = ["\n".join(lines[a:b]).rstrip("\n") for a, b in zip(bounds, bounds[1:])]
    cells = [c for c in cells if c.strip()]
    assert "\n".join(c for c in cells).replace("\n", "") == "\n".join(lines).replace("\n", ""), "cell split lost text"
    return cells


def snapshot(root):
    return {str(p.relative_to(root)): (p.stat().st_mtime_ns, p.stat().st_size) for p in root.rglob("*") if p.is_file() and "__pycache__" not in p.parts}


if scratch.exists():
    shutil.rmtree(scratch)
work = scratch / "pkg"
shutil.copytree(pkg, work, ignore=shutil.ignore_patterns("__pycache__", ".DS_Store"))

nb_cells, exec_count, failures = [], 0, []


def md(text):
    nb_cells.append({"cell_type": "markdown", "metadata": {}, "source": text.splitlines(keepends=True)})


md(f"# Mendel 1866, 3:1 re-analysis: derived notebook\n\n"
   f"This notebook was **derived from the package scripts** `code/01` to `code/05` on {build_date}; it is not an original project file "
   f"(the project was written as scripts, not notebooks). Each code cell is a verbatim section of one script, split at the script's own "
   f"banner comments, and the cells of one script share a namespace. Outputs are the captured standard output of each cell. "
   f"Where a cell wrote a figure file, that PNG is attached to the cell and labelled as a file written by it.\n\n"
   f"The scripts were executed on a copy of the package. `{out.name}.check.json` records whether every file they wrote is "
   f"byte-identical to the corresponding file in the package.\n")

for script in sorted(p.name for p in (work / "code").glob("*.py")):
    path = work / "code" / script
    src = path.read_text(encoding="utf-8")
    if script in SHOWN_ONLY:
        md(f"## code/{script}\n\n{SHOWN_ONLY[script]}\n")
        nb_cells.append({"cell_type": "code", "execution_count": None, "metadata": {"script": f"code/{script}", "executed": False}, "outputs": [], "source": src.splitlines(keepends=True)})
        continue
    if script not in RUN:
        continue
    md(f"## code/{script}\n")
    ns = {"__name__": "__main__", "__file__": str(path), "__builtins__": __builtins__}
    cells = split_cells(src)
    line0 = 1
    for i, code in enumerate(cells):
        before = snapshot(work)
        so, se = io.StringIO(), io.StringIO()
        t0 = time.time(); err = None
        try:
            with contextlib.redirect_stdout(so), contextlib.redirect_stderr(se):
                # pad with blank lines so tracebacks and ast positions match the script's own line numbers
                exec(compile("\n" * (line0 - 1) + code, str(path), "exec"), ns)
        except Exception:                                    # recorded, never hidden
            err = traceback.format_exc(); failures.append({"script": script, "cell": i, "error": err})
        exec_count += 1
        after = snapshot(work)
        written = sorted(k for k, v in after.items() if before.get(k) != v)
        outputs = []
        if so.getvalue():
            outputs.append({"output_type": "stream", "name": "stdout", "text": so.getvalue().replace(str(work), "<package>").splitlines(keepends=True)})
        if se.getvalue():
            outputs.append({"output_type": "stream", "name": "stderr", "text": se.getvalue().replace(str(work), "<package>").splitlines(keepends=True)})
        if err:
            outputs.append({"output_type": "error", "ename": "Exception", "evalue": err.strip().splitlines()[-1], "traceback": err.replace(str(work), "<package>").splitlines()})
        for w in written:
            if w.endswith(".png"):
                outputs.append({"output_type": "display_data", "metadata": {"file_written_by_this_cell": w},
                                "data": {"image/png": base64.b64encode((work / w).read_bytes()).decode("ascii"), "text/plain": [f"<file written by this cell: {w}>"]}})
        nb_cells.append({"cell_type": "code", "execution_count": exec_count,
                         "metadata": {"script": f"code/{script}", "script_first_line": line0, "executed": True, "seconds": round(time.time() - t0, 2),
                                      "files_written": [{"path": w, "sha256": sha(work / w)} for w in written]},
                         "outputs": outputs, "source": code.splitlines(keepends=True)})
        line0 += code.count("\n") + 1
        # account for blank lines dropped between cells so the next cell keeps its true script line number
        rest = src.split("\n")
        while line0 - 1 < len(rest) and i + 1 < len(cells) and rest[line0 - 1] != cells[i + 1].split("\n")[0]:
            line0 += 1
        if err:
            break

nb = {"cells": nb_cells, "metadata": {"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"},
                                      "language_info": {"name": "python", "version": sys.version.split()[0]},
                                      "derived_from": {"package_scripts": list(RUN), "build_date": build_date, "note": "derived by build/make_notebook.py; not an original project artifact"}},
      "nbformat": 4, "nbformat_minor": 5}
for n, c in enumerate(nb_cells):
    c["id"] = f"cell-{n:03d}"
out.write_text(json.dumps(nb, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")

# ---- completion check: files written by the run versus the original package
compare, differing, missing = [], [], []
for sub in ("data/curated", "results", "figures"):
    for p in sorted((pkg / sub).rglob("*")):
        if p.is_file() and p.name != ".DS_Store":
            compare.append(str(p.relative_to(pkg)))
compare.append("REPORT.md")
touched = {f["path"] for c in nb_cells if c["cell_type"] == "code" for f in c["metadata"].get("files_written", [])}
for rel in compare:
    q = work / rel
    if not q.exists():
        missing.append(rel)
    elif sha(q) != sha(pkg / rel):
        differing.append(rel)
check = {"build_date": build_date, "python": sys.version.split()[0], "cells": len(nb_cells), "code_cells_executed": exec_count, "failures": failures,
         "files_compared": len(compare), "files_identical": len(compare) - len(differing) - len(missing), "files_differing": differing, "files_missing": missing,
         "files_rewritten_by_the_run": len(touched & set(compare)), "compared_but_not_rewritten": sorted(set(compare) - touched),
         "notebook_sha256": sha(out), "notebook_bytes": out.stat().st_size}
pathlib.Path(str(out) + ".check.json").write_text(json.dumps(check, indent=1) + "\n", encoding="utf-8")
print(json.dumps(check, indent=1))
