File size: 61,680 Bytes
82d24d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
"""
WOLOJI Comprehensive Bacterial Genomics Suite (trimmed single-file build)

This one file replaces the former woloji/ package, app.py and
validation/compare_outputs.py.

Pipeline modules: read QC, assembly/polishing, QUAST, CheckM2, taxonomy
(GTDB-Tk, Mash, skani), mobileome (MOB-suite, geNomad, IntegronFinder, MinCED),
MLST, cgMLST/wgMLST, core SNP phylogenomics and population genomics (PopPUNK).
Utilities: primer design, local BLAST, PhyloForge and output concordance.

Removed from this build (covered by separate dedicated tools):
  Genome annotation (Bakta/Prokka), composition and codon usage, AMR detection,
  virulence screening, secondary metabolites, eggNOG-mapper and Panaroo.

Two ways to run:
  streamlit run app.py
  python app.py compare OBSERVED EXPECTED --keys Sample_ID [--numeric-tolerance 1e-8] [--json-out out.json]
"""
from __future__ import annotations

import argparse
import gzip
import hashlib
import io
import json
import math
import os
import re
import shutil
import subprocess
import sys
import tempfile
import zipfile
from collections.abc import Callable, Sequence
from dataclasses import asdict, dataclass
from datetime import UTC, datetime
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402
import pandas as pd  # noqa: E402

__version__ = "2.1.0"
SUITE_NAME = "WOLOJI Comprehensive Bacterial Genomics Suite"


# =============================================================================
# Data model
# =============================================================================
@dataclass
class Sample:
    sample_id: str
    read1: Path | None = None
    read2: Path | None = None
    long_reads: Path | None = None
    assembly: Path | None = None
    genus: str = ""
    species: str = ""


# =============================================================================
# Filesystem, hashing and command execution helpers
# =============================================================================
def utc_now() -> str:
    return datetime.now(UTC).isoformat()


def safe_name(value: str) -> str:
    value = re.sub(r"[^A-Za-z0-9._-]+", "_", str(value)).strip("._")
    return value or "sample"


def sha256_file(path: Path, block: int = 1024 * 1024) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as fh:
        while chunk := fh.read(block):
            h.update(chunk)
    return h.hexdigest()


def command_exists(name: str) -> bool:
    return shutil.which(name) is not None


def get_version(command: Sequence[str]) -> str:
    try:
        cp = subprocess.run(command, capture_output=True, text=True, timeout=30, check=False)
        text = (cp.stdout or cp.stderr or "").strip().splitlines()
        return text[0][:300] if text else "unknown"
    except (OSError, subprocess.SubprocessError) as exc:
        return f"unavailable: {exc}"


def open_text(path: Path):
    if str(path).lower().endswith(".gz"):
        return gzip.open(path, "rt", encoding="utf-8", errors="ignore")
    return open(path, encoding="utf-8", errors="ignore")


def fasta_stats(path: Path) -> dict:
    lengths: list[int] = []
    a = c = g = t = n = 0
    with open_text(path) as fh:
        cur = 0
        for raw in fh:
            line = raw.strip()
            if not line:
                continue
            if line.startswith(">"):
                if cur:
                    lengths.append(cur)
                cur = 0
                continue
            s = line.upper()
            cur += len(s)
            ca, cc, cg, ct = s.count("A"), s.count("C"), s.count("G"), s.count("T")
            a += ca; c += cc; g += cg; t += ct
            n += len(s) - (ca + cc + cg + ct)
        if cur:
            lengths.append(cur)
    seq_len = sum(lengths)
    canonical = a + c + g + t
    gc = 100.0 * (g + c) / canonical if canonical else float("nan")
    n_pct = 100.0 * n / seq_len if seq_len else float("nan")
    n50 = l50 = 0
    cum = 0
    for i, length in enumerate(sorted(lengths, reverse=True), start=1):
        cum += length
        if cum >= seq_len / 2.0:
            n50, l50 = length, i
            break
    return {
        "assembly": path.name,
        "total_length_bp": int(seq_len),
        "contigs": len(lengths),
        "largest_contig_bp": int(max(lengths) if lengths else 0),
        "N50_bp": int(n50),
        "L50": int(l50),
        "GC_percent": None if math.isnan(gc) else round(gc, 5),
        "ambiguous_percent": None if math.isnan(n_pct) else round(n_pct, 5),
        "A": a, "C": c, "G": g, "T": t, "ambiguous_bases": n,
    }


@dataclass
class CmdResult:
    name: str
    command: list[str]
    returncode: int
    started_at: str
    finished_at: str
    stdout_path: str
    stderr_path: str
    skipped: bool = False
    reason: str = ""

    def to_dict(self):
        return asdict(self)


class Runner:
    """Runs external commands, logs stdout/stderr and records every call."""

    def __init__(self, log_dir: Path, dry_run: bool = False, timeout: int = 14400):
        self.log_dir = Path(log_dir)
        self.log_dir.mkdir(parents=True, exist_ok=True)
        self.dry_run = dry_run
        self.timeout = timeout
        self.records: list[CmdResult] = []

    def skip(self, name: str, command: Sequence[str], reason: str) -> CmdResult:
        now = utc_now()
        rec = CmdResult(name, [str(x) for x in command], 0, now, now, "", "", True, reason)
        self.records.append(rec)
        return rec

    def run(self, name: str, command: Sequence[str], cwd: Path | None = None,
            stdout_file: Path | None = None, env: dict | None = None,
            check: bool = False) -> CmdResult:
        command = [str(x) for x in command]
        exe = command[0]
        # Dry run is checked first, so the intended command is always recorded,
        # even on a machine without the external tools.
        if self.dry_run:
            reason = "dry run" if command_exists(exe) else f"dry run (executable not installed: {exe})"
            return self.skip(name, command, reason)
        if not command_exists(exe):
            if check:
                raise RuntimeError(f"{name} failed: executable not found on PATH: {exe}")
            return self.skip(name, command, f"Executable not found on PATH: {exe}")
        started = utc_now()
        out_path = self.log_dir / f"{safe_name(name)}.stdout.txt"
        err_path = self.log_dir / f"{safe_name(name)}.stderr.txt"
        proc_env = os.environ.copy()
        if env:
            proc_env.update({k: str(v) for k, v in env.items()})
        target = stdout_file or out_path
        target.parent.mkdir(parents=True, exist_ok=True)
        try:
            with open(target, "w", encoding="utf-8") as out, open(err_path, "w", encoding="utf-8") as err:
                cp = subprocess.run(command, cwd=cwd, stdout=out, stderr=err, text=True,
                                    timeout=self.timeout, env=proc_env, check=False)
            code = int(cp.returncode)
        except subprocess.TimeoutExpired:
            with open(err_path, "a", encoding="utf-8") as err:
                err.write(f"\nTerminated after timeout of {self.timeout} s\n")
            code = -9
        rec = CmdResult(name, command, code, started, utc_now(), str(target), str(err_path))
        self.records.append(rec)
        if check and code != 0:
            tail = err_path.read_text(encoding="utf-8", errors="ignore")[-1500:] if err_path.exists() else ""
            raise RuntimeError(f"{name} failed (exit {code}). {tail}")
        return rec

    def write_manifest(self, path: Path):
        path.write_text(json.dumps([r.to_dict() for r in self.records], indent=2), encoding="utf-8")


def safe_extract_zip(zip_path: Path, dest: Path):
    """Extract a ZIP while refusing entries that would escape the destination."""
    dest = dest.resolve()
    with zipfile.ZipFile(zip_path) as zf:
        for info in zf.infolist():
            target = (dest / info.filename).resolve()
            if not str(target).startswith(str(dest) + os.sep) and target != dest:
                raise ValueError(f"Unsafe path in ZIP: {info.filename}")
        zf.extractall(dest)


