"""HTA·규제·KASMBS·OpenClaw 리포트 생성.

python-docx 있으면 .docx, 없으면 markdown으로 fallback.
"""
from __future__ import annotations

import json
from pathlib import Path
from typing import Dict, List, Optional

DISCLAIMER = (
    "⚠️ 본 도구는 연구 가설 생성·문헌 갭 분석 목적의 연구용·교육용 도구입니다. "
    "임상의사결정·환자 진료에 직접 사용해서는 안 되며, 모든 분석 결과는 추가 검증이 필요합니다. "
    "비만 약물·수술 선택은 반드시 자격 있는 임상의와 상담 후 결정해야 합니다."
)


def build_report_dict(intervention: str, outcome: str) -> Dict:
    """모든 분석 모듈을 호출해 통합 리포트 데이터 생성."""
    from .grid import get_pair_rows, concordance_score
    from .lawlor import lawlor_score
    from .mvmr import mvmr_for_pair
    from .mediation import mediation_for_pair
    from .bias import diagnose_discordance
    from .designs import recommend_designs

    rows = get_pair_rows(intervention, outcome)
    return {
        "title": f"ObesityTriangulate Report — {intervention} × {outcome}",
        "disclaimer": DISCLAIMER,
        "intervention": intervention,
        "outcome": outcome,
        "n_evidence_rows": len(rows),
        "concordance": concordance_score(rows),
        "lawlor_5criterion": lawlor_score(intervention, outcome),
        "mvmr_decomposition": mvmr_for_pair(intervention, outcome),
        "weight_loss_mediation": mediation_for_pair(intervention, outcome),
        "discordance_diagnosis": diagnose_discordance(intervention, outcome),
        "next_design_recommendations": recommend_designs(intervention, outcome),
        "raw_evidence_rows": rows,
    }


def to_markdown(report: Dict) -> str:
    """리포트를 markdown으로 직렬화."""
    md = [
        f"# {report['title']}",
        "",
        f"> {report['disclaimer']}",
        "",
        f"- intervention: **{report['intervention']}**",
        f"- outcome: **{report['outcome']}**",
        f"- evidence rows: {report['n_evidence_rows']}",
        "",
        "## 1. Concordance",
        "```json",
        json.dumps(report["concordance"], ensure_ascii=False, indent=2),
        "```",
        "",
        "## 2. Lawlor 5-criterion",
        "```json",
        json.dumps(report["lawlor_5criterion"], ensure_ascii=False, indent=2),
        "```",
        "",
        "## 3. Multivariable MR (BMI / WHR / BF%)",
        "```json",
        json.dumps(report["mvmr_decomposition"], ensure_ascii=False, indent=2),
        "```",
        "",
        "## 4. Weight-loss mediation",
        "```json",
        json.dumps(report["weight_loss_mediation"], ensure_ascii=False, indent=2),
        "```",
        "",
        "## 5. Discordance diagnosis",
        "```json",
        json.dumps(report["discordance_diagnosis"], ensure_ascii=False, indent=2),
        "```",
        "",
        "## 6. Triangulation-targeted 후속 design (8 cards)",
    ]
    for i, card in enumerate(report["next_design_recommendations"], 1):
        md += [
            f"### {i}. {card['type']}",
            f"- rationale: {card['rationale']}",
            f"- primary endpoint: {card.get('primary_endpoint')}",
            f"- sample size: {card.get('sample_size_estimate')}",
            f"- follow-up: {card.get('follow_up_years')}년",
            f"- key hypothesis: {card.get('key_hypothesis')}",
            f"- key threats: {card.get('key_threats')}",
            "",
        ]
    md += [
        "## 7. Raw evidence rows",
        "| design | estimate | 95% CI | n | follow-up | population | source |",
        "|---|---|---|---|---|---|---|",
    ]
    for r in report["raw_evidence_rows"]:
        md.append(
            f"| {r['design']} | {r['effect_estimate']} | "
            f"[{r['ci_low']}, {r['ci_high']}] | {r['sample_size']} | "
            f"{r['follow_up_years']} | {r['population']} | "
            f"{r['source_citation']} |"
        )
    return "\n".join(md)


def to_docx(report: Dict, out_path: str) -> Optional[str]:
    """python-docx로 .docx 저장. 미설치 시 markdown 저장."""
    try:
        from docx import Document
        doc = Document()
        doc.add_heading(report["title"], level=1)
        doc.add_paragraph(report["disclaimer"])
        for section, key in [
            ("Concordance", "concordance"),
            ("Lawlor 5-criterion", "lawlor_5criterion"),
            ("MVMR", "mvmr_decomposition"),
            ("Weight-loss mediation", "weight_loss_mediation"),
            ("Discordance diagnosis", "discordance_diagnosis"),
        ]:
            doc.add_heading(section, level=2)
            doc.add_paragraph(json.dumps(report[key], ensure_ascii=False, indent=2))
        doc.add_heading("Next design recommendations", level=2)
        for card in report["next_design_recommendations"]:
            doc.add_heading(card["type"], level=3)
            doc.add_paragraph(f"Rationale: {card['rationale']}")
            doc.add_paragraph(f"Hypothesis: {card.get('key_hypothesis', '')}")
        doc.save(out_path)
        return out_path
    except ImportError:
        # fallback markdown
        md_path = out_path.replace(".docx", ".md")
        Path(md_path).write_text(to_markdown(report), encoding="utf-8")
        return md_path


def save_report(intervention: str, outcome: str, out_path: str = "report.json") -> str:
    report = build_report_dict(intervention, outcome)
    if out_path.endswith(".docx"):
        return to_docx(report, out_path) or out_path
    if out_path.endswith(".md"):
        Path(out_path).write_text(to_markdown(report), encoding="utf-8")
        return out_path
    Path(out_path).write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
    return out_path


if __name__ == "__main__":
    r = build_report_dict("semaglutide", "CV death")
    print(to_markdown(r)[:2000])
