#!/usr/bin/env python3
"""Create and run deterministic Chapter 13A `custom` examples."""

from __future__ import annotations

import csv
import math
import os
import shutil
import subprocess
from pathlib import Path


BOOK = Path(__file__).resolve().parents[1]
ROOT = BOOK.parent / "nlmx"
INPUT = BOOK / "documents" / "ch13a" / "input"
RESULTS = BOOK / "documents" / "ch13a" / "results"
EXE = Path(os.environ.get("NLMX_EXE", ROOT / "target" / "release" / "nlmx.exe"))


def make_data() -> Path:
    INPUT.mkdir(parents=True, exist_ok=True)
    path = INPUT / "custom_data.csv"
    fields = [
        "ID", "TIME", "DV", "PRED", "IPRED", "CWRES", "DOSE", "ARM",
        "SEX", "AGE", "WT", "HT", "CRCL", "ETA1", "ETA2", "SITE",
        "EVID", "MDV", "DVID", "LABEL",
    ]
    times = [0.5, 1, 2, 4, 8, 12, 24, 36]
    rows: list[dict[str, object]] = []
    for sid in range(1, 31):
        dose = (50, 100, 200)[(sid - 1) % 3]
        arm = ("Low", "Mid", "High")[(sid - 1) % 3]
        sex = "F" if sid % 2 else "M"
        age = 20 + (sid * 7) % 51
        wt = 48 + (sid * 5) % 47
        ht = 150 + (sid * 3) % 36
        crcl = 58 + (sid * 11) % 85
        eta1 = 0.28 * math.sin(sid * 0.73)
        eta2 = 0.22 * math.cos(sid * 0.57)
        site = ("North", "Central", "South")[sid % 3]
        cl = 4.2 * (wt / 70) ** 0.75 * math.exp(eta1)
        vol = 42 * (wt / 70) * math.exp(eta2)
        ka = 1.15
        k = cl / vol
        common = {
            "ID": sid, "DOSE": dose, "ARM": arm, "SEX": sex, "AGE": age,
            "WT": wt, "HT": ht, "CRCL": crcl, "ETA1": f"{eta1:.7f}",
            "ETA2": f"{eta2:.7f}", "SITE": site, "DVID": 1,
        }
        rows.append({
            **common, "TIME": 0, "DV": "", "PRED": "", "IPRED": "",
            "CWRES": "", "EVID": 1, "MDV": 1, "LABEL": f"S{sid:02d}",
        })
        for j, t in enumerate(times):
            pred = dose / 42 * ka / (ka - 0.1) * (math.exp(-0.1 * t) - math.exp(-ka * t))
            ipred = dose / vol * ka / (ka - k) * (math.exp(-k * t) - math.exp(-ka * t))
            eps = 0.13 * math.sin(sid * 1.17 + j * 0.83)
            dv = max(ipred * (1 + eps), 0.0001)
            cwres = eps / 0.13
            rows.append({
                **common, "TIME": t, "DV": f"{dv:.8f}", "PRED": f"{pred:.8f}",
                "IPRED": f"{ipred:.8f}", "CWRES": f"{cwres:.7f}",
                "EVID": 0, "MDV": 0, "LABEL": f"S{sid:02d}",
            })
    with path.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields)
        writer.writeheader()
        writer.writerows(rows)

    # Same data with a title line, a headerless teaching file, and two NONMEM tables.
    titled = INPUT / "titled_data.csv"
    titled.write_text("Chapter 13A teaching export\n" + path.read_text(encoding="utf-8"), encoding="utf-8")
    with (INPUT / "headerless.csv").open("w", newline="", encoding="utf-8") as handle:
        w = csv.writer(handle)
        for sid in range(1, 13):
            w.writerow([sid, 45 + sid * 3, round(0.1 * math.sin(sid), 5)])
    with (INPUT / "multi_table.tab").open("w", encoding="utf-8") as handle:
        handle.write("TABLE NO. 1\nID ETA1 ETA2\n")
        for sid in range(1, 16):
            handle.write(f"{sid} {0.2 * math.sin(sid):.6f} {0.15 * math.cos(sid):.6f}\n")
        handle.write("TABLE NO. 2\nID ETA1 ETA2\n")
        for sid in range(16, 31):
            handle.write(f"{sid} {0.2 * math.sin(sid):.6f} {0.15 * math.cos(sid):.6f}\n")
    return path


