"""One analysis run: params.yaml -> a self-contained folder (analysis spec 3.10)."""
from __future__ import annotations

import argparse
import json
import logging
import shutil
import sys
import traceback
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Optional

from . import __version__, csvmeta, inputs as inputs_mod, params as params_mod
from .aggregate import by_stack, by_subject
from .figures import make_all
from .filters import filter_somas, filter_stacks, qc_by_stack
from .metrics import add_metrics
from .report import ReportContext, build_report, write_html, write_markdown, write_notebook
from .split import run_split

STAGES = ("params", "inputs", "filters", "aggregate", "split", "figures", "report", "scripts", "summary")
log = logging.getLogger("synapse_analysis")

README = """# Analysis {analysis_id}

Label: {label} · created {created} · code {code_version} · dataset {dataset}

This folder is self-contained. `params.yaml` holds every parameter and the input run ids; `input/` holds the input
tables copied from those runs; `scripts/` is the exact analysis code that produced the outputs; every CSV starts with
a `#` header repeating the run metadata and parameters (`pd.read_csv(path, comment="#")` reads them).

## Re-run from this folder

    cd "{folder_name}"
    python -m scripts run --params params.yaml --input input --out .

Needs Python >= 3.9 with pandas, numpy, scipy, scikit-learn, matplotlib, pyyaml and nbformat.
`reproduce.ipynb` regenerates the figures from the tables (`jupyter notebook reproduce.ipynb`).

## Files

- `stacks_excluded.csv`, `somas_dropped.csv`, `qc_stacks.csv` — what the filters removed and why
- `somas_filtered.csv` — every kept soma with its metrics
- `stacks.csv`, `subjects.csv` — per stack and per subject x layer x hemisphere statistics (the unit of analysis)
- `split_*.csv`, `figures/split_*` — EXPLORATORY unsupervised split of subjects (not a group test)
- `figures/` — figures; `report.md` / `report.html` — the report; `summary.json` — counts; `log.txt` — the run log
"""


@dataclass
class RunSummary:
    analysis_id: str
    out_dir: str
    n_inputs: int
    n_problems: int
    n_stacks_kept: int
    n_somas_total: int
    n_somas_kept: int
    n_subjects: int
    split_skipped_reason: Optional[str]
    figures: dict
    figure_errors: dict


def _copy_scripts(out_dir: Path, code_version: str) -> None:
    src = Path(__file__).resolve().parent
    dst = (out_dir / "scripts").resolve()
    if src != dst:
        if dst.exists():
            shutil.rmtree(dst)
        shutil.copytree(src, dst, ignore=lambda d, names: [n for n in names if not n.endswith(".py")])
    (dst / "VERSION").write_text(f"code_version: {code_version}\npackage_version: {__version__}\n")


