Spaces:
Running

File size: 39,123 Bytes
54a73d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
821e72a
 
 
 
 
54a73d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58dccf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54a73d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58dccf2
54a73d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58dccf2
 
 
 
 
 
 
54a73d4
58dccf2
54a73d4
 
 
 
58dccf2
 
54a73d4
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
# report_builder.py
# -*- coding: utf-8 -*-
"""
파이프라인 결과(Stage 2/3 CSV + 그림)를 읽어 '간단한 분석 보고서'(HTML)를 만듭니다.

  build_report(results_dir, lang, region_map, endemic_countries)
      -> dict(html=화면용 조각, html_page=다운로드용 완성 HTML, md=Markdown 요약,
              zip_path=보고서+CSV+그림 ZIP 경로, message=상태)

- 모든 문장은 결과 표에서 규칙 기반으로 만듭니다(고정된 템플릿 + 계산한 숫자).
- ko / en / th / id 4개 언어를 지원합니다. 국가·권역 이름은 결과 파일 그대로 영어로 둡니다.
- 외부 리소스(폰트·CDN)를 쓰지 않는 단일 HTML 이라 내려받아 바로 열 수 있고,
  브라우저에서 '인쇄 → PDF로 저장'으로 PDF 도 만들 수 있습니다.
"""
from __future__ import annotations

import base64
import datetime as _dt
import glob
import html as _html
import os
import re
import zipfile
from pathlib import Path

import pandas as pd