def write_config() -> Path:
    path = INPUT / "chapter13a.custom"
    text = r'''# Chapter 13A: complete custom gallery and tables
[data]
file = "custom_data.csv"
mutate = ["BMI = WT / (HT / 100)^2", "LNDV = ifelse(DV > 0, log(DV), NA)"]

[output]
csv = true
markdown = true
html = true
tables = true
json = true
digits = 4

[plots]
width = 9
height = 6
units = "in"
dpi = 120
base_size = 11
format = "both"

[style]
theme = "classic"
palette = "okabe-ito"
legend_position = "right"
seed = 131301

[[plot]]
name = "01_point_smooth_identity"
geom = ["point", "smooth"]
x = "IPRED"
y = "DV"
filter = "EVID == 0"
color = "factor(DOSE)"
identity = true
equal_axes = true
x_scale = "log"
y_scale = "log"
title = "Observed versus individual predictions"

[[plot]]
name = "02_jitter_text"
geom = ["jitter", "text"]
x = "SEX"
y = "ETA1"
label = "LABEL"
distinct = ["ID"]
jitter = 0.25
alpha = 0.55
title = "ETA1 by sex with subject labels"

[[plot]]
name = "03_line_profiles"
geom = ["line", "point"]
x = "TIME"
y = "DV"
filter = "EVID == 0"
group = "ID"
color = "factor(DOSE)"
y_scale = "log"
title = "Individual concentration profiles"

[[plot]]
name = "04_path_profiles"
geom = "path"
x = "TIME"
y = "DV"
filter = "EVID == 0 & ID <= 6"
group = "ID"
color = "factor(ID)"
title = "Path follows source-row order"

[[plot]]
name = "05_step_prediction"
geom = "step"
x = "TIME"
y = "PRED"
filter = "EVID == 0 & ID <= 3"
group = "ID"
color = "factor(ID)"
title = "Step representation of predictions"

[[plot]]
name = "06_area_subject"
geom = "area"
x = "TIME"
y = "DV"
filter = "EVID == 0 & ID == 1"
alpha = 0.45
title = "Area under one observed profile"

[[plot]]
name = "07_boxplot_jitter"
geom = ["boxplot", "jitter"]
x = "ARM"
y = "WT"
distinct = ["ID"]
fill = "ARM"
title = "Weight by arm"

[[plot]]
name = "08_violin_boxplot"
geom = ["violin", "boxplot"]
x = "SEX"
y = "BMI"
distinct = ["ID"]
fill = "SEX"
title = "BMI distribution by sex"

[[plot]]
name = "09_bar_counts"
geom = "bar"
x = "ARM"
distinct = ["ID"]
fill = "SEX"
position = "dodge"
y_stat = "count"
title = "Subject counts by arm and sex"

[[plot]]
name = "10_col_sum"
geom = "col"
x = "factor(DOSE)"
y = "DV"
filter = "EVID == 0"
fill = "factor(DOSE)"
title = "Column geom sums supplied values"

[[plot]]
name = "11_histogram"
geom = "histogram"
x = "ETA1"
distinct = ["ID"]
fill = "SEX"
position = "identity"
alpha = 0.55
nbins = 10
title = "ETA1 histogram"

[[plot]]
name = "12_density"
geom = "density"
x = "WT"
distinct = ["ID"]
color = "SEX"
title = "Weight density"

[[plot]]
name = "13_ecdf"
geom = "ecdf"
x = "CRCL"
distinct = ["ID"]
color = "ARM"
y_stat = "percent"
title = "Empirical cumulative CRCL distribution"

[[plot]]
name = "14_qq"
geom = "qq"
x = "CWRES"
filter = "EVID == 0"
title = "Normal Q-Q plot of CWRES"

[[plot]]
name = "15_errorbar"
geom = ["line", "point", "errorbar"]
x = "factor(TIME)"
y = "DV"
filter = "EVID == 0"
color = "factor(DOSE)"
group = "DOSE"
summary_fun = "mean"
summary_error = "sd"
title = "Mean concentration with SD"

[[plot]]
name = "16_pointrange"
geom = "pointrange"
x = "factor(TIME)"
y = "DV"
filter = "EVID == 0"
color = "factor(DOSE)"
summary_fun = "median"
summary_error = "iqr"
title = "Median concentration and IQR"

[[plot]]
name = "17_tile"
geom = "tile"
x = "factor(TIME)"
y = "factor(DOSE)"
fill = "DV"
filter = "EVID == 0"
title = "Mean concentration by time and dose"

[[plot]]
name = "18_facets_reference_lines"
geom = ["point", "smooth"]
x = "TIME"
y = "CWRES"
filter = "EVID == 0"
hline = [-2, 0, 2]
facet_rows = ["SEX"]
facet_cols = ["ARM"]
facet_labels = "both"
title = "CWRES versus time by sex and arm"

[[plot]]
name = "19_aesthetics"
geom = "point"
x = "WT"
y = "ETA1"
distinct = ["ID"]
color = "CRCL"
shape = "SEX"
size = "AGE"
title = "Mapped colour, shape, and size"

[[table]]
name = "01_listing"
kind = "listing"
head = 12
select = ["ID", "TIME", "DV", "DOSE", "ARM", "SEX"]
title = "First twelve selected rows"

[[table]]
name = "02_summary"
kind = "summary"
vars = ["DV"]
by = ["DOSE", "TIME"]
filter = "EVID == 0"
stats = ["n", "geomean", "geocv", "median", "p5", "p95"]
title = "Concentration summary by dose and time"

[[table]]
name = "03_demographics"
kind = "demographics"
distinct = ["ID"]
vars = ["AGE", "WT", "BMI", "SEX", "SITE"]
by = ["ARM"]
continuous = ["AGE", "WT", "BMI"]
categorical = ["SEX", "SITE"]
stats = ["mean_sd", "median_range"]
title = "Baseline characteristics by arm"

[[table]]
name = "04_frequency"
kind = "frequency"
distinct = ["ID"]
rows = ["ARM"]
columns = ["SEX"]
percent = "column"
total = true
title = "Subjects by arm and sex"

[[table]]
name = "05_pivot"
kind = "pivot"
rows = ["TIME"]
columns = ["DOSE"]
value = "DV"
fun = "geomean"
filter = "EVID == 0"
title = "Geometric mean concentration"

[[table]]
name = "06_correlation"
kind = "correlation"
distinct = ["ID"]
vars = ["AGE", "WT", "CRCL", "ETA1", "ETA2"]
method = "spearman"
title = "Subject-level Spearman correlations"
'''
    path.write_text(text, encoding="utf-8")
    return path


