"""The human-readable outputs of an analysis folder (analysis spec 3.9): report.md, report.html (hand-written
emitter, no Markdown library) and reproduce.ipynb (nbformat, not executed here)."""
from __future__ import annotations

import html
from dataclasses import dataclass, field
from pathlib import Path

import nbformat
import pandas as pd

from .figures import EXPLORATORY


@dataclass
class Section:
    heading: str
    paragraphs: list = field(default_factory=list)
    tables: list = field(default_factory=list)       # (title, DataFrame)
    figures: list = field(default_factory=list)      # (name, "figures/<file>")


@dataclass
class Report:
    analysis_id: str
    sections: list


@dataclass
class ReportContext:
    params_dict: dict
    problems: pd.DataFrame
    stacks_dropped: pd.DataFrame
    qc: pd.DataFrame
    subjects: pd.DataFrame
    split: object
    figures: dict
    figure_errors: dict
    n_inputs: int
    n_stacks_kept: int
    n_somas_total: int
    n_somas_kept: int


def _cell(v) -> str:
    if v is None or (isinstance(v, float) and v != v):
        return ""
    if isinstance(v, float):
        return f"{v:.4g}"
    return str(v)


def md_table(df: pd.DataFrame, max_rows: int = 60) -> str:
    if len(df) == 0:
        return "_(empty)_"
    cols = [str(c) for c in df.columns]
    lines = ["| " + " | ".join(cols) + " |", "|" + "---|" * len(cols)]
    for _, r in df.head(max_rows).iterrows():
        lines.append("| " + " | ".join(_cell(r[c]) for c in df.columns) + " |")
    if len(df) > max_rows:
        lines.append(f"_… {len(df) - max_rows} more rows_")
    return "\n".join(lines)


def build_report(ctx: ReportContext) -> Report:
    p = ctx.params_dict
    inputs = Section("Inputs", [f"{ctx.n_inputs} input runs (dataset `{p.get('dataset', '')}`), created {p.get('created', '')}, "
                                f"code {p.get('code_version', '')}. {len(ctx.problems)} could not be read."])
    if len(ctx.problems):
        inputs.tables.append(("Input problems", ctx.problems))
    sf = p.get("soma_filter", {})
    filters = Section("Filters", [f"Stacks: quality in {p.get('stack_filter', {}).get('quality')} → {ctx.n_stacks_kept} stacks kept, "
                                  f"{len(ctx.stacks_dropped)} excluded.",
                                  f"Somas: volume {sf.get('volume_min_um3')}–{sf.get('volume_max_um3')} µm³, border fraction ≤ {sf.get('border_fraction_max')}, "
                                  f"exclude touching the XY border: {sf.get('exclude_touches_border')}, NeuN mean ≥ {sf.get('neun_mean_min')} "
                                  f"→ {ctx.n_somas_kept} of {ctx.n_somas_total} somas kept."])
    if len(ctx.stacks_dropped):
        filters.tables.append(("Excluded stacks", ctx.stacks_dropped))
    filters.tables.append(("Somas per stack", ctx.qc))
    subjects = Section("Subjects", ["One row per subject × layer × hemisphere; statistics pool every kept soma of that cell (not stack means)."],
                       [("subjects.csv", ctx.subjects)])
    sp = p.get("split", {})
    split = Section("Exploratory split", [f"**{EXPLORATORY}.** Groups (control vs stim) are unknown; this asks whether subjects fall into "
                                          f"k = {sp.get('k')} profiles from the metrics alone"
                                          + (" — k-means cluster sizes constrained to differ by at most 1, since the study's groups are "
                                             "(near-)equal in size; ward is the unconstrained comparison." if sp.get("balanced") else ".")])
    s = ctx.split
    if s is None or s.skipped_reason:
        split.paragraphs.append(f"split skipped: {s.skipped_reason if s else 'no split'}")
    else:
        split.paragraphs.append("`stability` is the bootstrap co-assignment with the subject's k-means cluster mates; it is empty for a "
                                "subject alone in its cluster and when no bootstrap ran.")
        split.tables += [("Silhouette per method", s.summary), ("Assignments (EXPLORATORY)", s.assignments)]
    figs = Section("Figures")
    for name in sorted(ctx.figures):
        png = next((f for f in ctx.figures[name] if f.endswith(".png")), ctx.figures[name][0])
        figs.figures.append((name, f"figures/{png}"))
    if ctx.figure_errors:
        figs.paragraphs.append("Figures that failed: " + "; ".join(f"{k}: {v}" for k, v in sorted(ctx.figure_errors.items())))
    return Report(str(p.get("analysis_id", "")), [inputs, filters, subjects, split, figs])


