"""
Extract structured metadata from each SR/MA markdown abstract in
01_revisiones_metaanalisis/ and write a CSV that the
data_extraction_filled.md table is generated from.

Fields not derivable from the abstract are marked "NR (full text needed)".

Usage:
    python extract_sr_metadata.py

Output:
    sr_metadata_extracted.csv  (one row per SR)
"""
from __future__ import annotations
import csv
import re
from pathlib import Path

ROOT = Path(__file__).resolve().parents[3]  # ganglio sergioc/
SR_DIR = ROOT / "01_revisiones_metaanalisis"
OUT_CSV = Path(__file__).resolve().parent / "sr_metadata_extracted.csv"

# Heuristic regexes against the markdown body
RE_PMID = re.compile(r"PMID:\*\*\s*(\d+)")
RE_DOI = re.compile(r"DOI:\*\*\s*\[([^\]]+)\]")
RE_JOURNAL = re.compile(r"\*\*Revista:\*\*\s*([^\(\n]+?)\s*\((\d{4})\)")
RE_AUTHORS = re.compile(r"\*\*Autores:\*\*\s*([^\n]+)")
RE_N_STUDIES = re.compile(r"(\d{1,3})\s+(?:unique\s+)?studies", re.I)
RE_N_PATIENTS = re.compile(r"([\d,]{3,})\s+(?:unique\s+)?patients", re.I)
RE_I2 = re.compile(r"I\s*[²\^2]?\s*=\s*([\d\.]+\s*%?)", re.I)
RE_DESIGN_MA = re.compile(r"meta-?analysis", re.I)
RE_DESIGN_SR = re.compile(r"systematic review", re.I)
RE_DESIGN_POOLED = re.compile(r"pooled (?:analysis|data)", re.I)
RE_DESIGN_NMA = re.compile(r"network meta-?analysis", re.I)


def classify_design(text: str) -> str:
    if RE_DESIGN_NMA.search(text):
        return "Network MA"
    if RE_DESIGN_POOLED.search(text):
        return "Pooled analysis"
    if RE_DESIGN_MA.search(text):
        return "MA"
    if RE_DESIGN_SR.search(text):
        return "SR"
    return "SR (inferred)"


def extract_from_md(path: Path) -> dict:
    text = path.read_text(encoding="utf-8", errors="replace")
    m_pmid = RE_PMID.search(text)
    m_doi = RE_DOI.search(text)
    m_journal = RE_JOURNAL.search(text)
    m_authors = RE_AUTHORS.search(text)
    m_n_studies = RE_N_STUDIES.search(text)
    m_n_patients = RE_N_PATIENTS.search(text)
    m_i2 = RE_I2.search(text)

    # Year/first author from filename: YYYY_FirstAuthor_...
    fname = path.stem
    parts = fname.split("_")
    year_fn = parts[0] if parts and parts[0].isdigit() else ""
    first_author_fn = parts[1] if len(parts) > 1 else ""

    return {
        "filename": path.name,
        "first_author": first_author_fn or (m_authors.group(1).split(",")[0].strip() if m_authors else ""),
        "year": year_fn or (m_journal.group(2) if m_journal else ""),
        "journal": m_journal.group(1).strip() if m_journal else "NR",
        "pmid": m_pmid.group(1) if m_pmid else "",
        "doi": m_doi.group(1) if m_doi else "",
        "design": classify_design(text),
        "n_included_studies": m_n_studies.group(1) if m_n_studies else "NR (full text needed)",
        "n_participants": m_n_patients.group(1) if m_n_patients else "NR (full text needed)",
        "i2_heterogeneity": m_i2.group(1) if m_i2 else "NR (full text needed)",
        "rob_tool": "NR (full text needed)",
        "grade_reported": "NR (full text needed)",
        "funding": "NR (full text needed)",
        "country": "NR (full text needed)",
    }


def main() -> None:
    if not SR_DIR.is_dir():
        raise SystemExit(f"Source folder not found: {SR_DIR}")
    md_files = sorted(SR_DIR.glob("*.md"))
    rows = [extract_from_md(p) for p in md_files]

    cols = [
        "filename", "first_author", "year", "journal", "pmid", "doi", "design",
        "n_included_studies", "n_participants", "i2_heterogeneity",
        "rob_tool", "grade_reported", "funding", "country",
    ]
    with OUT_CSV.open("w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=cols)
        w.writeheader()
        w.writerows(rows)
    print(f"Wrote {OUT_CSV}  ({len(rows)} rows)")


if __name__ == "__main__":
    main()