# =============================================================================
# Sample discovery from uploads or metadata
# =============================================================================
FASTA_EXT = (".fa", ".fasta", ".fna", ".fas", ".fa.gz", ".fasta.gz", ".fna.gz", ".fas.gz")
FASTQ_EXT = (".fastq", ".fq", ".fastq.gz", ".fq.gz")


def save_uploads(uploaded_files, input_dir: Path) -> dict[str, Path]:
    input_dir.mkdir(parents=True, exist_ok=True)
    mapping: dict[str, Path] = {}
    for uploaded in uploaded_files or []:
        name = os.path.basename(uploaded.name)
        target = input_dir / name
        target.write_bytes(uploaded.getvalue())
        if name.lower().endswith(".zip"):
            with zipfile.ZipFile(target) as zf:
                for info in zf.infolist():
                    base = os.path.basename(info.filename)
                    if info.is_dir() or not base or base.startswith("."):
                        continue
                    out = input_dir / base
                    out.write_bytes(zf.read(info.filename))
                    mapping[base] = out
        else:
            mapping[name] = target
    return mapping


def _clean_cell(value) -> str:
    if value is None or (isinstance(value, float) and pd.isna(value)):
        return ""
    return str(value).strip()


def _find_name(mapping: dict[str, Path], value) -> Path | None:
    value = _clean_cell(value)
    if not value:
        return None
    found = mapping.get(value) or mapping.get(os.path.basename(value))
    if found is None:
        raise ValueError(f"File named in metadata was not uploaded: {value}")
    return found


def samples_from_metadata(metadata_path: Path, mapping: dict[str, Path]) -> list[Sample]:
    df = pd.read_csv(metadata_path, sep=None, engine="python")
    if "Sample_ID" not in df.columns:
        raise ValueError("Metadata must contain Sample_ID. Optional columns: "
                         "Read_1, Read_2, Long_Reads, Assembly, Genus, Species")
    samples, seen = [], set()
    for _, row in df.iterrows():
        sid = safe_name(row["Sample_ID"])
        if sid in seen:
            raise ValueError(f"Duplicate Sample_ID in metadata: {sid}")
        seen.add(sid)
        samples.append(Sample(
            sample_id=sid,
            read1=_find_name(mapping, row.get("Read_1")),
            read2=_find_name(mapping, row.get("Read_2")),
            long_reads=_find_name(mapping, row.get("Long_Reads")),
            assembly=_find_name(mapping, row.get("Assembly")),
            genus=_clean_cell(row.get("Genus")),
            species=_clean_cell(row.get("Species")),
        ))
    return samples


def _stem_without_ext(name: str) -> str:
    for ext in sorted(FASTQ_EXT + FASTA_EXT, key=len, reverse=True):
        if name.lower().endswith(ext):
            return name[:-len(ext)]
    return Path(name).stem


_PAIR_PATTERNS = [
    (re.compile(r"(.+?)_R?1(?:_\d+)?$", re.IGNORECASE), "read1"),
    (re.compile(r"(.+?)_R?2(?:_\d+)?$", re.IGNORECASE), "read2"),
]


def auto_samples(mapping: dict[str, Path]) -> list[Sample]:
    """Pair files by name. Ambiguous duplicate assignments raise an error instead of being overwritten."""
    samples: dict[str, Sample] = {}

    def assign(sid: str, field: str, path: Path):
        s = samples.setdefault(sid, Sample(sample_id=sid))
        current = getattr(s, field)
        if current is not None and current != path:
            raise ValueError(f"Ambiguous input for sample {sid}: both {current.name} and {path.name} "
                             f"map to {field}. Use a metadata table.")
        setattr(s, field, path)

    for name, path in sorted(mapping.items()):
        low = name.lower()
        if low.endswith(FASTQ_EXT):
            stem = _stem_without_ext(name)
            for pat, field in _PAIR_PATTERNS:
                m = pat.match(stem)
                if m:
                    assign(safe_name(m.group(1)), field, path)
                    break
            else:
                # An unpaired FASTQ is interpreted as long-read input.
                assign(safe_name(stem), "long_reads", path)
        elif low.endswith(FASTA_EXT):
            assign(safe_name(_stem_without_ext(name)), "assembly", path)
    for s in samples.values():
        if s.read2 and not s.read1:
            raise ValueError(f"Sample {s.sample_id} has an R2 file without a matching R1 file.")
    return sorted(samples.values(), key=lambda s: s.sample_id)


# =============================================================================
# External tool and database status
# =============================================================================
TOOLS = {
    "fastp": ["fastp", "--version"],
    "FastQC": ["fastqc", "--version"],
    "MultiQC": ["multiqc", "--version"],
    "SPAdes": ["spades.py", "--version"],
    "Flye": ["flye", "--version"],
    "Unicycler": ["unicycler", "--version"],
    "BWA": ["bwa"],
    "Polypolish": ["polypolish", "--version"],
    "QUAST": ["quast.py", "--version"],
    "CheckM2": ["checkm2", "--version"],
    "GTDB-Tk": ["gtdbtk", "--version"],
    "Mash": ["mash", "--version"],
    "skani": ["skani", "--version"],
    "MOB-suite": ["mob_recon", "--version"],
    "geNomad": ["genomad", "--version"],
    "IntegronFinder": ["integron_finder", "--version"],
    "MinCED": ["minced", "--version"],
    "mlst": ["mlst", "--version"],
    "chewBBACA": ["chewBBACA.py", "--version"],
    "Snippy": ["snippy", "--version"],
    "Gubbins": ["run_gubbins.py", "--version"],
    "MAFFT": ["mafft", "--version"],
    "IQ-TREE 2": ["iqtree2", "--version"],
    "PopPUNK": ["poppunk", "--version"],
    "BLAST+": ["blastn", "-version"],
}

DATABASES = {
    "GTDB-Tk": "GTDBTK_DATA_PATH",
    "CheckM2": "CHECKM2DB",
    "geNomad": "GENOMAD_DB",
    "MOB-suite": "MOB_SUITE_DB",
}


def status_rows():
    rows = []
    for display, cmd in TOOLS.items():
        ok = command_exists(cmd[0])
        rows.append({"tool": display, "executable": cmd[0], "available": ok,
                     "version": get_version(cmd) if ok else "not installed"})
    return rows


def database_rows():
    rows = []
    for name, envvar in DATABASES.items():
        value = os.getenv(envvar, "")
        rows.append({"database": name, "environment_variable": envvar, "path": value,
                     "detected": bool(value) and Path(value).exists()})
    return rows


# =============================================================================
# Publication figures
# =============================================================================
def _bar_or_scatter(df: pd.DataFrame, column: str, ylabel: str, title: str, out: Path, kind: str):
    if df.empty or column not in df:
        return
    fig, ax = plt.subplots(figsize=(8, 4.8))
    x = list(range(len(df)))
    y = pd.to_numeric(df[column], errors="coerce")
    if kind == "bar":
        ax.bar(x, y)
    else:
        ax.scatter(x, y, s=42)
    ax.set_xticks(x)
    ax.set_xticklabels(df["sample"], rotation=45, ha="right")
    ax.set_ylabel(ylabel)
    ax.set_title(title)
    fig.tight_layout()
    fig.savefig(out, dpi=600, bbox_inches="tight")
    plt.close(fig)


def assembly_summary_plot(df: pd.DataFrame, out: Path):
    _bar_or_scatter(df, "N50_bp", "N50 (bp)", "Assembly contiguity across isolates", out, "bar")