def write_markdown(report: Report, path) -> None:
    out = [f"# Analysis {report.analysis_id}", ""]
    for s in report.sections:
        out += [f"## {s.heading}", ""]
        for para in s.paragraphs:
            out += [para, ""]
        for title, df in s.tables:
            out += [f"### {title}", "", md_table(df), ""]
        for name, rel in s.figures:
            out += [f"![{name}]({rel})", ""]
    Path(path).write_text("\n".join(out))


def _html_table(df: pd.DataFrame, max_rows: int = 60) -> str:
    if len(df) == 0:
        return "<p><em>(empty)</em></p>"
    head = "".join(f"<th>{html.escape(str(c))}</th>" for c in df.columns)
    rows = "".join("<tr>" + "".join(f"<td>{html.escape(_cell(r[c]))}</td>" for c in df.columns) + "</tr>" for _, r in df.head(max_rows).iterrows())
    more = f"<p><em>… {len(df) - max_rows} more rows</em></p>" if len(df) > max_rows else ""
    return f"<table><thead><tr>{head}</tr></thead><tbody>{rows}</tbody></table>{more}"


def _inline(text: str) -> str:
    """Escape, then honour the two Markdown bits the paragraphs use: **bold** and `code`."""
    t = html.escape(text)
    while "**" in t:
        t = t.replace("**", "<strong>", 1).replace("**", "</strong>", 1)
    while "`" in t:
        t = t.replace("`", "<code>", 1).replace("`", "</code>", 1)
    return t


def write_html(report: Report, path) -> None:
    aid = report.analysis_id
    body = [f"<h1>Analysis {html.escape(aid)}</h1>"]
    for s in report.sections:
        body.append(f"<h2>{html.escape(s.heading)}</h2>")
        for para in s.paragraphs:
            body.append(f"<p>{_inline(para)}</p>")
        for title, df in s.tables:
            body.append(f"<h3>{html.escape(title)}</h3>{_html_table(df)}")
        for name, rel in s.figures:
            body.append(f'<figure><img src="{html.escape(rel)}" alt="{html.escape(name)}"><figcaption>{html.escape(name)}</figcaption></figure>')
    doc = ("<!DOCTYPE html>\n<html><head><meta charset=\"utf-8\"><title>Analysis " + html.escape(aid) + "</title>"
           "<style>body{font:14px system-ui,sans-serif;max-width:1100px;margin:2em auto;padding:0 1em}table{border-collapse:collapse;font-size:12px}"
           "td,th{border:1px solid #ccc;padding:2px 6px}img{max-width:100%}figure{margin:1em 0}</style></head><body>"
           + "\n".join(body) + "</body></html>\n")
    Path(path).write_text(doc)


def write_notebook(path, metrics) -> None:
    m = list(metrics)
    cells = [
        nbformat.v4.new_markdown_cell("# Reproduce this analysis\n\nRun from inside the analysis folder. Every table below is read from this "
                                      "folder's own CSVs; `scripts/` is the exact code that produced them. `python -m scripts run --params "
                                      "params.yaml --input input --out .` re-runs the whole analysis in place."),
        nbformat.v4.new_code_cell("import sys, pandas as pd\nsys.path.insert(0, '.')\nfrom scripts import csvmeta, params, split, figures\n"
                                  "P = params.load(\"params.yaml\")\nsomas, meta = csvmeta.read_csv(\"somas_filtered.csv\")\n"
                                  "subjects, _ = csvmeta.read_csv(\"subjects.csv\")\nqc, _ = csvmeta.read_csv(\"qc_stacks.csv\")\n"
                                  "print(meta['analysis_id'], meta['created'], meta['code_version'])\nsubjects"),
        nbformat.v4.new_code_cell(f"METRICS = {m!r}\nsp = split.run_split(somas, METRICS, P)\nsp.skipped_reason or sp.assignments"),
        nbformat.v4.new_code_cell("files, errors = figures.make_all(somas, subjects, qc, sp, METRICS, \"figures_notebook\", (\"png\",), P.analysis_id)\n"
                                  "from IPython.display import Image, display\nfor name in sorted(files):\n    display(Image(f\"figures_notebook/{files[name][0]}\"))\nerrors"),
    ]
    nb = nbformat.v4.new_notebook(cells=cells, metadata={"kernelspec": {"name": "python3", "display_name": "Python 3", "language": "python"}})
    nbformat.write(nb, str(path))