# ─────────────────────────────────────────────────────────────────────────────
# 문구 (ko / en / th / id)
# ─────────────────────────────────────────────────────────────────────────────
_TXT = {
    "ko": dict(
        sum_mixed="입력 서열에 **서로 다른 혈청형({lst})**이 섞여 있습니다. 설정한 혈청형({sel}) 모델로 모두 비교되므로, 다른 혈청형 서열은 결과가 의미 없을 수 있습니다. 혈청형별로 나누어 분석하세요.",
        title="DenAIGeo 분석 보고서", sub="DENV 서열 지리적 유입원 예측 결과 요약",
        made="생성 시각", gene="비교 대상 gene", sero="혈청형",
        h_over="1. 분석 개요", h_s2="2. Stage 2 — 서열별 유사 국가", h_s3="3. Stage 3 — 유입원 요약",
        h_per="4. 검출 국가별 해석", h_fig="5. 그림", h_note="6. 읽을 때 유의할 점", h_files="7. 포함된 파일",
        k_seq="분석 서열 수", k_ctry="검출 국가 수", k_med="Top-1 유사도 중앙값", k_low="유사도 90% 미만 서열",
        s2_cap="검출 국가별 가장 유사한 참조 국가 (Top-1, 상위 3)", s2_c1="검출 국가", s2_c2="서열 수", s2_c3="Top-1 국가 분포", s2_c4="유사도 중앙값",
        s3_reg="유입원 권역 비중", s3_cty="유입원 국가 Top-10", s3_ei="자국 유래 vs 타국 유입",
        e_self="자국 유래", e_imp="타국 유입",
        p_c1="검출 국가", p_c2="구분", p_c3="서열 수", p_c4="유입원 권역", p_c5="유사 국가 Top-5", p_c6="해석",
        endemic="엔데믹 목록", nonendemic="비엔데믹",
        fig_note="Stage 3 그림과 2D·Top-3 그림이 생성되어 있으면 아래에 함께 표시됩니다.",
        no_fig="표시할 그림이 아직 없습니다. Stage 3, 2D 시각화, 예측 차트를 먼저 실행하세요.",
        # 요약 문장
        sum_main="전체 유입원은 **{r1} {p1}%**{r2txt}이며, 국가로는 **{c1}({q1}%)**{c2txt}가 가장 큽니다.",
        sum_r2=", 그다음 {r2} {p2}%", sum_c2=", {c2}({q2}%)",
        sum_imp="서열 수 기준 가중 평균으로 **타국 유입 비중은 약 {imp}%**, 자국 유래는 약 {slf}%입니다.",
        sum_low="Top-1 유사도가 90% 미만인 서열이 **{n}개**({pct}%) 있어, 이들은 가까운 계통이 참조에 없을 수 있으므로 보수적으로 해석하세요.",
        sum_cross="검출 국가가 속한 권역과 **유입원 1순위 권역이 다른 국가**: {lst}",
        sum_none_cross="검출 국가 대부분은 같은 권역 안에서 유입원이 확인되었습니다.",
        # 국가별 문장
        c_main="유입원은 **{r1} {p1}%**{r2txt}이며 유사 국가는 {top}입니다.",
        c_few="서열이 {n}개뿐이라 후보 비중이 비슷하게 나올 수 있어 **참고용**입니다.",
        c_self="자국 계통과 가까워 **자국 유래가 약 {x}%**입니다.",
        c_non="엔데믹 목록에 없는 국가로, **어느 권역 계통과 닮았는지**가 핵심 정보입니다.",
        c_low="Top-1 유사도 중앙값이 {m}%로 낮아 **신뢰가 낮습니다**.",
        c_cross="검출 권역({dr})과 다른 권역({r1})이 1순위입니다.",
        notes=["결과는 **참조 데이터베이스에 포함된 국가·도시**를 기준으로 한 **서열 유사도 추정**이며, 확정적인 유입 경로를 뜻하지 않습니다.",
               "서열 수가 적은 국가의 비율, 유사도가 낮은 서열은 해석에 주의하세요.",
               "gene(C/prM, E 등)이나 샘플 구성에 따라 결과가 달라질 수 있습니다.",
               "후보 비중이 거의 같으면(예: 5곳 약 20%씩) 사실상 동률이므로 Top-1만 단정하지 마세요.",
               "여행력·접촉력 등 역학 정보와 함께 **보조 근거**로 활용하세요."],
        files_zip="ZIP에는 이 보고서(HTML), 결과 CSV, 그림(PNG)이 들어 있습니다.",
        none="결과 파일을 찾지 못했습니다. Stage 2와 Stage 3를 먼저 실행하세요.",
        status_ok="✅ 보고서를 만들었습니다 ({n}개 파일 포함).",
        print_hint="PDF가 필요하면 내려받은 HTML을 브라우저에서 열어 '인쇄 → PDF로 저장'을 선택하세요.",
    ),
    "en": dict(
        sum_mixed="The input mixes **different serotypes ({lst})**. All were compared against the selected serotype ({sel}) model, so results for the other serotypes may be meaningless. Analyze each serotype separately.",
        title="DenAIGeo Analysis Report", sub="Summary of DENV geographic origin prediction",
        made="Generated", gene="Gene compared", sero="Serotype",
        h_over="1. Overview", h_s2="2. Stage 2 — Most similar country per sequence", h_s3="3. Stage 3 — Source summary",
        h_per="4. Interpretation by detection country", h_fig="5. Figures", h_note="6. Points to keep in mind", h_files="7. Included files",
        k_seq="Sequences analyzed", k_ctry="Detection countries", k_med="Median Top-1 similarity", k_low="Sequences below 90%",
        s2_cap="Most similar reference country by detection country (Top-1, top 3)", s2_c1="Detection country", s2_c2="Sequences", s2_c3="Top-1 country distribution", s2_c4="Median similarity",
        s3_reg="Source region share", s3_cty="Top-10 source countries", s3_ei="Endemic vs imported",
        e_self="Endemic", e_imp="Imported",
        p_c1="Detection country", p_c2="Type", p_c3="Seqs", p_c4="Source regions", p_c5="Top-5 similar countries", p_c6="Interpretation",
        endemic="endemic list", nonendemic="non-endemic",
        fig_note="Stage 3 figures and the 2D / Top-3 figures are shown below if they have been generated.",
        no_fig="No figures yet. Run Stage 3, the 2D visualization and the prediction chart first.",
        sum_main="Overall, the main source is **{r1} {p1}%**{r2txt}, and by country the largest is **{c1} ({q1}%)**{c2txt}.",
        sum_r2=", then {r2} {p2}%", sum_c2=", followed by {c2} ({q2}%)",
        sum_imp="Weighted by sequence count, the **imported share is about {imp}%** and the endemic share about {slf}%.",
        sum_low="**{n} sequences ({pct}%)** have Top-1 similarity below 90%; the reference may lack a close lineage, so interpret them conservatively.",
        sum_cross="Countries whose **top source region differs from their own region**: {lst}",
        sum_none_cross="For most detection countries, the main source is within the same region.",
        c_main="Main source: **{r1} {p1}%**{r2txt}; similar countries: {top}.",
        c_few="Only {n} sequence(s), so candidate shares may be near-equal — **for reference only**.",
        c_self="Close to its own lineage, with an **endemic share of about {x}%**.",
        c_non="Not on the endemic list, so **which regional lineage it resembles** is the key information.",
        c_low="Median Top-1 similarity is only {m}% — **low confidence**.",
        c_cross="The top source region ({r1}) differs from the detection region ({dr}).",
        notes=["Results are **sequence-similarity estimates** based on the **countries and cities in the reference database** and do not establish a definitive route.",
               "Be careful with proportions for countries with few sequences and with low-similarity sequences.",
               "Results can differ by gene (C/prM, E, etc.) and by sample composition.",
               "When candidate shares are nearly equal (e.g. 5 places at about 20%), they are effectively tied; do not rely on Top-1 alone.",
               "Use as **supporting evidence** together with epidemiological information (travel and contact history)."],
        files_zip="The ZIP contains this report (HTML), the result CSVs and the figures (PNG).",
        none="No result files found. Run Stage 2 and Stage 3 first.",
        status_ok="✅ Report created ({n} files included).",
        print_hint="For a PDF, open the downloaded HTML in a browser and choose Print → Save as PDF.",
    ),
    "th": dict(
        sum_mixed="ข้อมูลนำเข้ามี**ซีโรไทป์ต่างกันปะปน ({lst})** ทุกลำดับถูกเปรียบเทียบกับโมเดลของซีโรไทป์ที่เลือก ({sel}) ผลของซีโรไทป์อื่นอาจไม่มีความหมาย ควรวิเคราะห์แยกตามซีโรไทป์",
        title="รายงานการวิเคราะห์ DenAIGeo", sub="สรุปผลการทำนายแหล่งที่มาทางภูมิศาสตร์ของ DENV",
        made="สร้างเมื่อ", gene="ยีนที่เปรียบเทียบ", sero="ซีโรไทป์",
        h_over="1. ภาพรวม", h_s2="2. Stage 2 — ประเทศที่คล้ายที่สุดของแต่ละลำดับ", h_s3="3. Stage 3 — สรุปแหล่งที่มา",
        h_per="4. การตีความรายประเทศที่ตรวจพบ", h_fig="5. ภาพ", h_note="6. ข้อควรระวัง", h_files="7. ไฟล์ที่รวมอยู่",
        k_seq="จำนวนลำดับที่วิเคราะห์", k_ctry="จำนวนประเทศที่ตรวจพบ", k_med="มัธยฐานความคล้ายคลึง Top-1", k_low="ลำดับที่ต่ำกว่า 90%",
        s2_cap="ประเทศอ้างอิงที่คล้ายที่สุดตามประเทศที่ตรวจพบ (Top-1, 3 อันดับแรก)", s2_c1="ประเทศที่ตรวจพบ", s2_c2="จำนวนลำดับ", s2_c3="การกระจาย Top-1", s2_c4="มัธยฐานความคล้ายคลึง",
        s3_reg="สัดส่วนภูมิภาคต้นทาง", s3_cty="ประเทศต้นทาง 10 อันดับแรก", s3_ei="ภายในประเทศ vs นำเข้า",
        e_self="ภายในประเทศ", e_imp="นำเข้า",
        p_c1="ประเทศที่ตรวจพบ", p_c2="ประเภท", p_c3="ลำดับ", p_c4="ภูมิภาคต้นทาง", p_c5="ประเทศที่คล้าย Top-5", p_c6="การตีความ",
        endemic="รายการเอนเดมิก", nonendemic="ไม่ใช่เอนเดมิก",
        fig_note="หากสร้างภาพ Stage 3 และภาพ 2D / Top-3 แล้ว จะแสดงด้านล่าง",
        no_fig="ยังไม่มีภาพ โปรดรัน Stage 3, การแสดงผล 2D และกราฟการทำนายก่อน",
        sum_main="โดยรวมต้นทางหลักคือ **{r1} {p1}%**{r2txt} และระดับประเทศ **{c1} ({q1}%)**{c2txt} มากที่สุด",
        sum_r2=" รองลงมา {r2} {p2}%", sum_c2=" ตามด้วย {c2} ({q2}%)",
        sum_imp="เมื่อถ่วงน้ำหนักตามจำนวนลำดับ **สัดส่วนนำเข้าประมาณ {imp}%** และภายในประเทศประมาณ {slf}%",
        sum_low="มี **{n} ลำดับ ({pct}%)** ที่ความคล้ายคลึง Top-1 ต่ำกว่า 90% อาจไม่มีสายพันธุ์ใกล้เคียงในข้อมูลอ้างอิง จึงควรตีความอย่างระมัดระวัง",
        sum_cross="ประเทศที่ **ภูมิภาคต้นทางอันดับ 1 ต่างจากภูมิภาคของตนเอง**: {lst}",
        sum_none_cross="ประเทศที่ตรวจพบส่วนใหญ่มีต้นทางหลักอยู่ในภูมิภาคเดียวกัน",
        c_main="ต้นทางหลัก: **{r1} {p1}%**{r2txt} ประเทศที่คล้าย: {top}",
        c_few="มีเพียง {n} ลำดับ สัดส่วนผู้สมัครจึงอาจใกล้เคียงกัน — **ใช้อ้างอิงเท่านั้น**",
        c_self="ใกล้สายพันธุ์ของประเทศตนเอง **สัดส่วนภายในประเทศประมาณ {x}%**",
        c_non="ไม่อยู่ในรายการเอนเดมิก ดังนั้นข้อมูลสำคัญคือ **คล้ายสายพันธุ์ของภูมิภาคใด**",
        c_low="มัธยฐานความคล้ายคลึง Top-1 เพียง {m}% — **ความเชื่อถือต่ำ**",
        c_cross="ภูมิภาคต้นทางอันดับ 1 ({r1}) ต่างจากภูมิภาคที่ตรวจพบ ({dr})",
        notes=["ผลลัพธ์เป็น**การประมาณความคล้ายคลึงของลำดับ**โดยอ้างอิง**ประเทศและเมืองในฐานข้อมูลอ้างอิง** ไม่ใช่การยืนยันเส้นทางที่แน่นอน",
               "ควรระวังสัดส่วนของประเทศที่มีลำดับน้อยและลำดับที่ความคล้ายคลึงต่ำ",
               "ผลอาจต่างกันตามยีน (C/prM, E ฯลฯ) และองค์ประกอบตัวอย่าง",
               "หากสัดส่วนผู้สมัครเกือบเท่ากัน (เช่น 5 แห่งแห่งละประมาณ 20%) ถือว่าเสมอกัน อย่าสรุปจาก Top-1 อย่างเดียว",
               "ใช้เป็น**หลักฐานสนับสนุน**ร่วมกับข้อมูลทางระบาดวิทยา (ประวัติการเดินทางและการสัมผัส)"],
        files_zip="ZIP ประกอบด้วยรายงานนี้ (HTML) ไฟล์ CSV ผลลัพธ์ และภาพ (PNG)",
        none="ไม่พบไฟล์ผลลัพธ์ โปรดรัน Stage 2 และ Stage 3 ก่อน",
        status_ok="✅ สร้างรายงานแล้ว (รวม {n} ไฟล์)",
        print_hint="หากต้องการ PDF ให้เปิด HTML ที่ดาวน์โหลดในเบราว์เซอร์ แล้วเลือกพิมพ์ → บันทึกเป็น PDF",
    ),
    "id": dict(
        sum_mixed="Input mencampur **serotipe berbeda ({lst})**. Semua dibandingkan dengan model serotipe terpilih ({sel}), sehingga hasil serotipe lain mungkin tidak bermakna. Analisis setiap serotipe secara terpisah.",
        title="Laporan Analisis DenAIGeo", sub="Ringkasan prediksi asal geografis DENV",
        made="Dibuat", gene="Gen yang dibandingkan", sero="Serotipe",
        h_over="1. Gambaran umum", h_s2="2. Stage 2 — Negara paling mirip per sekuens", h_s3="3. Stage 3 — Ringkasan asal",
        h_per="4. Interpretasi per negara deteksi", h_fig="5. Gambar", h_note="6. Hal yang perlu diperhatikan", h_files="7. File yang disertakan",
        k_seq="Sekuens dianalisis", k_ctry="Negara deteksi", k_med="Median kemiripan Top-1", k_low="Sekuens di bawah 90%",
        s2_cap="Negara referensi paling mirip menurut negara deteksi (Top-1, 3 teratas)", s2_c1="Negara deteksi", s2_c2="Jumlah sekuens", s2_c3="Distribusi Top-1", s2_c4="Median kemiripan",
        s3_reg="Proporsi wilayah asal", s3_cty="10 negara asal teratas", s3_ei="Endemik vs impor",
        e_self="Endemik", e_imp="Impor",
        p_c1="Negara deteksi", p_c2="Tipe", p_c3="Sekuens", p_c4="Wilayah asal", p_c5="Top-5 negara mirip", p_c6="Interpretasi",
        endemic="daftar endemik", nonendemic="non-endemik",
        fig_note="Gambar Stage 3 serta gambar 2D / Top-3 ditampilkan di bawah bila sudah dibuat.",
        no_fig="Belum ada gambar. Jalankan Stage 3, visualisasi 2D, dan grafik prediksi terlebih dahulu.",
        sum_main="Secara keseluruhan, asal utama adalah **{r1} {p1}%**{r2txt}, dan menurut negara yang terbesar adalah **{c1} ({q1}%)**{c2txt}.",
        sum_r2=", lalu {r2} {p2}%", sum_c2=", diikuti {c2} ({q2}%)",
        sum_imp="Dibobot menurut jumlah sekuens, **proporsi impor sekitar {imp}%** dan endemik sekitar {slf}%.",
        sum_low="**{n} sekuens ({pct}%)** memiliki kemiripan Top-1 di bawah 90%; referensi mungkin tidak memiliki garis keturunan yang dekat, sehingga interpretasikan dengan hati-hati.",
        sum_cross="Negara yang **wilayah asal teratasnya berbeda dari wilayahnya sendiri**: {lst}",
        sum_none_cross="Pada sebagian besar negara deteksi, asal utama berada di wilayah yang sama.",
        c_main="Asal utama: **{r1} {p1}%**{r2txt}; negara mirip: {top}.",
        c_few="Hanya {n} sekuens, sehingga proporsi kandidat bisa hampir sama — **hanya sebagai referensi**.",
        c_self="Dekat dengan garis keturunan negara sendiri, dengan **porsi endemik sekitar {x}%**.",
        c_non="Tidak ada dalam daftar endemik, sehingga **garis keturunan wilayah mana yang mirip** adalah informasi kuncinya.",
        c_low="Median kemiripan Top-1 hanya {m}% — **keandalan rendah**.",
        c_cross="Wilayah asal teratas ({r1}) berbeda dari wilayah deteksi ({dr}).",
        notes=["Hasil adalah **estimasi kemiripan sekuens** berdasarkan **negara dan kota dalam basis data referensi** dan tidak menetapkan jalur secara pasti.",
               "Berhati-hatilah pada proporsi negara dengan sedikit sekuens dan sekuens berkemiripan rendah.",
               "Hasil dapat berbeda menurut gen (C/prM, E, dll.) dan komposisi sampel.",
               "Bila proporsi kandidat hampir sama (mis. 5 tempat sekitar 20%), kandidat praktis seri; jangan mengandalkan Top-1 saja.",
               "Gunakan sebagai **bukti pendukung** bersama informasi epidemiologi (riwayat perjalanan dan kontak)."],
        files_zip="ZIP berisi laporan ini (HTML), CSV hasil, dan gambar (PNG).",
        none="File hasil tidak ditemukan. Jalankan Stage 2 dan Stage 3 terlebih dahulu.",
        status_ok="✅ Laporan dibuat ({n} file disertakan).",
        print_hint="Untuk PDF, buka HTML yang diunduh di browser lalu pilih Cetak → Simpan sebagai PDF.",
    ),
}