def gc_plot(df: pd.DataFrame, out: Path):
    _bar_or_scatter(df, "GC_percent", "GC (%)", "Genome GC content", out, "scatter")


# =============================================================================
# Utilities: primer design, local BLAST, PhyloForge
# =============================================================================
def read_fasta_bytes(file_bytes: bytes) -> list[tuple[str, str]]:
    from Bio import SeqIO
    text = file_bytes.decode("utf-8", errors="ignore")
    return [(rec.id, str(rec.seq).upper()) for rec in SeqIO.parse(io.StringIO(text), "fasta")]


def fasta_first_sequence(file_bytes: bytes) -> tuple[str, str]:
    records = read_fasta_bytes(file_bytes)
    if not records:
        raise ValueError("No FASTA record was found in the file.")
    return records[0]


def design_primers(sequence: str, target_start: int = 0, target_length: int = 0,
                   product_min: int = 100, product_max: int = 600, num_return: int = 5) -> pd.DataFrame:
    import primer3
    seq = re.sub(r"\s+", "", sequence).upper()
    if product_min >= product_max:
        raise ValueError("Minimum product size must be smaller than the maximum product size.")
    if len(seq) < product_min:
        raise ValueError(f"Template ({len(seq)} bp) is shorter than the minimum product size ({product_min} bp).")
    args = {"SEQUENCE_ID": "target", "SEQUENCE_TEMPLATE": seq}
    if target_length > 0:
        args["SEQUENCE_TARGET"] = [int(target_start), int(target_length)]
    global_args = {
        "PRIMER_OPT_SIZE": 20, "PRIMER_MIN_SIZE": 18, "PRIMER_MAX_SIZE": 25,
        "PRIMER_OPT_TM": 60.0, "PRIMER_MIN_TM": 57.0, "PRIMER_MAX_TM": 63.0,
        "PRIMER_MIN_GC": 35.0, "PRIMER_MAX_GC": 65.0,
        "PRIMER_PRODUCT_SIZE_RANGE": [[int(product_min), int(product_max)]],
        "PRIMER_NUM_RETURN": int(num_return),
    }
    res = primer3.bindings.design_primers(args, global_args)
    rows = []
    for i in range(int(res.get("PRIMER_PAIR_NUM_RETURNED", 0))):
        rows.append({
            "pair": i + 1,
            "left_primer": res.get(f"PRIMER_LEFT_{i}_SEQUENCE", ""),
            "right_primer": res.get(f"PRIMER_RIGHT_{i}_SEQUENCE", ""),
            "left_tm": res.get(f"PRIMER_LEFT_{i}_TM"),
            "right_tm": res.get(f"PRIMER_RIGHT_{i}_TM"),
            "left_gc": res.get(f"PRIMER_LEFT_{i}_GC_PERCENT"),
            "right_gc": res.get(f"PRIMER_RIGHT_{i}_GC_PERCENT"),
            "product_size": res.get(f"PRIMER_PAIR_{i}_PRODUCT_SIZE"),
            "pair_penalty": res.get(f"PRIMER_PAIR_{i}_PENALTY"),
        })
    return pd.DataFrame(rows)


def local_blast(query_bytes: bytes, subject_bytes: bytes, task: str = "blastn",
                evalue: float = 1e-10, threads: int = 2) -> pd.DataFrame:
    fields = "qseqid sseqid pident length mismatch gapopen qstart qend sstart send evalue bitscore qcovs"
    cols = fields.split()
    with tempfile.TemporaryDirectory() as td:
        td = Path(td)
        q, s = td / "query.fasta", td / "subject.fasta"
        q.write_bytes(query_bytes)
        s.write_bytes(subject_bytes)
        runner = Runner(td / "logs")
        runner.run("makeblastdb", ["makeblastdb", "-in", s, "-dbtype", "nucl", "-out", td / "db"], check=True)
        out = td / "blast.tsv"
        runner.run("blastn", ["blastn", "-task", task, "-query", q, "-db", td / "db", "-evalue", evalue,
                              "-num_threads", threads, "-outfmt", f"6 {fields}", "-out", out], check=True)
        if out.exists() and out.stat().st_size:
            return pd.read_csv(out, sep="\t", names=cols)
        return pd.DataFrame(columns=cols)


def phyloforge(files, threads: int = 2, model: str = "MFP", bootstrap: int = 1000) -> tuple[str, str, str]:
    """MAFFT alignment followed by IQ-TREE 2 with ultrafast bootstrap. Returns alignment, Newick tree and log."""
    records: list[tuple[str, str]] = []
    for f in files:
        records.extend(read_fasta_bytes(f.getvalue()))
    ids = [r[0] for r in records]
    dups = sorted({x for x in ids if ids.count(x) > 1})
    if dups:
        raise ValueError(f"Duplicate sequence IDs across the uploaded files: {', '.join(dups[:10])}")
    if len(records) < 4:
        raise ValueError(f"IQ-TREE with ultrafast bootstrap needs at least 4 sequences; {len(records)} found.")
    with tempfile.TemporaryDirectory() as td:
        td = Path(td)
        inp = td / "input.fasta"
        inp.write_text("".join(f">{i}\n{s}\n" for i, s in records), encoding="utf-8")
        runner = Runner(td / "logs")
        aln = td / "aligned.fasta"
        runner.run("mafft", ["mafft", "--auto", "--thread", threads, inp], stdout_file=aln, check=True)
        prefix = td / "tree"
        runner.run("iqtree", ["iqtree2", "-s", aln, "-m", model, "-B", bootstrap, "-T", threads,
                              "--prefix", prefix], check=True)
        tree = Path(f"{prefix}.treefile")
        log = Path(f"{prefix}.iqtree")
        return (aln.read_text() if aln.exists() else "",
                tree.read_text() if tree.exists() else "",
                log.read_text() if log.exists() else "")


# =============================================================================
# Output concordance (formerly validation/compare_outputs.py)
# =============================================================================
def read_table(path_or_buffer, name: str | None = None) -> pd.DataFrame:
    label = (name or str(path_or_buffer)).lower()
    if label.endswith((".tsv", ".txt", ".tab")):
        return pd.read_csv(path_or_buffer, sep="\t")
    return pd.read_csv(path_or_buffer)


def compare_tables(observed: pd.DataFrame, expected: pd.DataFrame, keys: list[str],
                   numeric_tolerance: float = 1e-8) -> dict[str, object]:
    """Compare a WOLOJI table with a direct-tool reference table on shared key columns."""
    missing = [k for k in keys if k not in observed.columns or k not in expected.columns]
    if missing:
        raise ValueError(f"Missing key columns: {', '.join(missing)}")
    merged = observed.merge(expected, how="outer", on=keys, suffixes=("_observed", "_expected"), indicator=True)
    only_observed = merged[merged["_merge"] == "left_only"]
    only_expected = merged[merged["_merge"] == "right_only"]
    shared = merged[merged["_merge"] == "both"].copy()

    compared_columns: list[str] = []
    disagreements: list[dict[str, object]] = []
    disagreement_count = 0
    for column in sorted((set(observed.columns) & set(expected.columns)) - set(keys)):
        left, right = f"{column}_observed", f"{column}_expected"
        if left not in shared.columns or right not in shared.columns:
            continue
        compared_columns.append(column)
        lv, rv = shared[left], shared[right]
        if pd.api.types.is_numeric_dtype(lv) and pd.api.types.is_numeric_dtype(rv):
            lnum, rnum = pd.to_numeric(lv, errors="coerce"), pd.to_numeric(rv, errors="coerce")
            mismatch = ((lnum - rnum).abs() > numeric_tolerance) | (lnum.isna() ^ rnum.isna())
        else:
            mismatch = lv.astype(object).where(lv.notna(), "<NA>").astype(str) != \
                       rv.astype(object).where(rv.notna(), "<NA>").astype(str)
        disagreement_count += int(mismatch.sum())
        for _, row in shared.loc[mismatch, keys + [left, right]].iterrows():
            if len(disagreements) >= 100:
                break
            record = {k: row[k] for k in keys}
            record.update({"column": column, "observed": row[left], "expected": row[right]})
            disagreements.append(record)

    tp, fp, fn = len(shared), len(only_observed), len(only_expected)
    precision = tp / (tp + fp) if tp + fp else math.nan
    recall = tp / (tp + fn) if tp + fn else math.nan
    f1 = 2 * precision * recall / (precision + recall) if (precision + recall) else math.nan
    return {
        "observed_rows": int(len(observed)),
        "expected_rows": int(len(expected)),
        "matched_key_rows": int(tp),
        "only_observed_rows": int(fp),
        "only_expected_rows": int(fn),
        "key_precision": precision,
        "key_recall": recall,
        "key_f1": f1,
        "compared_columns": compared_columns,
        "value_disagreement_count": disagreement_count,
        "value_disagreements_first_100": disagreements,
    }


