"""Real-data benchmark track using packaged curated case studies."""

from __future__ import annotations

from pathlib import Path

import pandas as pd

from babappa.benchmark.comparators import write_comparator_note
from babappa.config import BABAPPAConfig
from babappa.io.fasta import read_alignment_map
from babappa.io.newick import read_newick
from babappa.workflow import adjust_scores_table, fit_null_bundle, score_genes


def _run_case(case_dir: Path, cfg: BABAPPAConfig, outdir: Path, seed: int) -> pd.DataFrame:
    tree = read_newick(case_dir / "tree.nwk")
    alignments = read_alignment_map(directory=str(case_dir / "alignments"))

    first_gene = sorted(alignments.keys())[0]
    bundle, _, _ = fit_null_bundle(
        alignment=alignments[first_gene],
        tree=tree,
        cfg=cfg,
        outdir=outdir / "fit_null",
        seed=seed,
        energy_family="gaussian",
    )

    scores = score_genes(
        alignments=alignments,
        tree=tree,
        bundle=bundle,
        cfg=cfg,
        outdir=outdir / "score",
        seed=seed + 17,
        jobs=max(1, cfg.runtime.jobs),
        resume=False,
    )
    adjusted = adjust_scores_table(scores, method="bh")
    adjusted.to_csv(outdir / "scores_adjusted.tsv", sep="\t", index=False)

    note = outdir / "biological_summary.txt"
    lines = [
        f"Case: {case_dir.name}",
        "Interpret significant genes as elevated gene-level dispersion relative to configured neutral model.",
        "Use site/branch methods (codeml/HyPhy) for mechanistic follow-up when needed.",
    ]
    note.write_text("\n".join(lines) + "\n", encoding="utf-8")
    return adjusted


def run_real_data_benchmark(cfg: BABAPPAConfig, outdir: str | Path, seed: int) -> pd.DataFrame:
    out = Path(outdir)
    out.mkdir(parents=True, exist_ok=True)

    base = Path(__file__).resolve().parents[1] / "data" / "examples"
    cases = [base / "real_case_1", base / "real_case_2"]

    rows: list[dict[str, object]] = []
    for i, case in enumerate(cases):
        case_out = out / case.name
        case_out.mkdir(parents=True, exist_ok=True)
        adjusted = _run_case(case, cfg=cfg, outdir=case_out, seed=seed + i * 31)
        for _, rec in adjusted.iterrows():
            rows.append(
                {
                    "case": case.name,
                    "gene": rec["gene"],
                    "statistic": float(rec["statistic"]),
                    "p_value": float(rec["p_value"]),
                    "q_value": float(rec["q_value"]),
                }
            )

    write_comparator_note(out / "comparators")

    summary = pd.DataFrame(rows)
    summary.to_csv(out / "real_data_summary.tsv", sep="\t", index=False)
    return summary