def run_analysis(params_path, out_dir, results_root=None, input_dir=None, on_stage=None) -> RunSummary:
    if (results_root is None) == (input_dir is None):
        raise ValueError("give exactly one of results_root and input_dir")
    out = Path(out_dir)
    out.mkdir(parents=True, exist_ok=True)
    handler = logging.FileHandler(out / "log.txt")
    handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
    log.addHandler(handler)
    log.setLevel(logging.INFO)

    def stage(name):
        log.info("stage: %s", name)
        if on_stage:
            on_stage(name)

    try:
        stage("params")
        params = params_mod.load(params_path)
        params.validate()
        pd_ = params_mod.to_dict(params)

        def write(df, name):                       # every table is named by its file stem
            csvmeta.write_csv(df, out / name, csvmeta.meta_from_params(pd_, name[:-4]))

        stage("inputs")
        if input_dir is not None:
            collected = inputs_mod.collect_from_dir(input_dir)
            if Path(input_dir).resolve() != (out / "input").resolve():
                inputs_mod.write_inputs(collected, out / "input", pd_)
        else:
            collected = inputs_mod.collect(results_root, params.inputs)
            inputs_mod.write_inputs(collected, out / "input", pd_)
        log.info("%d inputs, %d problems", len(params.inputs), len(collected.problems))

        stage("filters")
        stacks_kept, stacks_dropped = filter_stacks(collected.stacks, params)
        kept_names = set(stacks_kept["stack"].astype(str))
        somas_in = collected.somas[collected.somas["stack"].astype(str).isin(kept_names)].reset_index(drop=True) if len(collected.somas) else collected.somas
        somas_in = add_metrics(somas_in)
        somas_kept, somas_dropped = filter_somas(somas_in, params)
        qc = qc_by_stack(somas_in, somas_kept, somas_dropped, all_stacks=sorted(kept_names))
        write(stacks_dropped, "stacks_excluded.csv"); write(somas_kept, "somas_filtered.csv"); write(somas_dropped, "somas_dropped.csv"); write(qc, "qc_stacks.csv")

        stage("aggregate")
        stacks = by_stack(somas_kept, params.metrics)
        subjects = by_subject(somas_kept, params.metrics)
        write(stacks, "stacks.csv"); write(subjects, "subjects.csv")

        stage("split")
        split = run_split(somas_kept, params.metrics, params)
        if split.skipped_reason is None:
            write(split.features.reset_index(), "split_features.csv"); write(split.assignments, "split_assignments.csv")
            write(split.stability.reset_index().rename(columns={"index": "animal"}), "split_stability.csv"); write(split.summary, "split_summary.csv")
        else:
            log.info("split skipped: %s", split.skipped_reason)

        stage("figures")
        figures, figure_errors = make_all(somas_kept, subjects, qc, split, params.metrics, out / "figures", params.figure_format, params.analysis_id)
        for name, err in figure_errors.items():
            log.error("figure %s failed: %s", name, err)

        stage("report")
        ctx = ReportContext(pd_, collected.problems, stacks_dropped, qc, subjects, split, figures, figure_errors, len(params.inputs),
                            len(stacks_kept), len(somas_in), len(somas_kept))
        report = build_report(ctx)
        write_markdown(report, out / "report.md"); write_html(report, out / "report.html")
        write_notebook(out / "reproduce.ipynb", params.metrics)

        stage("scripts")
        _copy_scripts(out, params.code_version)
        (out / "README.md").write_text(README.format(analysis_id=params.analysis_id, label=params.label, created=params.created,
                                                     code_version=params.code_version, dataset=params.dataset, folder_name=out.name))

        stage("summary")
        s = RunSummary(params.analysis_id, str(out), len(params.inputs), len(collected.problems), len(stacks_kept), len(somas_in), len(somas_kept),
                       int(subjects["animal"].nunique()) if len(subjects) else 0, split.skipped_reason, figures, figure_errors)
        (out / "summary.json").write_text(json.dumps(asdict(s), indent=1, sort_keys=True))
        return s
    except Exception:
        log.error("analysis failed\n%s", traceback.format_exc())
        raise
    finally:
        log.removeHandler(handler)
        handler.close()


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(prog="synapse_analysis")
    sub = ap.add_subparsers(dest="cmd", required=True)
    r = sub.add_parser("run", help="run an analysis into a folder")
    r.add_argument("--params", required=True)
    src = r.add_mutually_exclusive_group(required=True)
    src.add_argument("--results-root", help="folder holding the input run folders")
    src.add_argument("--input", help="an analysis folder's input/ directory (re-run from a folder)")
    r.add_argument("--out", required=True)
    a = ap.parse_args(argv)
    try:
        s = run_analysis(a.params, a.out, results_root=a.results_root, input_dir=a.input)
    except Exception as e:
        print(f"analysis failed: {type(e).__name__}: {e}", file=sys.stderr)
        return 1
    print(f"analysis {s.analysis_id}: n_inputs={s.n_inputs} n_problems={s.n_problems} n_stacks_kept={s.n_stacks_kept} "
          f"n_somas_kept={s.n_somas_kept} n_subjects={s.n_subjects} split={'ok' if s.split_skipped_reason is None else 'skipped'}")
    return 0