def compare_cli(argv: list[str]) -> int:
    parser = argparse.ArgumentParser(prog="python app.py compare",
                                     description="Compare WOLOJI tabular output with a direct-tool reference output.")
    parser.add_argument("observed", type=Path, help="WOLOJI output CSV/TSV")
    parser.add_argument("expected", type=Path, help="Direct-tool reference CSV/TSV")
    parser.add_argument("--keys", required=True, help="Comma-separated key columns used to match records")
    parser.add_argument("--numeric-tolerance", type=float, default=1e-8)
    parser.add_argument("--json-out", type=Path, default=None)
    args = parser.parse_args(argv)
    result = compare_tables(read_table(args.observed), read_table(args.expected),
                            [k.strip() for k in args.keys.split(",") if k.strip()], args.numeric_tolerance)
    payload = json.dumps(result, indent=2, default=str)
    print(payload)
    if args.json_out:
        args.json_out.write_text(payload + "\n", encoding="utf-8")
    return 0


# =============================================================================
# End-to-end analysis pipeline
# =============================================================================
DEFAULTS = {
    "threads": 4,
    "memory_gb": 12,
    "fastp_quality": 20,
    "fastp_length": 50,
    "fastp_n_limit": 5,
    "assembly_mode": "Auto",
    "genome_size": "5m",
    "iqtree_model": "MFP",
    "iqtree_bootstrap": 1000,
    "dry_run": False,
    "timeout": 14400,
}


def _emit(cb: Callable[[str], None] | None, text: str):
    if cb:
        cb(text)


def _copy_or_link(src: Path, dst: Path):
    dst.parent.mkdir(parents=True, exist_ok=True)
    if dst.exists() or dst.is_symlink():
        dst.unlink()
    try:
        dst.symlink_to(Path(src).resolve())
    except OSError:
        shutil.copy2(src, dst)


def _run_fastp(sample: Sample, out: Path, runner: Runner, p: dict):
    qc = out / "01_read_qc" / sample.sample_id
    qc.mkdir(parents=True, exist_ok=True)
    r1 = qc / f"{sample.sample_id}.clean_R1.fastq.gz"
    r2 = qc / f"{sample.sample_id}.clean_R2.fastq.gz" if sample.read2 else None
    cmd = ["fastp", "-i", sample.read1, "-o", r1,
           "--qualified_quality_phred", p["fastp_quality"],
           "--length_required", p["fastp_length"],
           "--n_base_limit", p["fastp_n_limit"],
           "--thread", p["threads"],
           "--json", qc / "fastp.json", "--html", qc / "fastp.html"]
    if sample.read2:
        cmd += ["-I", sample.read2, "-O", r2, "--detect_adapter_for_pe"]
    result = runner.run(f"{sample.sample_id}_fastp", cmd)
    if result.skipped or result.returncode != 0:
        return sample.read1, sample.read2
    runner.run(f"{sample.sample_id}_fastqc", ["fastqc", "-t", p["threads"], "-o", qc, *[x for x in (r1, r2) if x]])
    return r1, r2


def _polypolish(sample_id: str, draft: Path, r1: Path, r2: Path, out: Path, runner: Runner, threads: int):
    pol = out / "03_polishing" / sample_id
    pol.mkdir(parents=True, exist_ok=True)
    draft_copy = pol / "draft.fasta"
    if draft.exists():
        shutil.copy2(draft, draft_copy)
    runner.run(f"{sample_id}_bwa_index", ["bwa", "index", draft_copy])
    a1, a2 = pol / "alignments_1.sam", pol / "alignments_2.sam"
    runner.run(f"{sample_id}_bwa_r1", ["bwa", "mem", "-t", threads, "-a", draft_copy, r1], stdout_file=a1)
    runner.run(f"{sample_id}_bwa_r2", ["bwa", "mem", "-t", threads, "-a", draft_copy, r2], stdout_file=a2)
    f1, f2 = pol / "filtered_1.sam", pol / "filtered_2.sam"
    runner.run(f"{sample_id}_polypolish_filter",
               ["polypolish", "filter", "--in1", a1, "--in2", a2, "--out1", f1, "--out2", f2])
    polished = pol / "polished.fasta"
    rec = runner.run(f"{sample_id}_polypolish", ["polypolish", "polish", draft_copy, f1, f2], stdout_file=polished)
    if not runner.dry_run and (rec.skipped or rec.returncode != 0):
        return draft  # fall back to the unpolished Flye assembly
    return polished


def _assemble(sample: Sample, r1: Path | None, r2: Path | None, out: Path, runner: Runner, p: dict):
    if sample.assembly:
        return sample.assembly
    asm_root = out / "02_assembly" / sample.sample_id
    asm_root.mkdir(parents=True, exist_ok=True)
    threads, mem, mode = p["threads"], p["memory_gb"], p["assembly_mode"]
    long_ok = mode in {"Auto", "Long-read: Flye"}
    hybrid_ok = mode in {"Auto", "Hybrid: Unicycler"}
    short_ok = mode in {"Auto", "Short-read: SPAdes"}

    if sample.long_reads and r1 and r2 and hybrid_ok:
        runner.run(f"{sample.sample_id}_unicycler",
                   ["unicycler", "-1", r1, "-2", r2, "-l", sample.long_reads, "-o", asm_root, "-t", threads])
        return asm_root / "assembly.fasta"
    if sample.long_reads and long_ok:
        runner.run(f"{sample.sample_id}_flye", ["flye", "--nano-hq", sample.long_reads, "--out-dir", asm_root,
                                                "--threads", threads, "--genome-size", p["genome_size"]])
        draft = asm_root / "assembly.fasta"
        if r1 and r2:
            return _polypolish(sample.sample_id, draft, r1, r2, out, runner, threads)
        return draft
    if r1 and short_ok:
        cmd = ["spades.py", "--isolate", "-1", r1, "-2", r2] if r2 else ["spades.py", "--isolate", "-s", r1]
        runner.run(f"{sample.sample_id}_spades", cmd + ["-o", asm_root, "-t", threads, "-m", mem])
        return asm_root / "contigs.fasta"
    runner.skip(f"{sample.sample_id}_assembly", [mode],
                f"Assembly strategy '{mode}' does not match the available reads for this sample")
    return None


def _quast(sample_id, assembly, out, runner, threads):
    runner.run(f"{sample_id}_quast", ["quast.py", assembly, "-o", out / "04_assembly_qc" / "quast" / sample_id,
                                      "-t", threads])