_CSS = """
.rp{font-family:'Inter','Noto Sans KR','Noto Sans Thai','Segoe UI',Arial,sans-serif;color:#14213d;line-height:1.65;font-size:15px}
.rp *{box-sizing:border-box}
.rp h1{font-size:26px;color:#153b66;margin:0 0 2px}
.rp .rp-sub{color:#64748b;margin:0 0 4px}
.rp .rp-meta{color:#64748b;font-size:13px;margin-bottom:14px}
.rp h2{font-size:18px;color:#153b66;border-bottom:2px solid #dbe4ef;padding-bottom:4px;margin:26px 0 10px}
.rp .rp-kpis{display:flex;flex-wrap:wrap;gap:10px;margin:10px 0}
.rp .rp-kpi{flex:1 1 150px;background:#f4f7fb;border:1px solid #dbe4ef;border-radius:12px;padding:10px 14px}
.rp .rp-kpi b{display:block;font-size:22px;color:#2563eb}
.rp .rp-kpi span{font-size:12.5px;color:#64748b}
.rp ul{padding-left:20px;margin:6px 0}
.rp table{border-collapse:collapse!important;width:100%;font-size:13.5px;margin:8px 0;border:1px solid #dbe4ef!important;background:#fff!important}
.rp table th{background:#153b66!important;color:#ffffff!important;text-align:left;padding:8px 10px!important;border:1px solid #153b66!important;font-weight:600!important;white-space:nowrap}
.rp table td{color:#14213d!important;background:#fff!important;border:0!important;border-bottom:1px solid #dbe4ef!important;padding:7px 10px!important;vertical-align:top}
.rp table tr:nth-child(even) td{background:#f4f7fb!important}
.rp table th *, .rp table th b{color:#ffffff!important}
.rp .rp-bar{display:flex;height:16px;border-radius:5px;overflow:hidden;background:#e8eef6;min-width:140px}
.rp .rp-bar i{display:block;height:100%}
.rp .rp-row{display:flex;align-items:center;gap:8px;margin:3px 0;font-size:13.5px}
.rp .rp-row .n{width:150px;flex:none;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.rp .rp-row .b{flex:1;background:#e8eef6;border-radius:5px;height:14px}
.rp .rp-row .b i{display:block;height:100%;border-radius:5px;background:#2563eb}
.rp .rp-row .v{width:56px;text-align:right;color:#64748b}
.rp .rp-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:16px}
.rp .rp-card{border:1px solid #dbe4ef;border-radius:12px;padding:12px 14px;background:#fff}
.rp .rp-card h3{font-size:14.5px;margin:0 0 6px;color:#153b66}
.rp .tag{display:inline-block;white-space:nowrap;font-size:11.5px;border-radius:99px;padding:1px 8px;border:1px solid #dbe4ef;color:#33475f;background:#f4f7fb}
.rp .tag.non{background:#fff7ed;border-color:#fed7aa;color:#c2410c}
.rp .lg{display:flex;flex-wrap:wrap;gap:4px 12px;font-size:12px;color:#33475f;margin-top:6px}
.rp .lg span::before{content:"";display:inline-block;width:10px;height:10px;border-radius:2px;margin-right:4px;background:var(--c)}
.rp figure{margin:10px 0}
.rp figure img{max-width:min(100%,900px);border:1px solid #dbe4ef;border-radius:10px}
.rp figcaption{font-size:12.5px;color:#64748b}
.rp .rp-box{background:#eff6ff;border:1px solid #bfdbfe;border-radius:12px;padding:10px 14px}
@media print{.rp h2{break-after:avoid}.rp figure,.rp .rp-card,.rp tr{break-inside:avoid}}
"""

