"""
MASLDRetractionWatch-Kor — CLI entrypoint.

Usage:
    python3 main.py --help
    python3 main.py --summary
    python3 main.py --top 10
    python3 main.py --export-digest digest.md
    python3 main.py --guideline-check
    python3 main.py --cross-reference
"""
from __future__ import annotations

import argparse
import json
import sys
from typing import List


def _format_record_brief(r) -> str:
    return (
        f"[{r.get('retraction_date','')}] {r.get('type',''):<22} "
        f"{r.get('journal','')[:24]:<25} {(r.get('title','') or '')[:70]}"
    )


def cmd_summary(args, core_mod):
    records_all = core_mod.load_retractions()
    records = core_mod.filter_and_dedup(records_all)
    s = core_mod.overall_summary(records)
    print(core_mod.DISCLAIMER)
    print()
    print("=== MASLDRetractionWatch-Kor — Summary ===")
    print(f"총 record: {s['n_total']}  (raw {len(records_all)})")
    print()
    print("[by type]")
    for k, v in s["by_type"].items():
        print(f"  {k:<25} {v}")
    print()
    print("[by source]")
    for k, v in s["by_source"].items():
        print(f"  {k:<25} {v}")
    print()
    print("[top journals]")
    for k, v in s["top_journals"].items():
        print(f"  {k:<25} {v}")
    print()
    print("[top publishers]")
    for k, v in s["top_publishers"].items():
        print(f"  {k:<25} {v}")
    print()
    print("[pub→retraction lag (days)]")
    print(f"  n={s['lag']['n']} mean={s['lag']['mean']} median={s['lag']['median']} "
          f"min={s['lag']['min']} max={s['lag']['max']}")
    print()
    print("[yearly timeseries]")
    for y, c in s["timeseries"]:
        print(f"  {y}  {'#' * c} ({c})")


def cmd_top(args, core_mod):
    records = core_mod.filter_and_dedup(core_mod.load_retractions())
    n = max(1, int(args.top))
    print(core_mod.DISCLAIMER)
    print()
    print(f"=== Top {n} 최근 record ===")
    for r in core_mod.recent_records(records, top_n=n):
        print(_format_record_brief(r))


def cmd_export_digest(args, core_mod):
    records = core_mod.filter_and_dedup(core_mod.load_retractions())
    md = core_mod.weekly_digest_markdown(records, top_n=15)
    out = args.export_digest
    with open(out, "w", encoding="utf-8") as f:
        f.write(md)
    print(f"saved: {out}")


def cmd_guideline_check(args, core_mod):
    records = core_mod.filter_and_dedup(core_mod.load_retractions())
    guidelines = core_mod.load_guidelines()
    report = core_mod.guideline_sanity_report(guidelines, records)
    print(core_mod.DISCLAIMER)
    print()
    print("=== KASL/AASLD/EASL 가이드라인 sanity check ===")
    for g in report:
        print()
        print(f"[{g['society']}] {g['guideline']} ({g['year']})")
        print(f"  인용 {g['n_cited']} 중 영향 {g['n_affected']}건")
        for a in g["affected"]:
            print(f"    - {a['type']:<22} PMID {a['pmid']} {a['journal']} "
                  f"{a['retraction_date']} 사유:{a['reason']}")


def cmd_cross_reference(args, core_mod):
    records = core_mod.filter_and_dedup(core_mod.load_retractions())
    sr = core_mod.load_sample_systematic_review()
    result = core_mod.cross_reference_review(sr.get("included_papers", []), records)
    print(core_mod.DISCLAIMER)
    print()
    print(f"=== Systematic review cross-reference: {sr.get('title')} ===")
    print(f"Included {result['n_included']} | 영향 {result['n_affected']} "
          f"({(100.0 * result['n_affected'] / result['n_included']) if result['n_included'] else 0:.1f}%)")
    print("[severity]", result["severity_breakdown"])
    print()
    print("[affected]")
    for a in result["affected"]:
        rec = a["record"]
        print(f"  - {rec.get('type'):<22} PMID {a['included'].get('pmid')} "
              f"{rec.get('journal')} 사유:{rec.get('reason')}")
    print()
    print("[suggestions]")
    for s in result["suggestions"]:
        print(f"  - {s}")


def cmd_data_test(args, core_mod):
    """Smoke test: load all data files and report counts."""
    records = core_mod.load_retractions()
    sr = core_mod.load_sample_systematic_review()
    guidelines = core_mod.load_guidelines()
    masld = core_mod.filter_and_dedup(records)
    print(json.dumps({
        "records_loaded": len(records),
        "after_masld_filter": len(masld),
        "sample_sr_included": len(sr.get("included_papers", [])),
        "guidelines": len(guidelines),
    }, indent=2))


def build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(
        prog="masld-retraction-watch-kor",
        description=(
            "MASLD/MASH·NAFLD·NASH·hepatic fibrosis retraction surveillance CLI. "
            "오프라인 mock data, LLM 호출 없음."
        ),
    )
    p.add_argument("--summary", action="store_true",
                   help="전체 요약(type/source/journal/publisher/lag/yearly) 출력")
    p.add_argument("--top", type=int, default=0,
                   help="최근 N개 record 출력 (기본 0=미사용)")
    p.add_argument("--export-digest", type=str, default="",
                   help="주간 다이제스트를 Markdown 파일로 저장")
    p.add_argument("--guideline-check", action="store_true",
                   help="KASL/AASLD/EASL 가이드라인 인용 retraction sanity")
    p.add_argument("--cross-reference", action="store_true",
                   help="샘플 systematic review included paper cross-reference")
    p.add_argument("--data-test", action="store_true",
                   help="mock data 파일 로드 smoke test (JSON 출력)")
    return p


def main(argv=None):
    parser = build_parser()
    args = parser.parse_args(argv)

    # lazy import so --help works even if downstream deps are missing
    import core as core_mod  # noqa

    did_anything = False
    if args.summary:
        cmd_summary(args, core_mod); did_anything = True
    if args.top and args.top > 0:
        cmd_top(args, core_mod); did_anything = True
    if args.export_digest:
        cmd_export_digest(args, core_mod); did_anything = True
    if args.guideline_check:
        cmd_guideline_check(args, core_mod); did_anything = True
    if args.cross_reference:
        cmd_cross_reference(args, core_mod); did_anything = True
    if args.data_test:
        cmd_data_test(args, core_mod); did_anything = True

    if not did_anything:
        parser.print_help()
        print()
        print(core_mod.DISCLAIMER)


if __name__ == "__main__":
    main(sys.argv[1:])