def _checkm2(sample_id, assembly, out, runner, threads):
    qout = out / "04_assembly_qc" / "checkm2" / sample_id
    indir = qout / "input"
    indir.mkdir(parents=True, exist_ok=True)
    _copy_or_link(assembly, indir / f"{sample_id}.fasta")
    cmd = ["checkm2", "predict", "--threads", threads, "--input", indir,
           "--output-directory", qout / "results", "--extension", "fasta"]
    db = os.getenv("CHECKM2DB", "")
    if db:
        cmd += ["--database_path", db]
    runner.run(f"{sample_id}_checkm2", cmd)


def _mobileome(sample_id, assembly, out, runner, threads):
    root = out / "12_mobileome" / sample_id
    root.mkdir(parents=True, exist_ok=True)
    cmd = ["mob_recon", "--infile", assembly, "--outdir", root / "mob_suite", "--num_threads", threads]
    mob_db = os.getenv("MOB_SUITE_DB", "")
    if mob_db:
        cmd += ["--database_directory", mob_db]
    runner.run(f"{sample_id}_mob_recon", cmd)
    gdb = os.getenv("GENOMAD_DB", "")
    if gdb and Path(gdb).exists():
        runner.run(f"{sample_id}_genomad", ["genomad", "end-to-end", "--cleanup", "--splits", threads,
                                            assembly, root / "genomad", gdb])
    else:
        runner.skip(f"{sample_id}_genomad", ["genomad", "end-to-end", assembly, root / "genomad", "$GENOMAD_DB"],
                    "GENOMAD_DB is not configured")
    runner.run(f"{sample_id}_integronfinder", ["integron_finder", "--local-max", "--cpu", min(int(threads), 4),
                                               "--outdir", root / "integrons", assembly])
    runner.run(f"{sample_id}_minced", ["minced", assembly, root / "crispr.txt", root / "crispr.gff"])


def _mlst(sample_id, assembly, out, runner):
    root = out / "13_typing" / "mlst"
    root.mkdir(parents=True, exist_ok=True)
    runner.run(f"{sample_id}_mlst", ["mlst", "--full", assembly], stdout_file=root / f"{sample_id}.tsv")


def _gtdbtk(assemblies: dict[str, Path], out: Path, runner: Runner, threads: int):
    if not assemblies:
        return
    root = out / "05_taxonomy" / "gtdbtk"
    inp = root / "input"
    inp.mkdir(parents=True, exist_ok=True)
    for sid, asm in assemblies.items():
        _copy_or_link(asm, inp / f"{sid}.fasta")
    cmd = ["gtdbtk", "classify_wf", "--genome_dir", inp, "--out_dir", root / "results",
           "--extension", "fasta", "--cpus", threads, "--skip_ani_screen"]
    db = os.getenv("GTDBTK_DATA_PATH", "")
    if not db or not Path(db).exists():
        runner.skip("gtdbtk_classify", cmd, "GTDBTK_DATA_PATH is not configured")
        return
    runner.run("gtdbtk_classify", cmd)


def _mash_skani(assemblies: dict[str, Path], out: Path, runner: Runner, threads: int):
    if len(assemblies) < 2:
        runner.skip("mash_skani", ["mash", "skani"], "Pairwise distance and ANI need at least two genomes")
        return
    root = out / "05_taxonomy" / "comparative"
    root.mkdir(parents=True, exist_ok=True)
    paths = list(assemblies.values())
    runner.run("mash_sketch", ["mash", "sketch", "-o", root / "genomes", *paths])
    runner.run("mash_dist", ["mash", "dist", root / "genomes.msh", root / "genomes.msh"],
               stdout_file=root / "mash_dist.tsv")
    runner.run("skani_triangle", ["skani", "triangle", "-s", "90", "-t", threads, "-E", *paths],
               stdout_file=root / "skani_triangle.tsv")


def _chewbbaca(assemblies: dict[str, Path], schema_dir: Path | None, out: Path, runner: Runner, threads: int):
    if len(assemblies) < 2 or not schema_dir:
        runner.skip("chewbbaca", ["chewBBACA.py", "AlleleCall"],
                    "cgMLST/wgMLST requires at least two genomes and a schema directory")
        return
    root = out / "13_typing" / "chewbbaca"
    inp = root / "genomes"
    inp.mkdir(parents=True, exist_ok=True)
    for sid, asm in assemblies.items():
        _copy_or_link(asm, inp / f"{sid}.fasta")
    runner.run("chewbbaca_allelecall", ["chewBBACA.py", "AlleleCall", "-i", inp, "-g", schema_dir,
                                        "-o", root / "allelecall", "--cpu", threads])


def _phylogenomics(samples: list[Sample], assemblies: dict[str, Path], reference: Path | None,
                   out: Path, runner: Runner, p: dict):
    if len(assemblies) < 3 or reference is None:
        runner.skip("core_snp_phylogeny", ["snippy"],
                    "Core SNP phylogeny requires at least three samples and a reference genome")
        return
    root = out / "16_phylogenomics"
    snippy_dirs = []
    for s in samples:
        asm = assemblies.get(s.sample_id)
        if asm is None:
            continue
        od = root / "snippy" / s.sample_id
        snippy_dirs.append(od)
        base = ["snippy", "--cpus", p["threads"], "--outdir", od, "--ref", reference, "--force"]
        if s.read1:
            cmd = base + ["--R1", s.read1] + (["--R2", s.read2] if s.read2 else [])
        else:
            cmd = base + ["--ctgs", asm]
        runner.run(f"{s.sample_id}_snippy", cmd)
    core = root / "core"
    core.mkdir(parents=True, exist_ok=True)
    runner.run("snippy_core", ["snippy-core", "--ref", reference, "--prefix", core / "core", *snippy_dirs])
    aln = core / "core.full.aln"
    gub = root / "gubbins"
    gub.mkdir(parents=True, exist_ok=True)
    rec = runner.run("gubbins", ["run_gubbins.py", "--prefix", gub / "gubbins", "--threads", p["threads"], aln])
    filt = gub / "gubbins.filtered_polymorphic_sites.fasta"
    iqdir = root / "iqtree"
    iqdir.mkdir(parents=True, exist_ok=True)
    if filt.exists() or (runner.dry_run and rec.skipped):
        # Only polymorphic sites remain, so ascertainment-bias correction (+ASC) is applied.
        model = p["iqtree_model"] if "+ASC" in p["iqtree_model"] else f"{p['iqtree_model']}+ASC"
        iq_input = filt
    else:
        model, iq_input = p["iqtree_model"], aln
    runner.run("iqtree", ["iqtree2", "-s", iq_input, "-m", model, "-B", p["iqtree_bootstrap"],
                          "-T", p["threads"], "--prefix", iqdir / "tree"])


def _poppunk(assemblies: dict[str, Path], out: Path, runner: Runner, threads: int):
    if len(assemblies) < 3:
        runner.skip("poppunk", ["poppunk", "--create-db"],
                    "PopPUNK model fitting needs at least three genomes (many more for stable clusters)")
        return
    root = out / "17_population" / "poppunk"
    root.mkdir(parents=True, exist_ok=True)
    rlist = root / "rlist.txt"
    rlist.write_text("".join(f"{sid}\t{path}\n" for sid, path in assemblies.items()))
    runner.run("poppunk_create_db", ["poppunk", "--create-db", "--output", root / "database",
                                     "--r-files", rlist, "--threads", threads])
    runner.run("poppunk_fit", ["poppunk", "--fit-model", "bgmm", "--K", "2", "--ref-db", root / "database",
                               "--output", root / "database", "--threads", threads])