_RC = {"South America": "#2563eb", "Europe": "#7c3aed", "North America": "#0f766e", "Africa": "#c2410c",
       "South Asia": "#d97706", "Southeast Asia": "#db2777", "East Asia": "#0891b2", "Oceania": "#65a30d",
       "Middle East": "#94a3b8"}


def _md(s: str) -> str:
    """**굵게** 만 HTML 로 바꾸고 나머지는 이스케이프."""
    s = _html.escape(s)
    return re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", s)


def _newest(files):
    files = [f for f in files if os.path.isfile(f)]
    return max(files, key=os.path.getmtime) if files else None


def _find(results_dir: Path, pattern: str, sub: str = "", suffix: str | None = None):
    base = glob.escape(str(results_dir / sub)) if sub else glob.escape(str(results_dir))
    files = glob.glob(os.path.join(base, pattern))
    if suffix:
        sel = [f for f in files if f.endswith(suffix)]
        files = sel or files
    return _newest(files)


_GENE_TAGS = ("C-prM", "E", "Polyprotein")


def _file_gene_tag(name: str):
    """파일명에 들어 있는 유전자 태그(C-prM / E / Polyprotein)를 돌려줍니다. 없으면 None."""
    stem = re.sub(r"\.[A-Za-z0-9]+$", "", os.path.basename(name))
    toks = re.split(r"[_.]", stem)
    for g in _GENE_TAGS:
        if g in toks:
            return g
    return None