def clean_dir(path: Path) -> None:
    if path.exists():
        resolved = path.resolve()
        if RESULTS.resolve() not in resolved.parents:
            raise RuntimeError(f"unsafe result path: {resolved}")
        shutil.rmtree(path)


def run(name: str, args: list[str]) -> None:
    out = RESULTS / name
    clean_dir(out)
    command = [str(EXE), "custom", *args, "-o", str(out), "--no-color"]
    done = subprocess.run(command, cwd=ROOT, text=True, capture_output=True)
    (RESULTS / f"{name}.command.txt").write_text(
        " ".join(command) + "\n\nSTDOUT\n" + done.stdout + "\nSTDERR\n" + done.stderr,
        encoding="utf-8",
    )
    if done.returncode:
        raise RuntimeError(f"{name} failed ({done.returncode}): {done.stderr or done.stdout}")


def main() -> None:
    if not EXE.is_file():
        raise SystemExit(f"nlmx executable not found: {EXE}")
    data = make_data()
    config = write_config()
    RESULTS.mkdir(parents=True, exist_ok=True)
    version = subprocess.run([str(EXE), "version"], cwd=ROOT, text=True, capture_output=True, check=True)
    (RESULTS / "nlmx_version.txt").write_text(version.stdout + version.stderr, encoding="utf-8")
    run("gallery", ["-c", str(config)])
    run("quick_plot", [str(data), "--filter", "EVID == 0", "--geom", "point,smooth", "--x", "IPRED", "--y", "DV", "--identity", "--equal-axes", "--x-scale", "log", "--y-scale", "log", "--plot-name", "dv_vs_ipred", "--plot-format", "both", "--no-tables"])
    run("titled_listing", [str(INPUT / "titled_data.csv"), "--skip", "1", "--table-kind", "listing", "--head", "8", "--no-plots"])
    run("headerless_plot", [str(INPUT / "headerless.csv"), "--no-header", "--geom", "point", "--x", "B", "--y", "C", "--plot-name", "headerless", "--plot-format", "both", "--no-tables"])
    run("multitable_listing", [str(INPUT / "multi_table.tab"), "--table-kind", "listing", "--no-plots"])
    print(f"wrote and ran Chapter 13A examples with {EXE}")


if __name__ == "__main__":
    main()