def _publication_report(run_dir: Path, samples: list[Sample], assemblies: dict[str, Path],
                        runner: Runner, modules: dict):
    report = run_dir / "20_publication_report"
    tables, figs = report / "tables", report / "figures"
    tables.mkdir(parents=True, exist_ok=True)
    figs.mkdir(parents=True, exist_ok=True)
    rows = []
    for sid, asm in assemblies.items():
        if Path(asm).exists():
            d = fasta_stats(Path(asm))
            d["sample"] = sid
            rows.append(d)
    df = pd.DataFrame(rows)
    if not df.empty:
        df.to_csv(tables / "assembly_summary.csv", index=False)
        assembly_summary_plot(df, figs / "assembly_n50.png")
        gc_plot(df, figs / "genome_gc.png")
    used = [k for k, v in modules.items() if v]
    methods = [
        f"{SUITE_NAME} v{__version__} was used to coordinate the following analysis modules: {', '.join(used)}.",
        "The exact commands, software versions, parameters, input SHA256 checksums and database paths are "
        "recorded in run_manifest.json, command_manifest.json and input_manifest.tsv.",
        "Taxonomic assignments, mobile genetic element predictions, sequence types and population clusters "
        "should be interpreted in the context of genome quality and the reference database release used. "
        "Cite each underlying program that was executed.",
    ]
    (report / "methods_note.txt").write_text("\n\n".join(methods) + "\n", encoding="utf-8")
    summary = {
        "samples": len(samples),
        "assemblies_available": len(assemblies),
        "commands_total": len(runner.records),
        "commands_skipped": sum(r.skipped for r in runner.records),
        "commands_failed": sum((not r.skipped and r.returncode != 0) for r in runner.records),
    }
    (report / "run_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")


def _zip_run(run_dir: Path) -> Path:
    target = run_dir.parent / f"{run_dir.name}.zip"
    with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as zf:
        for path in run_dir.rglob("*"):
            if path.is_file():
                zf.write(path, path.relative_to(run_dir))
    return target


def run_pipeline(samples: list[Sample], run_dir: Path, modules: dict, params: dict,
                 reference: Path | None = None, schema_dir: Path | None = None,
                 progress_cb: Callable[[str], None] | None = None):
    p = DEFAULTS | (params or {})
    run_dir.mkdir(parents=True, exist_ok=True)
    runner = Runner(run_dir / "logs", dry_run=bool(p["dry_run"]), timeout=int(p["timeout"]))
    assemblies: dict[str, Path] = {}

    input_manifest = []
    for s in samples:
        for label, path in [("Read_1", s.read1), ("Read_2", s.read2),
                            ("Long_Reads", s.long_reads), ("Assembly", s.assembly)]:
            if path and Path(path).exists():
                input_manifest.append({"sample": s.sample_id, "type": label, "file": Path(path).name,
                                       "sha256": sha256_file(Path(path))})
    if reference and reference.exists():
        input_manifest.append({"sample": "", "type": "Reference", "file": reference.name,
                               "sha256": sha256_file(reference)})
    pd.DataFrame(input_manifest).to_csv(run_dir / "input_manifest.tsv", sep="\t", index=False)

    for i, sample in enumerate(samples, start=1):
        _emit(progress_cb, f"[{i}/{len(samples)}] {sample.sample_id}: read QC and assembly")
        r1, r2 = sample.read1, sample.read2
        if modules.get("read_qc") and sample.read1:
            r1, r2 = _run_fastp(sample, run_dir, runner, p)
        asm = _assemble(sample, r1, r2, run_dir, runner, p) if modules.get("assembly") else sample.assembly
        if not asm:
            continue
        asm = Path(asm)
        if not runner.dry_run and not asm.exists():
            runner.skip(f"{sample.sample_id}_downstream", [str(asm)],
                        "Assembly was not produced; downstream modules skipped for this sample")
            continue
        assemblies[sample.sample_id] = asm
        _emit(progress_cb, f"[{i}/{len(samples)}] {sample.sample_id}: assembly QC, mobileome and MLST")
        if modules.get("quast"):
            _quast(sample.sample_id, asm, run_dir, runner, p["threads"])
        if modules.get("checkm2"):
            _checkm2(sample.sample_id, asm, run_dir, runner, p["threads"])
        if modules.get("mobileome"):
            _mobileome(sample.sample_id, asm, run_dir, runner, p["threads"])
        if modules.get("mlst"):
            _mlst(sample.sample_id, asm, run_dir, runner)

    if modules.get("read_qc") and (run_dir / "01_read_qc").exists():
        runner.run("multiqc", ["multiqc", run_dir / "01_read_qc", "-o", run_dir / "01_read_qc" / "multiqc"])
    _emit(progress_cb, "Cohort analyses: taxonomy, typing, phylogenomics and population structure")
    if modules.get("taxonomy"):
        _gtdbtk(assemblies, run_dir, runner, p["threads"])
        _mash_skani(assemblies, run_dir, runner, p["threads"])
    if modules.get("cgmlst"):
        _chewbbaca(assemblies, schema_dir, run_dir, runner, p["threads"])
    if modules.get("phylogenomics"):
        _phylogenomics(samples, assemblies, reference, run_dir, runner, p)
    if modules.get("population"):
        _poppunk(assemblies, run_dir, runner, p["threads"])

    _emit(progress_cb, "Writing publication report and manifests")
    _publication_report(run_dir, samples, assemblies, runner, modules)
    runner.write_manifest(run_dir / "command_manifest.json")
    run_manifest = {
        "suite": SUITE_NAME,
        "version": __version__,
        "created_at": utc_now(),
        "parameters": p,
        "modules": modules,
        "database_paths": {v: os.getenv(v, "") for v in DATABASES.values()},
        "samples": [s.sample_id for s in samples],
        "software_versions": status_rows(),
    }
    (run_dir / "run_manifest.json").write_text(json.dumps(run_manifest, indent=2, default=str), encoding="utf-8")
    return _zip_run(run_dir), run_manifest, runner.records


# =============================================================================
# Streamlit interface
# =============================================================================
def _store_upload(uploaded, folder: Path) -> Path:
    path = folder / os.path.basename(uploaded.name)
    path.write_bytes(uploaded.getvalue())
    return path


