"""SHM GCMIP-analog quality improvement report generator (한국어/영문).

산출물:
  - docx (python-docx 가 설치되어 있으면)
  - markdown (항상)
  - 텍스트 콘솔 요약 (CLI)

SHM Glycemic Control Mentored Implementation Program 의 측정 set 을
한국 KDA 입원당뇨 가이드 + ADA 2025 inpatient 와 cross-mapping.

참고용·연구용 — Not for clinical decision making.
"""
from __future__ import annotations

import os
from dataclasses import asdict
from datetime import datetime
from typing import Dict, List

from .tir import WardTIR
from .regimen import WardRegimenMix
from .episode import EpisodeTrajectory
from .subgroup import SubgroupKPI
from .transition import TransitionSummary

DISCLAIMER_KOR = (
    "본 리포트는 참고용·연구용입니다. 임상 의사결정 도구가 아닙니다. "
    "데이터는 de-identified surrogate 이며 실제 환자 정보가 포함되어 있지 않습니다."
)
DISCLAIMER_ENG = (
    "This report is for research / reference use only. NOT a clinical decision tool. "
    "All data are de-identified surrogates and contain no real PHI."
)


def build_markdown(ward_tir: List[WardTIR],
                   regimen_mix: List[WardRegimenMix],
                   episodes: List[EpisodeTrajectory],
                   subgroups: List[SubgroupKPI],
                   transition: TransitionSummary,
                   km_rows: List[tuple],
                   language: str = "ko") -> str:
    L = language.lower()
    today = datetime.now().strftime("%Y-%m-%d")
    lines: List[str] = []

    if L == "ko":
        lines += [
            f"# 인합글라이워드코어 (InHospGlyWard-Kor) — 입원 혈당관리 KPI 리포트",
            f"_생성일: {today}_",
            "",
            f"> {DISCLAIMER_KOR}",
            "",
            "## 1. Ward별 ADA/KDA 입원 TIR",
            "| Ward | N환자 | N측정 | TIR창(mg/dL) | TIR% | 평균BG | hypo<70% | hyper>180% | persistent hyper | KDA점수 |",
            "|---|---|---|---|---|---|---|---|---|---|",
        ]
        for w in ward_tir:
            lines.append(
                f"| {w.ward} | {w.n_patients} | {w.n_readings} | {w.tir_low}-{w.tir_high} "
                f"| {w.pct_in_range} | {w.mean_bg} | {w.pct_hypo_l1} | {w.pct_hyper_180} "
                f"| {w.n_persistent_hyper} | {w.kda_compliance_score} |"
            )
        lines += [
            "",
            "## 2. Ward별 인슐린 처방 mix (basal-bolus vs sliding-scale-only)",
            "| Ward | N | basal-bolus% | sliding-scale-only% | IV-infusion% | basal-only% | no-insulin% | ADA bb율 | SS-only 패널티 |",
            "|---|---|---|---|---|---|---|---|---|",
        ]
        for r in regimen_mix:
            lines.append(
                f"| {r.ward} | {r.n_orders} | {r.pct_basal_bolus} | {r.pct_sliding_scale_only} "
                f"| {r.pct_iv_infusion} | {r.pct_basal_only} | {r.pct_no_insulin} "
                f"| {r.ada_basal_bolus_rate} | {r.sliding_scale_only_penalty} |"
            )
        lines += [
            "",
            "## 3. DKA / HHS / Hypo episode trajectory",
            "| 종류 | N | 해소율% | 중앙해소시간(h) | K+ 보충% | 수액(L/24h) | IV rate(U/h) | bb 전환% | protocol 부합% |",
            "|---|---|---|---|---|---|---|---|---|",
        ]
        for e in episodes:
            lines.append(
                f"| {e.episode_type} | {e.n_total} | {e.resolution_rate} | {e.median_resolution_h} "
                f"| {e.pct_k_supplement} | {e.median_fluid_l_24h} | {e.median_iv_rate_uhr} "
                f"| {e.pct_transition_basal_bolus} | {e.protocol_compliance_pct} |"
            )
        lines += [
            "",
            "## 4. Subgroup KPI (perioperative / steroid / TPN-PN / ER)",
            "| Subgroup | N환자 | N측정 | 평균BG | 140-180% | hypo<70% | hyper>250% | protocol | 부합% |",
            "|---|---|---|---|---|---|---|---|---|",
        ]
        for s in subgroups:
            lines.append(
                f"| {s.subgroup} | {s.n_patients} | {s.n_readings} | {s.mean_bg} "
                f"| {s.pct_in_140_180} | {s.pct_hypo_l1} | {s.pct_hyper_250} "
                f"| {s.protocol_label} | {s.protocol_compliance_pct} |"
            )
        lines += [
            "",
            "## 5. Discharge transition & 30일 readmission",
            f"- 총 환자: **{transition.n_total}**",
            f"- 30일 readmission: **{transition.n_readmit_30d} ({transition.readmit_rate_pct}%)**",
            f"- 중앙 재입원까지 일수: **{transition.median_time_to_readmit_d}일**",
            f"- discharge 처방 mix: {transition.discharge_regimen_mix}",
            f"- 재입원 사유 mix: {transition.readmit_reason_mix}",
            "",
            "### Kaplan-Meier (생존: 30일 내 재입원 없을 확률)",
            "| Day | S(t) | n_at_risk |",
            "|---|---|---|",
        ]
        for d, s, n in km_rows[:30]:
            lines.append(f"| {d} | {s} | {n} |")
        lines += [
            "",
            "## 6. 참고문헌 / 표준",
            "- ADA Standards of Care 2025 — Diabetes Care in the Hospital",
            "- KDA 진료지침 2023 — 입원 환자 당뇨병 관리",
            "- AACE Inpatient Glycemic Management Consensus",
            "- SHM Glycemic Control Mentored Implementation Program (GCMIP) measure set",
            "- NICE-SUGAR / DIGAMI / GIK protocols",
            "",
            f"> {DISCLAIMER_KOR}",
        ]
    else:
        lines += [
            f"# InHospGlyWard-Kor — Inpatient Glycemic KPI Report",
            f"_Generated: {today}_",
            "",
            f"> {DISCLAIMER_ENG}",
            "",
            "## 1. Ward-level ADA/KDA inpatient TIR",
            "| Ward | N pt | N rdg | TIR (mg/dL) | TIR% | Mean BG | hypo<70% | hyper>180% | persistent hyper | KDA score |",
            "|---|---|---|---|---|---|---|---|---|---|",
        ]
        for w in ward_tir:
            lines.append(
                f"| {w.ward} | {w.n_patients} | {w.n_readings} | {w.tir_low}-{w.tir_high} "
                f"| {w.pct_in_range} | {w.mean_bg} | {w.pct_hypo_l1} | {w.pct_hyper_180} "
                f"| {w.n_persistent_hyper} | {w.kda_compliance_score} |"
            )
        lines += [
            "",
            "## 2. Ward insulin regimen mix",
            "| Ward | N | basal-bolus% | sliding-only% | IV infusion% | basal-only% | no-insulin% | ADA bb rate | SS-only penalty |",
            "|---|---|---|---|---|---|---|---|---|",
        ]
        for r in regimen_mix:
            lines.append(
                f"| {r.ward} | {r.n_orders} | {r.pct_basal_bolus} | {r.pct_sliding_scale_only} "
                f"| {r.pct_iv_infusion} | {r.pct_basal_only} | {r.pct_no_insulin} "
                f"| {r.ada_basal_bolus_rate} | {r.sliding_scale_only_penalty} |"
            )
        lines += [
            "",
            "## 3. Episode trajectory",
            "| Type | N | Resolved% | Median res.(h) | K+ supp% | Fluid L/24h | IV rate U/h | bb transition% | protocol compl% |",
            "|---|---|---|---|---|---|---|---|---|",
        ]
        for e in episodes:
            lines.append(
                f"| {e.episode_type} | {e.n_total} | {e.resolution_rate} | {e.median_resolution_h} "
                f"| {e.pct_k_supplement} | {e.median_fluid_l_24h} | {e.median_iv_rate_uhr} "
                f"| {e.pct_transition_basal_bolus} | {e.protocol_compliance_pct} |"
            )
        lines += [
            "",
            "## 4. Subgroup KPI",
            "| Subgroup | N pt | N rdg | Mean BG | 140-180% | hypo<70% | hyper>250% | Protocol | compliance% |",
            "|---|---|---|---|---|---|---|---|---|",
        ]
        for s in subgroups:
            lines.append(
                f"| {s.subgroup} | {s.n_patients} | {s.n_readings} | {s.mean_bg} "
                f"| {s.pct_in_140_180} | {s.pct_hypo_l1} | {s.pct_hyper_250} "
                f"| {s.protocol_label} | {s.protocol_compliance_pct} |"
            )
        lines += [
            "",
            "## 5. Discharge transition & 30-day readmission",
            f"- Total patients: **{transition.n_total}**",
            f"- 30-day readmissions: **{transition.n_readmit_30d} ({transition.readmit_rate_pct}%)**",
            f"- Median time to readmit: **{transition.median_time_to_readmit_d} d**",
            f"- Discharge regimen mix: {transition.discharge_regimen_mix}",
            f"- Readmit reason mix: {transition.readmit_reason_mix}",
            "",
            "### Kaplan-Meier (survival = no readmit by day t)",
            "| Day | S(t) | n_at_risk |",
            "|---|---|---|",
        ]
        for d, s, n in km_rows[:30]:
            lines.append(f"| {d} | {s} | {n} |")
        lines += [
            "",
            "## 6. References / standards",
            "- ADA Standards of Care 2025 — Diabetes Care in the Hospital",
            "- KDA Clinical Practice Guideline 2023 — Inpatient diabetes",
            "- AACE Inpatient Glycemic Management Consensus",
            "- SHM GCMIP measure set",
            "- NICE-SUGAR / DIGAMI / GIK protocols",
            "",
            f"> {DISCLAIMER_ENG}",
        ]
    return "\n".join(lines)


def write_markdown(path: str, content: str) -> str:
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        f.write(content)
    return path


def write_docx(path: str, md_text: str, title: str) -> str:
    """If python-docx is installed, produce a simple docx of the report.
    Returns the actual path written. Falls back to writing .md if docx unavailable.
    """
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    try:
        from docx import Document  # type: ignore
        doc = Document()
        doc.add_heading(title, level=0)
        for line in md_text.splitlines():
            if line.startswith("# "):
                doc.add_heading(line[2:], level=1)
            elif line.startswith("## "):
                doc.add_heading(line[3:], level=2)
            elif line.startswith("### "):
                doc.add_heading(line[4:], level=3)
            elif line.startswith("|"):
                # render as plain text — keeping it simple
                doc.add_paragraph(line)
            elif line.startswith("> "):
                p = doc.add_paragraph()
                run = p.add_run(line[2:])
                run.italic = True
            elif line.strip() == "":
                doc.add_paragraph()
            else:
                doc.add_paragraph(line)
        doc.save(path)
        return path
    except Exception:
        fallback = path.rsplit(".", 1)[0] + ".md"
        with open(fallback, "w", encoding="utf-8") as f:
            f.write(md_text)
        return fallback