def purge_other_gene_results(results_dir, keep_gene):
    """결과 폴더(하위 폴더 포함)에서 keep_gene 이 아닌 다른 유전자의 결과 파일을 삭제합니다. 삭제한 파일 수 반환."""
    keep = str(keep_gene).replace("/", "-")
    results_dir = Path(results_dir)
    if not results_dir.exists() or keep not in _GENE_TAGS:
        return 0
    n = 0
    for f in list(results_dir.rglob("*")):
        if not f.is_file() or "_download" in f.parts:
            continue
        g = _file_gene_tag(f.name)
        if g and g != keep:
            try:
                f.unlink(); n += 1
            except Exception:
                pass
    return n


def _safe_part(x: str) -> str:
    return re.sub(r"[^0-9A-Za-z._-]+", "-", str(x)).strip("-._") or "x"


def _pct(x, nd=1):
    try:
        return f"{float(x):.{nd}f}"
    except Exception:
        return str(x)


def _bar_row(name, value, vmax, color="#2563eb", unit="%"):
    w = 0 if vmax <= 0 else max(1.0, 100.0 * float(value) / vmax)
    return (f'<div class="rp-row"><div class="n" title="{_html.escape(str(name))}">{_html.escape(str(name))}</div>'
            f'<div class="b"><i style="width:{w:.1f}%;background:{color}"></i></div>'
            f'<div class="v">{_pct(value)}{unit}</div></div>')