def render_app():
    import streamlit as st

    st.set_page_config(page_title=SUITE_NAME, page_icon="🧬", layout="wide")
    st.title(f"🧬 {SUITE_NAME}")
    st.caption(f"Version {__version__} | Raw reads to publication-ready bacterial whole-genome analysis")

    with st.expander("Scope and interpretation", expanded=False):
        st.write(
            "WOLOJI is designed for bacterial isolate whole-genome analysis. It coordinates read quality control, "
            "assembly, assembly quality, taxonomy, mobile genetic elements, sequence typing, SNP phylogenomics, "
            "population genomics and reproducibility reporting. Genome annotation, codon usage analysis, AMR "
            "detection, virulence screening and secondary metabolite prediction are handled by separate dedicated "
            "tools and are out of scope here. Database-dependent modules run only when the corresponding database "
            "path is configured. Prediction-based outputs do not replace phenotypic or experimental validation."
        )

    with st.sidebar:
        st.header("Workflow modules")
        modules = {
            "read_qc": st.checkbox("1. Raw read QC", True),
            "assembly": st.checkbox("2. Genome assembly / polishing", True),
            "quast": st.checkbox("3. QUAST assembly QC", True),
            "checkm2": st.checkbox("4. CheckM2 completeness", False),
            "taxonomy": st.checkbox("5. Taxonomy + ANI", True),
            "mobileome": st.checkbox("6. Mobileome / plasmids / prophages / CRISPR", True),
            "mlst": st.checkbox("7. Classical MLST", True),
            "cgmlst": st.checkbox("8. cgMLST / wgMLST", False),
            "phylogenomics": st.checkbox("9. Core SNP phylogenomics", False),
            "population": st.checkbox("10. Population genomics", False),
        }
        st.header("Core parameters")
        cpu = max(1, os.cpu_count() or 2)
        threads = st.slider("CPU threads", 1, cpu, min(4, cpu))
        memory_gb = st.number_input("Assembly memory limit (GB)", 2, 256, 12, 1)
        assembly_mode = st.selectbox("Assembly strategy",
                                     ["Auto", "Hybrid: Unicycler", "Long-read: Flye", "Short-read: SPAdes"])
        genome_size = st.text_input("Expected genome size for Flye", "5m",
                                    help="For example 2.8m for Staphylococcus aureus, 5m for Escherichia coli.")
        fastp_quality = st.slider("fastp minimum Phred", 10, 35, 20)
        fastp_length = st.number_input("fastp minimum read length", 20, 300, 50, 5)
        fastp_n_limit = st.number_input("fastp maximum N bases per read", 0, 50, 5, 1,
                                        help="fastp --n_base_limit is an absolute count, not a percentage.")
        iqtree_model = st.text_input("IQ-TREE model", "MFP", help="MFP runs ModelFinder Plus.")
        dry_run = st.checkbox("Dry run: record commands without executing", False)

    run_tab, utilities_tab, status_tab, help_tab = st.tabs(
        ["Run complete analysis", "Woloji sequence utilities", "Tools & databases", "User guide"])

    # ---------------------------------------------------------------- pipeline
    with run_tab:
        st.subheader("1. Upload data")
        files = st.file_uploader("Upload FASTQ/FASTQ.GZ, FASTA/FASTA.GZ, or a ZIP containing them",
                                 accept_multiple_files=True,
                                 type=["fastq", "fq", "gz", "fa", "fasta", "fna", "fas", "zip"])
        meta = st.file_uploader("Optional metadata CSV/TSV", type=["csv", "tsv", "txt"], key="meta")
        st.caption("Metadata columns: Sample_ID (required), Read_1, Read_2, Long_Reads, Assembly, Genus, Species")
        reference = st.file_uploader("Optional reference genome for core SNP analysis",
                                     type=["fa", "fasta", "fna", "gbk", "gbff"], key="ref")
        schema_zip = st.file_uploader("Optional chewBBACA cgMLST/wgMLST schema ZIP", type=["zip"], key="schema")
        run_name = st.text_input("Run name", value=f"woloji_{datetime.now(UTC).strftime('%Y%m%d_%H%M%S')}")

        if st.button("Run WOLOJI analysis", type="primary", width="stretch"):
            st.session_state.pop("pipeline_result", None)
            if not files:
                st.error("Upload at least one sequencing or assembly file.")
            else:
                work_root = Path(tempfile.gettempdir()) / "woloji_runs"
                run_dir = work_root / safe_name(run_name)
                if run_dir.exists():
                    shutil.rmtree(run_dir)
                input_dir = run_dir / "00_input"
                input_dir.mkdir(parents=True, exist_ok=True)
                samples: list[Sample] = []
                try:
                    mapping = save_uploads(files, input_dir)
                    samples = (samples_from_metadata(_store_upload(meta, input_dir), mapping) if meta
                               else auto_samples(mapping))
                except Exception as exc:  # UI boundary
                    st.error(f"Input parsing failed: {exc}")
                if not samples:
                    st.error("No valid samples were detected. Use a metadata table if automatic pairing is unclear.")
                else:
                    ref_path = _store_upload(reference, input_dir) if reference else None
                    schema_dir = None
                    if schema_zip:
                        schema_dir = input_dir / "cgmlst_schema"
                        schema_dir.mkdir(parents=True, exist_ok=True)
                        safe_extract_zip(_store_upload(schema_zip, input_dir), schema_dir)
                        children = [c for c in schema_dir.iterdir() if c.is_dir()]
                        if len(children) == 1:
                            schema_dir = children[0]
                    st.write("Detected samples")
                    st.dataframe(pd.DataFrame([{
                        "Sample_ID": s.sample_id,
                        "Read_1": s.read1.name if s.read1 else "",
                        "Read_2": s.read2.name if s.read2 else "",
                        "Long_Reads": s.long_reads.name if s.long_reads else "",
                        "Assembly": s.assembly.name if s.assembly else "",
                    } for s in samples]), width="stretch", hide_index=True)
                    status, progress = st.empty(), st.progress(0)
                    events: list[str] = []
                    expected_events = 2 * len(samples) + 2

                    def cb(msg):
                        events.append(msg)
                        status.info(msg)
                        progress.progress(min(95, int(95 * len(events) / expected_events)))

                    params = {"threads": threads, "memory_gb": int(memory_gb), "assembly_mode": assembly_mode,
                              "genome_size": genome_size.strip() or "5m", "fastp_quality": fastp_quality,
                              "fastp_length": int(fastp_length), "fastp_n_limit": int(fastp_n_limit),
                              "iqtree_model": iqtree_model.strip() or "MFP", "dry_run": dry_run}
                    try:
                        zip_path, manifest, records = run_pipeline(samples, run_dir, modules, params,
                                                                   reference=ref_path, schema_dir=schema_dir,
                                                                   progress_cb=cb)
                        progress.progress(100)
                        status.success("Analysis finished")
                        st.session_state["pipeline_result"] = {
                            "zip": str(zip_path), "manifest": manifest,
                            "records": [r.to_dict() for r in records]}
                    except Exception as exc:  # UI boundary
                        progress.empty()
                        status.error(f"Pipeline failed: {exc}")

        result = st.session_state.get("pipeline_result")
        if result and Path(result["zip"]).exists():
            st.subheader("Execution summary")
            cdf = pd.DataFrame(result["records"])
            if not cdf.empty:
                cdf["status"] = cdf.apply(lambda r: "skipped" if r["skipped"]
                                          else ("ok" if r["returncode"] == 0 else "failed"), axis=1)
                st.dataframe(cdf[["name", "status", "returncode", "reason"]], width="stretch", hide_index=True)
            with st.expander("Run manifest"):
                st.json(result["manifest"])
            zp = Path(result["zip"])
            st.download_button("Download complete WOLOJI result package", data=zp.read_bytes(),
                               file_name=zp.name, mime="application/zip", width="stretch")

    # --------------------------------------------------------------- utilities
    with utilities_tab:
        u1, u2, u3, u4 = st.tabs(["Primer design", "GeneClean-BLAST", "PhyloForge", "Output concordance"])
        with u1:
            st.markdown("#### Primer Design Tool (Primer3)")
            primer_file = st.file_uploader("Target FASTA", type=["fa", "fasta", "fna"], key="primer_file")
            primer_text = st.text_area("Or paste target DNA sequence", height=120, key="primer_text")
            pc1, pc2, pc3 = st.columns(3)
            prod_min = pc1.number_input("Minimum product size", 50, 5000, 100, 10)
            prod_max = pc2.number_input("Maximum product size", 60, 10000, 600, 10)
            n_pairs = pc3.number_input("Primer pairs to return", 1, 20, 5, 1)
            if st.button("Design primers", key="design_primers"):
                try:
                    seq = fasta_first_sequence(primer_file.getvalue())[1] if primer_file else primer_text
                    seq = re.sub(r"\s+", "", seq or "")
                    if not seq:
                        st.error("Provide a FASTA file or DNA sequence.")
                    else:
                        st.session_state["primer_df"] = design_primers(
                            seq, product_min=int(prod_min), product_max=int(prod_max), num_return=int(n_pairs))
                except Exception as exc:  # UI boundary
                    st.error(f"Primer design failed: {exc}")
            if "primer_df" in st.session_state:
                pdf = st.session_state["primer_df"]
                if pdf.empty:
                    st.warning("Primer3 returned no pairs. Relax the product size range or check the template.")
                else:
                    st.dataframe(pdf, width="stretch", hide_index=True)
                    st.download_button("Download primer table", pdf.to_csv(index=False).encode(),
                                       "woloji_primers.csv", "text/csv")
        with u2:
            st.markdown("#### GeneClean-BLAST (local BLAST+)")
            q = st.file_uploader("Query FASTA", type=["fa", "fasta", "fna"], key="blast_q")
            subj = st.file_uploader("Subject/reference FASTA", type=["fa", "fasta", "fna"], key="blast_s")
            bc1, bc2 = st.columns(2)
            task = bc1.selectbox("blastn task", ["megablast", "dc-megablast", "blastn", "blastn-short"], index=2)
            evalue = bc2.number_input("E-value threshold", 0.0, 10.0, 1e-10, format="%.1e")
            if st.button("Run local BLAST", key="run_blast"):
                if not q or not subj:
                    st.error("Upload query and subject FASTA files.")
                else:
                    try:
                        st.session_state["blast_df"] = local_blast(q.getvalue(), subj.getvalue(), task=task,
                                                                   evalue=evalue, threads=threads)
                    except Exception as exc:  # UI boundary
                        st.error(f"BLAST failed: {exc}")
            if "blast_df" in st.session_state:
                bdf = st.session_state["blast_df"]
                st.dataframe(bdf, width="stretch", hide_index=True)
                st.download_button("Download BLAST table", bdf.to_csv(index=False).encode(),
                                   "woloji_blast.csv", "text/csv")
        with u3:
            st.markdown("#### PhyloForge (MAFFT + IQ-TREE 2)")
            pf = st.file_uploader("Upload homologous FASTA sequences (at least 4 sequences in total)",
                                  type=["fa", "fasta", "fna", "fas"], accept_multiple_files=True, key="phylo_files")
            pf_model = st.text_input("Substitution model", "MFP", key="pf_model")
            if st.button("Align and infer tree", key="run_phylo"):
                if not pf:
                    st.error("Upload at least one FASTA file.")
                else:
                    try:
                        st.session_state["phylo"] = phyloforge(pf, threads=threads, model=pf_model.strip() or "MFP")
                    except Exception as exc:  # UI boundary
                        st.error(f"PhyloForge failed: {exc}")
            if "phylo" in st.session_state:
                aln, tree, log = st.session_state["phylo"]
                st.text_area("MAFFT alignment", aln, height=250)
                st.code(tree, language="text")
                d1, d2, d3 = st.columns(3)
                d1.download_button("Download alignment", aln.encode(), "woloji_alignment.fasta", "text/plain")
                d2.download_button("Download Newick tree", tree.encode(), "woloji_tree.nwk", "text/plain")
                d3.download_button("Download IQ-TREE report", log.encode(), "woloji_iqtree_report.txt", "text/plain")
        with u4:
            st.markdown("#### Output concordance (WOLOJI versus direct-tool run)")
            st.caption("Matches rows on key columns, then reports key precision, recall, F1 and value disagreements.")
            obs = st.file_uploader("WOLOJI output table (CSV/TSV)", type=["csv", "tsv", "txt", "tab"], key="cmp_obs")
            exp = st.file_uploader("Direct-tool reference table (CSV/TSV)", type=["csv", "tsv", "txt", "tab"],
                                   key="cmp_exp")
            keys = st.text_input("Key columns (comma separated)", "Sample_ID")
            tol = st.number_input("Numeric tolerance", 0.0, 1e6, 1e-8, format="%.1e")
            if st.button("Compare tables", key="run_compare"):
                if not obs or not exp:
                    st.error("Upload both tables.")
                else:
                    try:
                        st.session_state["compare"] = compare_tables(
                            read_table(io.BytesIO(obs.getvalue()), obs.name),
                            read_table(io.BytesIO(exp.getvalue()), exp.name),
                            [k.strip() for k in keys.split(",") if k.strip()], tol)
                    except Exception as exc:  # UI boundary
                        st.error(f"Comparison failed: {exc}")
            if "compare" in st.session_state:
                res = st.session_state["compare"]
                m1, m2, m3 = st.columns(3)
                fmt = lambda v: "n/a" if isinstance(v, float) and math.isnan(v) else f"{v:.3f}"  # noqa: E731
                m1.metric("Key precision", fmt(res["key_precision"]))
                m2.metric("Key recall", fmt(res["key_recall"]))
                m3.metric("Key F1", fmt(res["key_f1"]))
                st.write(f"Value disagreements: {res['value_disagreement_count']}")
                if res["value_disagreements_first_100"]:
                    st.dataframe(pd.DataFrame(res["value_disagreements_first_100"]), width="stretch",
                                 hide_index=True)
                st.download_button("Download concordance JSON",
                                   json.dumps(res, indent=2, default=str).encode(),
                                   "woloji_concordance.json", "application/json")

    # ------------------------------------------------------------------ status
    with status_tab:
        st.subheader("Installed command-line tools")
        if st.button("Refresh tool status") or "tool_status" not in st.session_state:
            st.session_state["tool_status"] = status_rows()
            st.session_state["db_status"] = database_rows()
        st.dataframe(pd.DataFrame(st.session_state["tool_status"]), width="stretch", hide_index=True)
        st.subheader("Reference database configuration")
        st.dataframe(pd.DataFrame(st.session_state["db_status"]), width="stretch", hide_index=True)
        st.info("Mount large reference databases on persistent storage (for example /data) and expose them "
                "through the environment variables shown above.")

    # -------------------------------------------------------------------- help
    with help_tab:
        st.markdown("""
### Input naming
For paired Illumina files without metadata, use names such as `Sample01_R1.fastq.gz` and `Sample01_R2.fastq.gz`
(`_1/_2` and lane suffixes such as `_R1_001` are also recognised). Unpaired FASTQ files are interpreted as long reads.
FASTA files are treated as finished assemblies. For mixed or non-standard names, use the metadata table.

### Recommended analysis modes
**Routine isolate WGS:** read QC, assembly, QUAST, taxonomy/ANI, mobileome, MLST and report.

**Comparative genomics:** analyse multiple assemblies and enable cgMLST/wgMLST and population genomics.

**Outbreak/phylogenomic analysis:** provide a reference genome, at least three isolates, and enable core SNP
phylogenomics. WOLOJI calls Snippy, snippy-core, Gubbins and IQ-TREE 2 (with +ASC on the SNP-only alignment).

### Out of scope
Genome annotation, codon usage, AMR detection, virulence screening and secondary metabolite prediction.

### Database variables
`GTDBTK_DATA_PATH`, `CHECKM2DB`, `GENOMAD_DB`, `MOB_SUITE_DB`.

### Reproducibility outputs
Every run records input SHA256 hashes, parameters, database paths, exact command lines, command logs,
software versions, assembly summary tables, figures and a methods note.
""")


# =============================================================================
# Entry point
# =============================================================================
def _running_in_streamlit() -> bool:
    try:
        from streamlit.runtime.scriptrunner import get_script_run_ctx
        return get_script_run_ctx(suppress_warning=True) is not None
    except (ImportError, TypeError):
        return False


if _running_in_streamlit():
    render_app()
elif __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "compare":
        raise SystemExit(compare_cli(sys.argv[2:]))
    print(__doc__)
    print("Start the web interface with: streamlit run app.py")