#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MASLDBiomarkerQualifierWatch-Kor (매슬드바이오마커퀄리파이어워치코어)
=====================================================================
MASLD/MASH 진단 바이오마커 multi-pathway qualification 모니터링 + 디덥 +
중요도 스코어링 + 한국어 weekly digest + KFDA 동등성 dossier auto-draft +
MASLDStager alignment.

도메인: MASLD (대사성간질환)
카테고리: 연구 알림 (Python CLI)
빌드 일자: 2026-05-14

본 도구는 연구·교육·참고용입니다. 실제 바이오마커 qualification 결정은
FDA Biomarker Qualification Program, EMA, KFDA 등 공식 기관 데이터를
반드시 확인하십시오. Mock data로 동작하며 실제 qualification 정보가 아닙니다.
임상 진단·치료 결정은 의사와의 협의 하에 이루어져야 합니다.
"""

from __future__ import annotations

import argparse
import json
import sys
import textwrap
from collections import Counter, defaultdict
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any

# -----------------------------------------------------------------------------
# Constants
# -----------------------------------------------------------------------------

ROOT = Path(__file__).resolve().parent
DATA_DIR = ROOT / "data"

PATHWAY_CHOICES = [
    "FDA-BQP",
    "EMA-LoS",
    "EMA-QO",
    "ICH-M10",
    "KFDA",
    "DDTII",
    "CTTI",
    "LITMUS",
    "NIMBLE",
    "ALL",
]
BIOMARKER_TYPES = ["ECM", "NIT", "IMAGING", "GENETIC", "BREATH", "AI-SAMD", "PRO", "ALL"]
COU_CHOICES = [
    "screening",
    "diagnosis",
    "staging",
    "prognosis",
    "monitoring",
    "companion",
    "ALL",
]
TRIAL_CHOICES = [
    "MAESTRO",
    "HARMONY",
    "SYMMETRY",
    "ENLIVEN",
    "ENLIGHTEN",
    "SYNERGY",
    "LIVERAGE",
    "NATIV3",
    "REVERSE",
]

PATHWAY_TIER_WEIGHT = {
    "FDA-BQP": 5.0,
    "EMA-QO": 4.5,
    "EMA-LoS": 3.5,
    "ICH-M10": 3.0,
    "KFDA": 4.0,  # 한국 컨텍스트에서는 가산
    "DDTII": 2.0,
    "CTTI": 2.5,
    "LITMUS": 3.0,
    "NIMBLE": 3.0,
}

STATUS_WEIGHT = {
    "qualified": 5.0,
    "harmonized": 4.5,
    "letter_of_support": 3.5,
    "consensus_published": 3.0,
    "under_review": 2.5,
    "submitted": 2.0,
    "workshop_discussion": 1.5,
}

COU_CLINICAL_UTILITY = {
    "staging": 5.0,
    "diagnosis": 4.5,
    "prognosis": 4.0,
    "monitoring": 3.5,
    "companion": 3.5,
    "screening": 3.0,
}

DISCLAIMER = (
    "본 도구는 연구·교육·참고용입니다. 실제 바이오마커 qualification 결정은 "
    "FDA Biomarker Qualification Program, EMA, KFDA 등 공식 기관 데이터를 반드시 확인하십시오. "
    "Mock data로 동작하며 실제 qualification 정보가 아닙니다. "
    "임상 진단·치료 결정은 의사와의 협의 하에 이루어져야 합니다."
)

# MASLDStager 핀포인트 컨셉: NIT-based staging tool 데이터 layer가 선호하는
# 바이오마커 (staging/diagnosis CoU + imaging/NIT + qualified 우선)
MASLDSTAGER_PREFERRED_TYPES = {"NIT", "IMAGING", "ECM"}
MASLDSTAGER_PREFERRED_COU = {"staging", "diagnosis", "prognosis"}


# -----------------------------------------------------------------------------
# Data classes
# -----------------------------------------------------------------------------


@dataclass
class Qualification:
    biomarker_id: str
    name: str
    biomarker_type: str
    pathway: str
    submission_date: str
    decision_date: str | None
    status: str
    context_of_use: str
    indication: str
    population: str
    analytical_validation: str
    clinical_validation: str
    clinical_utility: str
    tier_rank: int
    score: float = 0.0
    score_breakdown: dict[str, float] = field(default_factory=dict)
    masld_stager_alignment: float = 0.0
    korea_strategy_flag: bool = False


@dataclass
class Milestone:
    milestone_id: str
    consortium: str
    title: str
    date: str
    deliverable: str
    korean_site_participation: bool
    linked_biomarkers: list[str]


@dataclass
class Trial:
    trial_code: str
    drug: str
    sponsor: str
    phase: str
    n: int
    primary_endpoint: str
    biomarkers_used: list[str]
    korean_sites: int
    status: str
    biomarker_data_summary: str


@dataclass
class Abstract:
    abstract_id: str
    society: str
    title: str
    session: str
    linked_biomarker: str
    korean_authors: bool
    importance: str
    summary: str


# -----------------------------------------------------------------------------
# Loaders
# -----------------------------------------------------------------------------


def _load_json(path: Path) -> dict[str, Any]:
    if not path.exists():
        raise FileNotFoundError(f"필수 데이터 파일 누락: {path}")
    with path.open("r", encoding="utf-8") as fh:
        return json.load(fh)


def load_qualifications() -> list[Qualification]:
    data = _load_json(DATA_DIR / "qualifications.json")
    return [Qualification(**entry) for entry in data["entries"]]


def load_milestones() -> list[Milestone]:
    data = _load_json(DATA_DIR / "litmus_nimble.json")
    return [Milestone(**entry) for entry in data["milestones"]]


def load_trials() -> list[Trial]:
    data = _load_json(DATA_DIR / "trials.json")
    return [Trial(**entry) for entry in data["trials"]]


def load_abstracts() -> list[Abstract]:
    data = _load_json(DATA_DIR / "abstracts.json")
    return [Abstract(**entry) for entry in data["abstracts"]]


def load_dossier_template() -> dict[str, Any]:
    data = _load_json(DATA_DIR / "dossier_template.json")
    return data["template"]


# -----------------------------------------------------------------------------
# Dedup
# -----------------------------------------------------------------------------


def dedupe_qualifications(items: list[Qualification]) -> list[Qualification]:
    """동일 (name, pathway) 조합은 더 진행된 status를 우선."""
    bucket: dict[tuple[str, str], Qualification] = {}
    for q in items:
        key = (q.name.strip().lower(), q.pathway)
        prev = bucket.get(key)
        if prev is None:
            bucket[key] = q
            continue
        if STATUS_WEIGHT.get(q.status, 0) > STATUS_WEIGHT.get(prev.status, 0):
            bucket[key] = q
    return list(bucket.values())


# -----------------------------------------------------------------------------
# Scoring
# -----------------------------------------------------------------------------


def _korea_strategy_flag(q: Qualification) -> bool:
    text = " ".join(
        [q.pathway, q.population, q.indication, q.clinical_utility, q.analytical_validation]
    )
    keywords = ("KFDA", "MFDS", "HIRA", "KASL", "한국", "Korean", "KoGES")
    return any(k in text for k in keywords)


def _masld_stager_alignment(q: Qualification) -> float:
    score = 0.0
    if q.biomarker_type in MASLDSTAGER_PREFERRED_TYPES:
        score += 2.0
    if q.context_of_use in MASLDSTAGER_PREFERRED_COU:
        score += 2.0
    if q.status in ("qualified", "harmonized", "letter_of_support"):
        score += 1.5
    if q.tier_rank == 1:
        score += 1.0
    return round(score, 2)


def score_qualification(q: Qualification) -> Qualification:
    pathway_w = PATHWAY_TIER_WEIGHT.get(q.pathway, 1.0)
    status_w = STATUS_WEIGHT.get(q.status, 1.0)
    cou_w = COU_CLINICAL_UTILITY.get(q.context_of_use, 1.0)
    tier_bonus = max(0.0, 4.0 - float(q.tier_rank))  # tier_rank 1 -> +3, 2 -> +2, 3 -> +1

    korea_flag = _korea_strategy_flag(q)
    korea_bonus = 1.5 if korea_flag else 0.0
    alignment = _masld_stager_alignment(q)

    total = pathway_w + status_w + cou_w + tier_bonus + korea_bonus + alignment

    q.score = round(total, 2)
    q.score_breakdown = {
        "pathway": round(pathway_w, 2),
        "status": round(status_w, 2),
        "cou_utility": round(cou_w, 2),
        "tier_bonus": round(tier_bonus, 2),
        "korea_bonus": round(korea_bonus, 2),
        "masld_stager_alignment": alignment,
    }
    q.masld_stager_alignment = alignment
    q.korea_strategy_flag = korea_flag
    return q


def score_all(items: list[Qualification]) -> list[Qualification]:
    return [score_qualification(q) for q in items]


# -----------------------------------------------------------------------------
# Filters
# -----------------------------------------------------------------------------


def filter_items(
    items: list[Qualification],
    pathway: str | None = None,
    biomarker_type: str | None = None,
    cou: str | None = None,
) -> list[Qualification]:
    out = items
    if pathway and pathway != "ALL":
        if pathway in {"LITMUS", "NIMBLE"}:
            # 컨소시엄 필터는 별도 흐름 (milestones에서 처리). 여기선 통과.
            pass
        else:
            out = [q for q in out if q.pathway == pathway]
    if biomarker_type and biomarker_type != "ALL":
        out = [q for q in out if q.biomarker_type == biomarker_type]
    if cou and cou != "ALL":
        out = [q for q in out if q.context_of_use == cou]
    return out


# -----------------------------------------------------------------------------
# Formatters
# -----------------------------------------------------------------------------


def _hr(char: str = "=", width: int = 78) -> str:
    return char * width


def fmt_disclaimer() -> str:
    return textwrap.fill(DISCLAIMER, width=78)


def fmt_summary(
    quals: list[Qualification],
    milestones: list[Milestone],
    trials: list[Trial],
    abstracts: list[Abstract],
) -> str:
    by_pathway = Counter(q.pathway for q in quals)
    by_type = Counter(q.biomarker_type for q in quals)
    by_status = Counter(q.status for q in quals)
    by_cou = Counter(q.context_of_use for q in quals)
    korea_n = sum(1 for q in quals if q.korea_strategy_flag)
    masld_stager_top = sum(1 for q in quals if q.masld_stager_alignment >= 5.0)

    lines = []
    lines.append(_hr("="))
    lines.append("MASLDBiomarkerQualifierWatch-Kor :: 요약 (2026-05-14)")
    lines.append(_hr("="))
    lines.append(f"전체 qualification entry: {len(quals)}건")
    lines.append(f"  - Pathway 분포  : {dict(by_pathway)}")
    lines.append(f"  - Type 분포     : {dict(by_type)}")
    lines.append(f"  - Status 분포   : {dict(by_status)}")
    lines.append(f"  - CoU 분포      : {dict(by_cou)}")
    lines.append(f"  - 한국 전략 플래그: {korea_n}건")
    lines.append(f"  - MASLDStager 정렬(>=5.0): {masld_stager_top}건")
    lines.append("")
    lines.append(f"LITMUS/NIMBLE milestone: {len(milestones)}건")
    kor_ms = sum(1 for m in milestones if m.korean_site_participation)
    lines.append(f"  - 한국 사이트 참여: {kor_ms}건")
    lines.append("")
    lines.append(f"Phase 3 MASH trial biomarker entry: {len(trials)}건")
    lines.append("")
    lines.append(f"학회/컨소시엄 abstract: {len(abstracts)}건")
    kor_abs = sum(1 for a in abstracts if a.korean_authors)
    lines.append(f"  - 한국 저자 포함: {kor_abs}건")
    lines.append("")
    lines.append(fmt_disclaimer())
    lines.append(_hr("="))
    return "\n".join(lines)


def fmt_qualification_row(q: Qualification, idx: int) -> str:
    decision = q.decision_date or "(미정)"
    bd = q.score_breakdown
    breakdown_str = (
        f"pathway {bd.get('pathway', 0)} | status {bd.get('status', 0)} | "
        f"cou {bd.get('cou_utility', 0)} | tier+{bd.get('tier_bonus', 0)} | "
        f"한국+{bd.get('korea_bonus', 0)} | stager+{bd.get('masld_stager_alignment', 0)}"
    )
    kor_tag = " [KOR]" if q.korea_strategy_flag else ""
    return (
        f"{idx:>2}. [{q.biomarker_id}] {q.name}{kor_tag}\n"
        f"     Pathway     : {q.pathway}  |  Status: {q.status}  |  Decision: {decision}\n"
        f"     Type / CoU  : {q.biomarker_type}  |  {q.context_of_use}\n"
        f"     Indication  : {q.indication}\n"
        f"     Population  : {q.population}\n"
        f"     Analytical  : {q.analytical_validation}\n"
        f"     Clinical    : {q.clinical_validation}\n"
        f"     Utility     : {q.clinical_utility}\n"
        f"     점수        : {q.score}  ({breakdown_str})"
    )


def fmt_milestone_row(m: Milestone, idx: int) -> str:
    kor = "[한국 사이트 참여]" if m.korean_site_participation else ""
    return (
        f"{idx:>2}. [{m.milestone_id}] {m.consortium} :: {m.title}  {kor}\n"
        f"     일자        : {m.date}\n"
        f"     산출물      : {m.deliverable}\n"
        f"     연관 BMK    : {', '.join(m.linked_biomarkers)}"
    )


def fmt_abstract_row(a: Abstract, idx: int) -> str:
    kor = "[KOR 저자]" if a.korean_authors else ""
    return (
        f"{idx:>2}. [{a.abstract_id}] {a.society}  {kor}\n"
        f"     세션        : {a.session}  |  중요도: {a.importance}\n"
        f"     제목        : {a.title}\n"
        f"     연관 BMK    : {a.linked_biomarker}\n"
        f"     요약        : {a.summary}"
    )


def fmt_trial(t: Trial) -> str:
    return (
        f"[{t.trial_code}] {t.drug}  (sponsor: {t.sponsor}, phase {t.phase}, n={t.n})\n"
        f"  Primary EP   : {t.primary_endpoint}\n"
        f"  Status       : {t.status}\n"
        f"  한국 사이트  : {t.korean_sites}\n"
        f"  사용 BMK     : {', '.join(t.biomarkers_used)}\n"
        f"  Biomarker 데이터 요약: {t.biomarker_data_summary}"
    )


# -----------------------------------------------------------------------------
# Digest builder
# -----------------------------------------------------------------------------


def build_weekly_digest(
    quals: list[Qualification],
    milestones: list[Milestone],
    trials: list[Trial],
    abstracts: list[Abstract],
    top: int,
) -> str:
    quals_sorted = sorted(quals, key=lambda q: q.score, reverse=True)
    top_quals = quals_sorted[: max(top, 15)] if top < 15 else quals_sorted[:top]
    # Spec: top 15 qualification, top 10 abstract, top 5 Korea, top 5 MASLDStager
    digest_quals_n = max(top, 15)
    digest_abstracts_n = max(top, 10)
    digest_korea_n = max(top, 5)
    digest_stager_n = max(top, 5)

    importance_order = {"high": 3, "medium": 2, "low": 1}
    abstracts_sorted = sorted(
        abstracts, key=lambda a: importance_order.get(a.importance, 0), reverse=True
    )

    korea_picks = [q for q in quals_sorted if q.korea_strategy_flag][:digest_korea_n]
    stager_picks = sorted(
        quals, key=lambda q: q.masld_stager_alignment, reverse=True
    )[:digest_stager_n]

    out: list[str] = []
    out.append(_hr("="))
    out.append("MASLD 바이오마커 Qualification 주간 다이제스트 (2026-05-14, 한국어)")
    out.append("MASLDBiomarkerQualifierWatch-Kor")
    out.append(_hr("="))
    out.append("")

    out.append("[1] TOP 15 Qualification 마일스톤 (점수순)")
    out.append(_hr("-"))
    for i, q in enumerate(top_quals[:digest_quals_n], 1):
        out.append(fmt_qualification_row(q, i))
        out.append("")

    out.append("[2] LITMUS / NIMBLE 컨소시엄 마일스톤 (전체)")
    out.append(_hr("-"))
    milestones_sorted = sorted(milestones, key=lambda m: m.date, reverse=True)
    for i, m in enumerate(milestones_sorted, 1):
        out.append(fmt_milestone_row(m, i))
        out.append("")

    out.append("[3] TOP 10 학회 / 컨소시엄 Abstract")
    out.append(_hr("-"))
    for i, a in enumerate(abstracts_sorted[:digest_abstracts_n], 1):
        out.append(fmt_abstract_row(a, i))
        out.append("")

    out.append("[4] TOP 5 한국 전략 Alert (KFDA / KASL / HIRA / Korean cohort)")
    out.append(_hr("-"))
    if korea_picks:
        for i, q in enumerate(korea_picks, 1):
            out.append(fmt_qualification_row(q, i))
            out.append("")
    else:
        out.append("  (해당 항목 없음)")
        out.append("")

    out.append("[5] TOP 5 MASLDStager Alignment 핀포인트")
    out.append(_hr("-"))
    out.append("  * NIT-based staging tool 데이터 layer 호환성 기준 (type/cou/status/tier)")
    out.append("")
    for i, q in enumerate(stager_picks, 1):
        out.append(
            f"{i:>2}. [{q.biomarker_id}] {q.name}  "
            f"(alignment={q.masld_stager_alignment}, total={q.score})"
        )
        out.append(
            f"     Type/CoU: {q.biomarker_type} / {q.context_of_use}  |  Status: {q.status}"
        )
        out.append(f"     Pathway : {q.pathway}  |  Tier: {q.tier_rank}")
        out.append("")

    out.append("[6] 주간 Phase 3 MASH Trial Biomarker 데이터 스냅샷")
    out.append(_hr("-"))
    for t in trials:
        out.append(fmt_trial(t))
        out.append("")

    out.append("[7] 디스클레이머")
    out.append(_hr("-"))
    out.append(fmt_disclaimer())
    out.append(_hr("="))
    return "\n".join(out)


# -----------------------------------------------------------------------------
# Dossier auto-draft (KFDA 동등성)
# -----------------------------------------------------------------------------


def render_dossier(biomarker_id: str, quals: list[Qualification], template: dict[str, Any]) -> str:
    target = next((q for q in quals if q.biomarker_id == biomarker_id), None)
    if target is None:
        return f"[오류] biomarker_id '{biomarker_id}' 를 찾을 수 없습니다."

    out: list[str] = []
    out.append(_hr("="))
    out.append(f"KFDA(MFDS) 동등성 평가 Dossier Auto-Draft  ::  {target.biomarker_id}")
    out.append(f"대상 바이오마커: {target.name}")
    out.append(_hr("="))
    out.append("")

    section_value_map = {
        "section_1_administrative": [
            f"신청자 정보: (작성 필요)",
            f"제품명: {target.name}",
            f"Context of Use (CoU): {target.context_of_use}",
            f"대응 해외 인허가: {target.pathway} / status={target.status}",
            f"동등성 신청 분류: (검토 필요 — biomarker_type={target.biomarker_type})",
            f"제출일자: (예정)",
        ],
        "section_2_intended_use": [
            f"Intended use (한): {target.indication} 를 위한 {target.context_of_use} 도구",
            f"Intended use (영): {target.context_of_use.title()} tool for {target.indication}",
            f"Target population: {target.population}",
            f"Disease setting: MASLD/MASH (적응증={target.indication})",
            f"Clinical decision context: {target.context_of_use}",
        ],
        "section_3_analytical_validation": [
            f"원 데이터 (해외): {target.analytical_validation}",
            f"한국 bridging 요건: 다기관 bridging study 권고 (최소 n>=100)",
            f"표준 정렬: IFCC / QIBA / ICH M10 호환 검토 필요",
            f"한국 시장 공급 계획: (작성 필요)",
        ],
        "section_4_clinical_validation": [
            f"원 데이터 (해외): {target.clinical_validation}",
            f"Reference standard: paired liver biopsy 또는 composite endpoint",
            f"Korean cohort: KASL-LITMUS-Korea / KoGES-MASLD 활용 권고",
            f"Subgroup analysis: 연령, 성별, BMI, T2D, PNPLA3 genotype",
            f"한국인 cutoff 재정의 필요성: {'재정의 권고' if target.biomarker_type in {'NIT', 'ECM'} else '검토 필요'}",
        ],
        "section_5_clinical_utility": [
            f"임상적 유용성: {target.clinical_utility}",
            f"Decision impact study: 한국 1차/2차/3차 의료 시나리오별 평가",
            f"HIRA 비용효과: 간생검 대비 비용 절감 가능성",
            f"MASLDStager alignment score: {target.masld_stager_alignment} (NIT-based staging tool 데이터 layer 호환)",
            f"Companion diagnostic 가능성: {'YES' if target.context_of_use == 'companion' else '비해당/검토'}",
        ],
        "section_6_korean_cohort_compatibility": [
            "PNPLA3 G allele frequency 한국 (~0.47) 반영",
            "TM6SF2 / HSD17B13 한국 reference 검토",
            "한국인 정상 reference range: 별도 산출 필요",
            "Multi-center reproducibility: 서울/부산/대구/광주 권고",
        ],
        "section_7_risk_management": [
            "False positive 임상 영향: 불필요한 hepatology 의뢰 증가",
            "False negative 임상 영향: 진행성 섬유화 누락",
            "Post-market surveillance: KASL registry 활용",
            "RWE 수집: HIRA claims linkage",
        ],
        "section_8_regulatory_alignment": [
            f"해외 dossier 인용: {target.pathway} / status={target.status}",
            "ICH M10 bioanalytical method validation 준수 여부 검토",
            "LITMUS / NIMBLE consortium data citation 권고",
            "AASLD / EASL / KASL 가이드라인 인용 여부 확인",
        ],
    }

    for key, body in template.items():
        out.append(body["header_kor"])
        out.append(_hr("-"))
        out.append("Template 필드:")
        for f in body["fields"]:
            out.append(f"  - {f}")
        out.append("")
        out.append("자동 채움 (mock data 기반, 실제 검증 필수):")
        for line in section_value_map.get(key, ["(작성 필요)"]):
            out.append(f"  > {line}")
        out.append("")

    out.append(_hr("="))
    out.append(fmt_disclaimer())
    out.append(_hr("="))
    return "\n".join(out)


# -----------------------------------------------------------------------------
# Trial / Stager / Pathway views
# -----------------------------------------------------------------------------


def render_trial_view(code: str, trials: list[Trial], quals: list[Qualification]) -> str:
    target = next((t for t in trials if t.trial_code.upper().startswith(code.upper())), None)
    if target is None:
        return f"[오류] trial '{code}' 를 찾을 수 없습니다."
    out = [_hr("="), f"Phase 3 MASH Trial Biomarker View :: {target.trial_code}", _hr("=")]
    out.append(fmt_trial(target))
    out.append("")
    out.append("연관 바이오마커 qualification 상태:")
    out.append(_hr("-"))
    by_id = {q.biomarker_id: q for q in quals}
    for bid in target.biomarkers_used:
        q = by_id.get(bid)
        if q is None:
            out.append(f"  - {bid}: (데이터 미보유)")
            continue
        out.append(
            f"  - [{q.biomarker_id}] {q.name}  ::  pathway={q.pathway}, status={q.status}, "
            f"score={q.score}"
        )
    out.append("")
    out.append(fmt_disclaimer())
    return "\n".join(out)


def render_stager_alignment(quals: list[Qualification], top: int) -> str:
    ranked = sorted(quals, key=lambda q: q.masld_stager_alignment, reverse=True)[:top]
    out = [
        _hr("="),
        f"MASLDStager Alignment Top {top} (NIT-based staging tool 데이터 layer 호환)",
        _hr("="),
        "기준: biomarker_type ∈ {NIT, IMAGING, ECM} +2.0 / "
        "CoU ∈ {staging, diagnosis, prognosis} +2.0 / "
        "status ∈ {qualified, harmonized, letter_of_support} +1.5 / tier_rank=1 +1.0",
        "",
    ]
    for i, q in enumerate(ranked, 1):
        out.append(
            f"{i:>2}. [{q.biomarker_id}] {q.name}  alignment={q.masld_stager_alignment}  "
            f"total={q.score}"
        )
        out.append(
            f"     {q.biomarker_type} / {q.context_of_use} / {q.pathway} / {q.status} / "
            f"tier={q.tier_rank}"
        )
    out.append("")
    out.append(fmt_disclaimer())
    return "\n".join(out)


# -----------------------------------------------------------------------------
# CLI
# -----------------------------------------------------------------------------


def build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(
        prog="masld-biomarker-qualifier-watch-kor",
        description=(
            "MASLD/MASH 바이오마커 multi-pathway qualification 모니터링 + "
            "한국어 weekly digest + KFDA 동등성 dossier auto-draft 보조 + "
            "MASLDStager alignment (mock data 기반, 연구·교육용)."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    p.add_argument(
        "--digest",
        action="store_true",
        help="한국어 weekly biomarker qualification digest 출력 (기본 동작)",
    )
    p.add_argument("--pathway", choices=PATHWAY_CHOICES, help="Qualification pathway 필터")
    p.add_argument(
        "--biomarker-type",
        dest="biomarker_type",
        choices=BIOMARKER_TYPES,
        help="바이오마커 카테고리 필터",
    )
    p.add_argument("--cou", choices=COU_CHOICES, help="Context of Use 필터")
    p.add_argument(
        "--trial",
        choices=TRIAL_CHOICES,
        help="Phase 3 MASH trial 별 biomarker 데이터 출력",
    )
    p.add_argument(
        "--dossier",
        metavar="BIOMARKER_ID",
        help="KFDA 동등성 평가 dossier auto-draft 출력 (예: BMK-001)",
    )
    p.add_argument(
        "--masld-stager-align",
        dest="masld_stager_align",
        action="store_true",
        help="MASLDStager alignment top picks 출력",
    )
    p.add_argument("--top", type=int, default=15, help="Top-N 항목 수 (기본 15)")
    p.add_argument("--summary", action="store_true", help="전체 데이터 요약 출력")
    return p


def main(argv: list[str] | None = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)

    try:
        quals = score_all(dedupe_qualifications(load_qualifications()))
        milestones = load_milestones()
        trials = load_trials()
        abstracts = load_abstracts()
    except Exception as exc:  # noqa: BLE001
        print(f"[로딩 오류] {exc}", file=sys.stderr)
        return 2

    # --summary
    if args.summary:
        print(fmt_summary(quals, milestones, trials, abstracts))
        return 0

    # --dossier
    if args.dossier:
        template = load_dossier_template()
        print(render_dossier(args.dossier, quals, template))
        return 0

    # --trial
    if args.trial:
        print(render_trial_view(args.trial, trials, quals))
        return 0

    # --masld-stager-align
    if args.masld_stager_align:
        print(render_stager_alignment(quals, args.top))
        return 0

    # Filters for pathway-specific list view
    pathway = args.pathway or "ALL"
    biomarker_type = args.biomarker_type or "ALL"
    cou = args.cou or "ALL"

    # 컨소시엄 (LITMUS/NIMBLE) 직접 필터 처리
    if pathway in {"LITMUS", "NIMBLE"}:
        target_ms = [m for m in milestones if m.consortium == pathway]
        out = [_hr("="), f"{pathway} 컨소시엄 마일스톤", _hr("=")]
        for i, m in enumerate(
            sorted(target_ms, key=lambda x: x.date, reverse=True), 1
        ):
            out.append(fmt_milestone_row(m, i))
            out.append("")
        out.append(fmt_disclaimer())
        print("\n".join(out))
        return 0

    filtered = filter_items(quals, pathway, biomarker_type, cou)

    # 명시적 필터가 있고 --digest 미지정인 경우: 필터 결과 리스트만 출력
    user_specified_filter = any(
        [args.pathway, args.biomarker_type, args.cou]
    )
    if user_specified_filter and not args.digest:
        filtered_sorted = sorted(filtered, key=lambda q: q.score, reverse=True)
        top_n = args.top if args.top > 0 else len(filtered_sorted)
        out = [
            _hr("="),
            f"필터 결과  ::  pathway={pathway}  type={biomarker_type}  cou={cou}",
            f"매칭 entry: {len(filtered_sorted)}  |  표시: top {min(top_n, len(filtered_sorted))}",
            _hr("="),
            "",
        ]
        for i, q in enumerate(filtered_sorted[:top_n], 1):
            out.append(fmt_qualification_row(q, i))
            out.append("")
        out.append(fmt_disclaimer())
        print("\n".join(out))
        return 0

    # 기본: digest
    print(build_weekly_digest(filtered, milestones, trials, abstracts, args.top))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