def _stack_bar(items):
    """items: [(label, pct)] -> 누적 막대 + 범례"""
    segs = "".join(
        f'<i style="width:{max(float(p), 0):.2f}%;background:{_RC.get(l, "#94a3b8")}" title="{_html.escape(l)} {_pct(p)}%"></i>'
        for l, p in items if float(p) > 0)
    lg = "".join(f'<span style="--c:{_RC.get(l, "#94a3b8")}">{_html.escape(l)} {_pct(p, 0)}%</span>' for l, p in items if float(p) >= 3)
    return f'<div class="rp-bar">{segs}</div><div class="lg">{lg}</div>'


def _img_b64(path: str, max_kb: int = 1500):
    try:
        data = open(path, "rb").read()
        mime = "image/png" if path.lower().endswith(".png") else "image/jpeg"
        return f"data:{mime};base64," + base64.b64encode(data).decode()
    except Exception:
        return None


def build_report(results_dir, lang="ko", region_map=None, endemic_countries=None,
                 gene_label="", serotype_label="", out_dir=None, prefer_tag="", input_name=""):
    L = _TXT.get(lang, _TXT["en"])
    results_dir = Path(results_dir)
    region_map = region_map or {}
    endemic_countries = set(endemic_countries or [])

    r1p = _find(results_dir, "[[]r1[]]unknown_top5*.csv", "", f"_{prefer_tag}.csv" if prefer_tag else None)
    if not r1p:
        return dict(html="", html_page="", md="", zip_path=None, message="⚠️ " + L["none"])
    tag = re.sub(r"\.csv$", "", os.path.basename(r1p)).split("_")[-1]  # 예: E, C-prM
    gene = gene_label or tag.replace("-", "/")

    o = "01_output"
    pc_reg = _find(results_dir, "per_country_source_region_*.csv", o, f"_{tag}.csv")
    pc_cty = _find(results_dir, "per_country_source_country_*.csv", o, f"_{tag}.csv")
    ov_reg = _find(results_dir, "overall_source_region_*.csv", o, f"_{tag}.csv")
    ov_cty = _find(results_dir, "overall_source_country_*.csv", o, f"_{tag}.csv")
    endm = _find(results_dir, "endemic_vs_imported_*.csv", o, f"_{tag}.csv")
    if not (ov_reg and ov_cty and pc_reg and pc_cty):
        return dict(html="", html_page="", md="", zip_path=None, message="⚠️ " + L["none"])

    r1 = pd.read_csv(r1p)
    def found(sid):
        for t in reversed(str(sid).split("_")):
            if t in region_map:
                return t
        return str(sid).split("_")[-1]
    r1["found"] = r1["unknown_seq_id"].map(found)
    ovr, ovc = pd.read_csv(ov_reg), pd.read_csv(ov_cty)
    pcr, pcc = pd.read_csv(pc_reg), pd.read_csv(pc_cty)
    ei = pd.read_csv(endm) if endm else pd.DataFrame(columns=["found_country", "n_unknown_seq", "self_share_pct", "imported_share_pct"])

    n_seq = len(r1)
    sero_found = sorted({m.group(1) for m in (re.search(r"DENV-?(\d)", str(x), re.I) for x in r1["unknown_seq_id"]) if m})
    if len(sero_found) == 1:
        serotype_label = "DENV" + sero_found[0]     # 서열 ID 에서 읽은 값이 설정값보다 우선
    med = float(r1["top1_similarity_percent"].median())
    low = int((r1["top1_similarity_percent"] < 90).sum())
    ctry_counts = r1["found"].value_counts()
    n_ctry = len(ctry_counts)

    # ── 요약 문장 ───────────────────────────────────────────────────────────
    r_1, r_2 = ovr.iloc[0], (ovr.iloc[1] if len(ovr) > 1 else None)
    c_1, c_2 = ovc.iloc[0], (ovc.iloc[1] if len(ovc) > 1 else None)
    s_main = L["sum_main"].format(
        r1=r_1["source_region"], p1=_pct(r_1["share_%"]),
        r2txt=(L["sum_r2"].format(r2=r_2["source_region"], p2=_pct(r_2["share_%"])) if r_2 is not None else ""),
        c1=c_1["source_country"], q1=_pct(c_1["share_%"]),
        c2txt=(L["sum_c2"].format(c2=c_2["source_country"], q2=_pct(c_2["share_%"])) if c_2 is not None else ""))
    bullets = [s_main]
    if len(ei):
        w = ei["n_unknown_seq"].astype(float)
        imp = float((ei["imported_share_pct"] * w).sum() / w.sum()) if w.sum() else 0
        bullets.append(L["sum_imp"].format(imp=_pct(imp, 0), slf=_pct(100 - imp, 0)))
    if len(sero_found) > 1:
        bullets.append(L["sum_mixed"].format(lst=", ".join("DENV" + x for x in sero_found), sel=serotype_label or "?"))
    if low:
        bullets.append(L["sum_low"].format(n=low, pct=_pct(100 * low / n_seq, 0)))

    # 국가별 상위 권역/국가
    top_reg = {c: g.sort_values("weight", ascending=False) if "weight" in g else g
               for c, g in pcr.groupby("found_country")}
    top_cty = {c: g.sort_values("weight", ascending=False) for c, g in pcc.groupby("found_country")}
    med_by = r1.groupby("found")["top1_similarity_percent"].median().to_dict()
    ei_by = ei.set_index("found_country").to_dict("index") if len(ei) else {}

    cross = []
    for c in ctry_counts.index:
        g = top_reg.get(c)
        if g is None or g.empty:
            continue
        dr = region_map.get(c)
        if dr and g.iloc[0]["source_region"] != dr:
            cross.append(f"{c} → {g.iloc[0]['source_region']}")
    bullets.append(L["sum_cross"].format(lst=", ".join(cross[:10])) if cross else L["sum_none_cross"])

    # ── Stage 2 표 ──────────────────────────────────────────────────────────
    rows2 = []
    for c, n in ctry_counts.items():
        sub = r1[r1["found"] == c]
        dist = sub["top1_country"].value_counts().head(3)
        txt = ", ".join(f"{k} ({v})" for k, v in dist.items())
        rows2.append(f"<tr><td>{_html.escape(c)}</td><td>{n}</td><td>{_html.escape(txt)}</td><td>{_pct(med_by.get(c, 0))}%</td></tr>")

    # ── Stage 3 요약 ────────────────────────────────────────────────────────
    vm = float(ovr["share_%"].max())
    reg_html = "".join(_bar_row(r["source_region"], r["share_%"], vm, _RC.get(r["source_region"], "#2563eb")) for _, r in ovr.iterrows())
    vc = float(ovc["share_%"].head(10).max())
    cty_html = "".join(_bar_row(r["source_country"], r["share_%"], vc) for _, r in ovc.head(10).iterrows())
    ei_html = ""
    for c in ctry_counts.index[:12]:
        d = ei_by.get(c)
        if not d:
            continue
        ei_html += (f'<div class="rp-row"><div class="n">{_html.escape(c)} ({int(d["n_unknown_seq"])})</div>'
                    f'<div class="b" style="display:flex"><i style="width:{d["self_share_pct"]:.1f}%;background:#c2410c"></i>'
                    f'<i style="width:{d["imported_share_pct"]:.1f}%;background:#2563eb"></i></div>'
                    f'<div class="v">{_pct(d["self_share_pct"], 0)}/{_pct(d["imported_share_pct"], 0)}</div></div>')

    # ── 국가별 해석 ─────────────────────────────────────────────────────────
    per_rows = []
    for c, n in ctry_counts.items():
        g = top_reg.get(c)
        if g is None or g.empty:
            continue
        regs = [(r["source_region"], float(r["share_%"])) for _, r in g.iterrows()]
        cc = top_cty.get(c)
        top5 = ", ".join(f"{r['source_country']} {_pct(r['share_%'], 0)}%" for _, r in cc.head(5).iterrows()) if cc is not None else ""
        r1n, p1 = regs[0]
        r2txt = (", " + f"{regs[1][0]} {_pct(regs[1][1], 0)}%") if len(regs) > 1 else ""
        sents = [L["c_main"].format(r1=r1n, p1=_pct(p1, 0), r2txt=r2txt, top=top5)]
        if n <= 2:
            sents.append(L["c_few"].format(n=n))
        d = ei_by.get(c, {})
        if d and float(d.get("self_share_pct", 0)) >= 40:
            sents.append(L["c_self"].format(x=_pct(d["self_share_pct"], 0)))
        is_end = c in endemic_countries
        if not is_end:
            sents.append(L["c_non"])
        if med_by.get(c, 100) < 90:
            sents.append(L["c_low"].format(m=_pct(med_by[c], 0)))
        dr = region_map.get(c)
        if dr and r1n != dr:
            sents.append(L["c_cross"].format(r1=r1n, dr=dr))
        tag_html = (f'<span class="tag">{L["endemic"]}</span>' if is_end else f'<span class="tag non">{L["nonendemic"]}</span>')
        per_rows.append(
            f"<tr><td><b>{_html.escape(c)}</b></td><td>{tag_html}</td><td>{n}</td>"
            f"<td style='min-width:200px'>{_stack_bar(regs)}</td>"
            f"<td>{_html.escape(top5)}</td><td>{' '.join(_md(x) for x in sents[1:]) or '—'}</td></tr>")

    # ── 그림 ────────────────────────────────────────────────────────────────
    fig_paths = []
    figdir = results_dir / "02_figures"
    if figdir.exists():
        fig_paths += sorted(str(p) for p in figdir.glob(f"*_{tag}.png"))
    for pat in ("DENV*.png", "top3_countries_*.png"):
        for p in sorted(results_dir.glob(pat)):
            if tag in p.name or pat.startswith("top3"):
                fig_paths.append(str(p))
    seen, figs_html, fig_used = set(), "", []
    for p in fig_paths:
        if p in seen:
            continue
        seen.add(p)
        b = _img_b64(p)
        if b:
            fig_used.append(p)
            figs_html += f'<figure><img src="{b}" alt="{_html.escape(os.path.basename(p))}"/><figcaption>{_html.escape(os.path.basename(p))}</figcaption></figure>'
    if not figs_html:
        figs_html = f"<p>{L['no_fig']}</p>"

    now = _dt.datetime.now().strftime("%Y-%m-%d %H:%M")
    kpi = (f'<div class="rp-kpis">'
           f'<div class="rp-kpi"><b>{n_seq}</b><span>{L["k_seq"]}</span></div>'
           f'<div class="rp-kpi"><b>{n_ctry}</b><span>{L["k_ctry"]}</span></div>'
           f'<div class="rp-kpi"><b>{_pct(med)}%</b><span>{L["k_med"]}</span></div>'
           f'<div class="rp-kpi"><b>{low}</b><span>{L["k_low"]}</span></div></div>')

    body = (
        f'<div class="rp"><h1>{L["title"]}</h1><p class="rp-sub">{L["sub"]}</p>'
        f'<div class="rp-meta">{L["made"]}: {now} · {L["sero"]}: {_html.escape(serotype_label or "DENV")} · {L["gene"]}: {_html.escape(gene)}</div>'
        f'<h2>{L["h_over"]}</h2>{kpi}<div class="rp-box"><ul>' + "".join(f"<li>{_md(b)}</li>" for b in bullets) + "</ul></div>"
        f'<h2>{L["h_s2"]}</h2><table><tr><th>{L["s2_c1"]}</th><th>{L["s2_c2"]}</th><th>{L["s2_c3"]}</th><th>{L["s2_c4"]}</th></tr>' + "".join(rows2) + "</table>"
        f'<h2>{L["h_s3"]}</h2><div class="rp-grid"><div class="rp-card"><h3>{L["s3_reg"]}</h3>{reg_html}</div>'
        f'<div class="rp-card"><h3>{L["s3_cty"]}</h3>{cty_html}</div>'
        f'<div class="rp-card"><h3>{L["s3_ei"]} <span style="font-weight:400;color:#64748b">({L["e_self"]}/{L["e_imp"]} %)</span></h3>{ei_html}</div></div>'
        f'<h2>{L["h_per"]}</h2><table><tr><th>{L["p_c1"]}</th><th>{L["p_c2"]}</th><th>{L["p_c3"]}</th><th>{L["p_c4"]}</th><th>{L["p_c5"]}</th><th>{L["p_c6"]}</th></tr>'
        + "".join(per_rows) + "</table>"
        f'<h2>{L["h_fig"]}</h2><p style="color:#64748b">{L["fig_note"]}</p>{figs_html}'
        f'<h2>{L["h_note"]}</h2><ul>' + "".join(f"<li>{_md(x)}</li>" for x in L["notes"]) + "</ul>"
        f'<h2>{L["h_files"]}</h2><p>{L["files_zip"]}</p><p style="color:#64748b">{L["print_hint"]}</p></div>')

    page = (f'<!doctype html><html lang="{lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
            f'<title>{L["title"]}</title><style>body{{margin:0;padding:24px;background:#fff}}{_CSS}</style></head><body>{body}</body></html>')
    screen = f"<style>{_CSS}</style>{body}"

    md_lines = [f"# {L['title']}", "", f"- {L['made']}: {now}", f"- {L['sero']}: {serotype_label or 'DENV'} / {L['gene']}: {gene}",
                f"- {L['k_seq']}: {n_seq} / {L['k_ctry']}: {n_ctry} / {L['k_med']}: {_pct(med)}% / {L['k_low']}: {low}", ""]
    md_lines += [f"- {b}" for b in bullets] + [""]

    # ── 파일 저장 + ZIP ─────────────────────────────────────────────────────
    out_dir = Path(out_dir) if out_dir else results_dir / "_download"
    out_dir.mkdir(parents=True, exist_ok=True)
    for old_f in out_dir.glob("DenAIGeo_*"):
        try:
            old_f.unlink()
        except Exception:
            pass
    base = "_".join(_safe_part(x) for x in (input_name, serotype_label or "DENV", tag) if x) + f"_report_{lang}"
    html_path = out_dir / f"{base}.html"
    html_path.write_text(page, encoding="utf-8")
    zip_path = out_dir / f"{base}.zip"
    n_files = 1
    with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
        zf.write(html_path, arcname=html_path.name)
        for f in sorted(results_dir.rglob("*")):
            if f.is_file() and f.suffix.lower() in {".csv", ".png"} and "_download" not in f.parts \
                    and _file_gene_tag(f.name) in (None, tag):
                zf.write(f, arcname=str(Path("data") / f.relative_to(results_dir)))
                n_files += 1
    return dict(html=screen, html_page=page, md="\n".join(md_lines), html_path=str(html_path),
                zip_path=str(zip_path), message=L["status_ok"].format(n=n_files))