File size: 128,227 Bytes
dac3297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
"""
analyze_blueprint.py  β€”  HVAC Blueprint Analyzer

Usage:
    python analyze_blueprint.py <pdf> [--dpi 300] [--out-dir ./output]
                                      [--psm 11] [--min-conf 40]
                                      [--step schedule|classify|ocr-one]
                                      [--tile]

Run with --step <name> to stop and confirm after each phase.
"""

from __future__ import annotations

import argparse
import itertools
import logging
import re
import sys
from io import BytesIO
from pathlib import Path
from typing import NamedTuple

import base64
import csv
import io
import os

import cv2
import fitz
import numpy as np
import pdfplumber
import pytesseract
from PIL import Image, ImageDraw, ImageFont

# ── Load .env from project root ──────────────────────────────────────────────
try:
    from dotenv import load_dotenv
    load_dotenv(Path(__file__).parent.parent / ".env")
except ImportError:
    pass  # python-dotenv not installed β€” use system env vars

# ── Windows Tesseract path ────────────────────────────────────────────────────
_TESS_WIN = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
if Path(_TESS_WIN).exists():
    pytesseract.pytesseract.tesseract_cmd = _TESS_WIN

# ── Inject sibling package ────────────────────────────────────────────────────
sys.path.insert(0, str(Path(__file__).parent))
from hvac_pipeline.extract_schedule_robust import (
    RowParse,
    extract_from_pdf_tables,
    extract_from_pdf_text,
    normalize_tag as _normalize_tag_schedule,
)

# ── Regex patterns (inlined from read_mechanical_plansvs1.4.py) ───────────────
# Matches standard single-letter tags (AC-A … AC-U) plus extended formats:
#   multi-letter  : AC-LV, AC-R
#   letter+number : AC-C-1, AC-C-11
#   number+number : AC-1-1, AC-1-14, AC-2-2
_TAG_STRICT = re.compile(
    r"\bAC"
    r"[-\s]?"
    r"(?:"
    r"[A-Z]{1,3}(?:[-]\d{1,2})?"   # AC-A, AC-LV, AC-C-1, AC-C-11
    r"|"
    r"\d{1,2}(?:[-]\d{1,2})?"       # AC-1, AC-1-1, AC-1-14
    r")\b",
    re.IGNORECASE,
)
_TAG_LOOSE = re.compile(r"\bA\s*C\s*[-]?\s*([A-U])\b", re.IGNORECASE)
_INT_PAT = re.compile(r"\b\d{1,2}\b")
_FLOOR_PAT = re.compile(r"(LEVEL|FLOOR|ROOF|BASEMENT)\s*(\d+)?", re.IGNORECASE)

# ── Schedule model-number / company extraction ────────────────────────────────
_MODEL_NUMBER_PAT = re.compile(
    r"\b("
    r"(?:FX|RX|RZ)[A-Z]{1,3}Q?\d{2,3}[A-Z]{2,8}"  # Daikin VRV/VRF (FXAQ, FXSQ, RXTQ …)
    r"|MSZ[-\s]?[A-Z]{2,4}[-\s]?\d{2,3}[A-Z]*"     # Mitsubishi MSZ wall-mount
    r"|(?:SEZ|MFZ|MLZ|PEFY|PKFY|PLFY|PMFY|PCFY)[-\s]?[A-Z0-9]{3,12}"  # Mitsubishi others
    r")\b",
    re.IGNORECASE,
)
_COMPANY_PAT = re.compile(r"\b(DAIKIN|DAIK|MITSUBISHI|MITS)\b", re.IGNORECASE)

# ── Annotation color palette ──────────────────────────────────────────────────
_PALETTE = [
    (220, 50, 50),
    (50, 150, 220),
    (50, 200, 100),
    (220, 150, 50),
    (150, 50, 220),
    (50, 200, 200),
    (220, 220, 50),
    (200, 100, 150),
    (100, 200, 50),
    (50, 100, 200),
    (200, 50, 150),
    (100, 150, 50),
]

# ── Data types ────────────────────────────────────────────────────────────────
class TagHit(NamedTuple):
    tag: str
    x: int
    y: int
    w: int
    h: int
    conf: float
    fuzzy: bool


FloorResults = dict[str, dict[str, list[TagHit]]]


# ─────────────────────────────────────────────────────────────────────────────
# Helpers inlined from read_mechanical_plansvs1.4.py
# ─────────────────────────────────────────────────────────────────────────────

def _extract_explicit_title(text: str) -> str | None:
    if not text:
        return None
    lines = [ln.strip() for ln in text.split("\n")]
    for i, line in enumerate(lines):
        if re.search(r"DRAWING\s*TITLE", line, re.IGNORECASE):
            remainder = re.sub(r"DRAWING\s*TITLE\s*[:\-]?\s*", "", line, flags=re.IGNORECASE)
            if remainder:
                return remainder.strip()
            for nxt in lines[i + 1 : i + 6]:
                if nxt:
                    return nxt.strip()
    return None


_SCHEDULE_TITLE_PAT = re.compile(
    r"\b("
    r"INDOOR\s+UNITS?|"
    r"INDOOR\s+FAN\s+COILS?|"
    r"FAN\s+COIL\s+UNITS?|"
    r"VR[FV]\s+INDOOR|"
    r"EQUIPMENT\s+SCHEDULE|"
    r"UNIT\s+SCHEDULE|"
    r"MECHANICAL\s+SCHEDULE|"
    r"MECHANICAL\s+EQUIPMENT|"
    r"HEAT\s+PUMP\s+SCHEDULE|"
    r"SPLIT\s+SYSTEM\s+SCHEDULE"
    r")\b",
    re.IGNORECASE,
)

_SCHEDULE_BODY_PAT = re.compile(
    r"\b("
    r"INDOOR\s+UNITS?|"
    r"INDOOR\s+UNIT\s+SCHEDULE|"
    r"VARIABLE\s+REFRIGERANT\s+VOLUME|"
    r"VR[FV]\s+INDOOR|"
    r"FAN\s+COIL\s+UNITS?|"
    r"HEAT\s+PUMP\s+SCHEDULE|"
    r"SPLIT\s+SYSTEM\s+SCHEDULE"
    r")\b",
    re.IGNORECASE,
)

_TITLE_KEYWORDS = re.compile(
    r"\b(MECHANICAL|HVAC|AIR\s+RISER|RISER|DIAGRAM|PLAN|SCHEDULE|DETAIL|"
    r"SECTION|BULKHEAD|CELLAR|ROOF|EQUIPMENT|INDOOR\s+UNITS?)\b",
    re.IGNORECASE,
)

def _extract_heuristic_title(text: str, max_lines: int = 20) -> str | None:
    """
    Drawing titles are almost entirely uppercase (>60% ratio).
    Scans up to max_lines lines; None = search entire text.
    When scanning the full OCR output, returns the HIGHEST-ratio matching
    line (not the first), so diagram labels ('BULKHEAD') lose to the
    actual title ('MECHANICAL AIR RISERS' at 0.90).
    Also requires at least one title keyword and no junk characters.
    """
    if not text:
        return None
    lines = [ln.strip() for ln in text.split("\n") if ln.strip()]
    search = lines if max_lines is None else lines[:max_lines]

    candidates: list[tuple[float, str]] = []
    for line in search:
        # Strip non-ASCII junk chars (common OCR artifacts) before evaluating
        clean = re.sub(r"[^\x00-\x7F]+", " ", line).strip()
        clean = re.sub(r"\s{2,}", " ", clean)
        if len(clean) < 8 or len(clean) > 120:
            continue
        upper_ratio = sum(c.isupper() for c in clean) / max(len(clean), 1)
        if upper_ratio > 0.6 and _TITLE_KEYWORDS.search(clean):
            line = clean  # use the cleaned version
            # Strongly prefer lines that start with MECHANICAL
            bonus = 0.2 if line.upper().startswith("MECHANICAL") else 0.0
            if _SCHEDULE_TITLE_PAT.search(line):
                bonus += 0.4
            candidates.append((upper_ratio + bonus, line))

    if not candidates:
        return None
    # Return highest-scoring line, stripped of leading punctuation/symbols
    best = max(candidates, key=lambda x: x[0])[1]
    return re.sub(r"^[^A-Z]+", "", best).strip()


# Strong schedule signal: the literal word SCHEDULE next to an equipment word.
# Requiring "…SCHEDULE" avoids false-positives on DETAIL/SECTION pages that merely
# mention "INDOOR UNITS" (e.g. Dean St p15 "24 MIN. TO INDOOR UNITS"). The char
# classes absorb the most common OCR misreads of these words.
_SCHEDULE_STRONG = re.compile(
    r"\b("
    r"E[OQ]UIPMENT|UNIT|INDOOR\s*UNIT|MECHANICAL|HEAT\s*PUMP|FAN\s*COIL|"
    r"CONDENSING\s*UNIT|OUTDOOR\s*UNIT|VR[FV]"
    r")\s+SCH[EO]D[UV][IL][EO]\b",
    re.IGNORECASE,
)

# Schedule signal acceptable IN A TITLE (title block / sheet title) β€” broader than
# _SCHEDULE_STRONG because a title saying "INDOOR UNITS" (without the word
# SCHEDULE) is still the indoor-unit schedule. NOT safe to run over body text,
# where "INDOOR UNIT(S)" shows up in notes ("…for each INDOOR UNIT").
_SCHEDULE_TITLE_KEYWORDS = re.compile(
    r"\b(SCH[EO]D[UV][IL][EO]|INDOOR\s+UNITS?|INDOOR\s+FAN\s+COILS?|"
    r"FAN\s+COIL\s+UNITS?|VR[FV]\s+INDOOR)\b",
    re.IGNORECASE,
)


def _ocr_page_fulltext(pdf_path: Path, page_0idx: int, dpi: int = 220) -> str:
    """OCR the whole page (multi-PSM) and return the combined text.

    Higher DPI than the old 150 (small title text reads far better at 220), and
    PSM 4 (columnar) + PSM 6 (block) together recover titles one mode misses.
    """
    doc = fitz.open(pdf_path)
    pix = doc.load_page(page_0idx).get_pixmap(
        matrix=fitz.Matrix(dpi / 72, dpi / 72), alpha=False)
    img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
    gray = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2GRAY)
    g = Image.fromarray(gray)
    parts = []
    for psm in (6, 4):
        try:
            parts.append(pytesseract.image_to_string(g, config=f"--oem 3 --psm {psm}"))
        except Exception:
            pass
    return "\n".join(parts)


def _title_from_ocr_text(ocr_txt: str) -> str | None:
    """Pick the drawing title out of already-OCR'd page text."""
    title = _extract_explicit_title(ocr_txt)
    if title and _TITLE_KEYWORDS.search(title):
        return title
    return _extract_heuristic_title(ocr_txt, max_lines=None)


def _ocr_page_title(pdf_path: Path, page_0idx: int) -> str | None:
    """Render the page, OCR it, and return the drawing title (or None)."""
    return _title_from_ocr_text(_ocr_page_fulltext(pdf_path, page_0idx))


# Sub-labels that live in the title block but are NOT the drawing title.
_TITLE_BLOCK_EXCLUDE = re.compile(
    r"\b(SITE\s+PLAN|PLAN\s+NOTES?|KEY\s+PLAN|GENERAL\s+NOTES?|"
    r"NORTH|SCALE|DRAWN|CHECKED)\b", re.IGNORECASE)

# A note / spec / callout line β€” never the drawing title. Catches things like
# "1. PROVIDE ONE 7-DAY PROGRAMMABLE THERMOSTAT FOR EACH INDOOR UNIT" that would
# otherwise score as a schedule title because they contain "INDOOR UNIT".
_NOTE_LINE = re.compile(
    r"^\s*\d+\s*[.\)]"                       # numbered note ("1.", "2)")
    r"|\b(PROVIDE|INSTALL|SHALL|THERMOSTAT|PURGE|MINIMUM|REFER\s+TO|"
    r"CONSTRUCTION|SLEEVE|CONTROL\s+PANEL|TYPICAL\s+OF|EACH\s+INDOOR)\b",
    re.IGNORECASE)


def _ocr_titleblock_text(pdf_path: Path, page_0idx: int, dpi: int = 220) -> str:
    """OCR the title-block strips (right edge + bottom) and return their text.
    These strips hold the sheet title; kept separate from the page body so the
    title scorer can give title-block lines a small boost."""
    doc = fitz.open(pdf_path)
    pix = doc.load_page(page_0idx).get_pixmap(
        matrix=fitz.Matrix(dpi / 72, dpi / 72), alpha=False)
    img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
    W, H = img.size
    out = []
    for (x0, y0, x1, y1) in [(int(0.70 * W), 0, W, H), (0, int(0.80 * H), W, H)]:
        gray = cv2.cvtColor(np.array(img.crop((x0, y0, x1, y1))), cv2.COLOR_RGB2GRAY)
        g = Image.fromarray(gray)
        for psm in (6, 4):
            try:
                out.append(pytesseract.image_to_string(g, config=f"--oem 3 --psm {psm}"))
            except Exception:
                pass
    return "\n".join(out)


def _best_ocr_title(full_text: str, tb_text: str = "") -> str | None:
    """Pick the drawing title from OCR'd text (whole page + title block).

    Scores every title-ish line and PREFERS a 'standard' drawing title β€” one that
    starts with MECHANICAL, ends with a sheet-type word (PLAN/SCHEDULE/RISERS/…),
    or carries an ordinal floor. This beats both note paragraphs (Dean St) and
    stray floor-key legends in the title block (355 'CELLAR FLOOR'), without
    caring where on the sheet the title sits.
    """
    scored: dict[str, int] = {}

    def consider(line: str, in_tb: bool):
        s = re.sub(r"[^\x00-\x7F]+", " ", line)
        s = re.sub(r"\s{2,}", " ", s).strip()
        # Titles are short; note/spec lines are long sentences. 55 keeps the
        # longest real titles ("…TYPICAL 13TH THRU 14TH FLOOR PLAN" β‰ˆ 44).
        if not (6 <= len(s) <= 55) or _TITLE_BLOCK_EXCLUDE.search(s) \
                or _NOTE_LINE.search(s):
            return
        if sum(c.isupper() for c in s) / max(len(s), 1) < 0.5:
            return
        su = s.upper()
        if not (_TITLE_KEYWORDS.search(su) or _SCHEDULE_TITLE_KEYWORDS.search(su)):
            return
        sc = 1
        std = _is_standard_title(s)
        if std:
            sc += 6                       # a real sheet title beats notes & floor-keys
        if _SCHEDULE_TITLE_KEYWORDS.search(su):
            sc += 4
        if std and _FLOOR_DESIG_PAT.search(su):
            sc += 2                       # prefer the floor-specific standard title
        if in_tb:
            sc += 1
        scored[s] = scored.get(s, 0) + sc

    for ln in (full_text or "").splitlines():
        consider(ln, False)
    for ln in (tb_text or "").splitlines():
        consider(ln, True)
    if not scored:
        return None
    return max(scored.items(), key=lambda kv: kv[1])[0]


_JUNK_TITLE = re.compile(r"^(DOB\s*[#:\-]|N/A|TBD|NONE|\-+|\s*)$", re.IGNORECASE)

def _is_valid_title(title: str | None) -> bool:
    """Return False for placeholder/form-field titles that aren't real drawing titles."""
    if not title:
        return False
    if _JUNK_TITLE.match(title.strip()):
        return False
    return bool(_TITLE_KEYWORDS.search(title))

def _extract_page_title(text: str) -> str | None:
    title = _extract_explicit_title(text) or _extract_heuristic_title(text)
    return title if _is_valid_title(title) else None


def _classify_page_context(title: str | None, text: str) -> str:
    t = (title or "").upper()
    x = (text or "").upper()
    # Schedule: require the literal word SCHEDULE in the title (every real
    # schedule sheet's title block says "...SCHEDULE"). The old rule also fired
    # on a bare "INDOOR UNIT(S)", which wrongly tagged plan sheets whose notes
    # say "...for each INDOOR UNIT" as schedules.
    # Schedule when the TITLE says SCHEDULE or INDOOR UNIT(S)/FAN COIL β€” title
    # text is safe to match broadly (notes live in the body, not the title).
    if _SCHEDULE_TITLE_KEYWORDS.search(t):
        return "schedule"
    # Cover/index/title sheet β€” generic, no specific floor. Exact-match guard so
    # a real "<FLOOR> MECHANICAL PLAN" is never swallowed.
    if (any(k in t for k in ("COVER", "INDEX", "TITLE SHEET"))
            or t.strip() in ("MECHANICAL PLANS", "MECHANICAL PLAN", "MECHANICAL")):
        return "other"
    if "SPECIFICATION" in t or ("NOTE" in t and "PLAN" not in t):
        return "notes"
    # A floor-PLAN title (has both FLOOR and PLAN) wins over a stray SECTION /
    # DETAIL callout that the title block may also contain.
    if "FLOOR" in t and "PLAN" in t:
        return "plan"
    # Details, DOB forms, and riser diagrams are not floor plans
    if "DETAIL" in t or "SECTION" in t or "RISER" in t or "DIAGRAM" in t:
        return "detail"
    if ("PLAN" in t or "FLOOR" in t or "LEVEL" in t or "ROOF" in t or
            "CELLAR" in t or "BULKHEAD" in t or "PENTHOUSE" in t or
            "MEZZANINE" in t):
        return "plan"
    # Image-only schedule whose title block didn't OCR a usable title β€” fall
    # back to a STRONG body signal (word SCHEDULE beside an equipment word).
    # Only when there's no title at all, so a specs/notes sheet that merely
    # references a schedule isn't itself called a schedule.
    if not t and _SCHEDULE_STRONG.search(x):
        return "schedule"
    return "other"


def _normalize_tag(raw: str) -> str | None:
    """Return normalized tag form or None.

    Accepted output formats:
      AC-A … AC-U   (single letter)
      AC-LV         (multi-letter special tags)
      AC-C-1        (letter + dash + number, e.g. AC-C-1 … AC-C-11)
      AC-1-1        (digit + dash + digit, e.g. AC-1-1 … AC-1-14)
    """
    # Uppercase, collapse whitespace β†’ dashes, strip anything that isn't
    # alphanumeric or dash, collapse double-dashes, trim leading/trailing dashes.
    cleaned = raw.upper().strip()
    cleaned = re.sub(r"\s+", "-", cleaned)
    cleaned = re.sub(r"[^A-Z0-9\-]", "", cleaned)
    cleaned = re.sub(r"-{2,}", "-", cleaned).strip("-")

    # Extract the "rest" after the AC prefix
    if cleaned.startswith("AC-"):
        rest = cleaned[3:]
    elif cleaned.startswith("AC") and len(cleaned) > 2:
        rest = cleaned[2:]
    else:
        return None

    # Validate: 1–3 uppercase letters (optionally followed by -NN)
    #           OR 1–2 digits (optionally followed by -NN)
    if (re.match(r"^[A-Z]{1,3}(?:-\d{1,2})?$", rest) or
            re.match(r"^\d{1,2}(?:-\d{1,2})?$", rest)):
        return f"AC-{rest}"
    return None


def _parse_schedule_lines_robust(lines: list[str], page_num: int) -> list[dict]:
    rows: list[dict] = []
    seen: set = set()
    for line in lines:
        upper = line.upper()
        tag = None
        m = _TAG_STRICT.search(upper)
        if m:
            tag = _normalize_tag(m.group(0))
        if tag is None:
            m2 = _TAG_LOOSE.search(upper)
            if m2:
                tag = f"AC-{m2.group(1).upper()}"
        if tag is None:
            m3 = re.search(r"\bAC[-\s]?([A-U])\w*\b", upper)
            if m3:
                tag = f"AC-{m3.group(1).upper()}"
        if not tag:
            continue

        # Model number: search after the tag position so we don't grab
        # model-like strings that precede the tag in garbled OCR lines.
        tag_end = (m or m2 or m3).end() if (m or m2 or m3) else 0
        model_match = _MODEL_NUMBER_PAT.search(line, tag_end)
        model_number = model_match.group(1).upper() if model_match else ""

        # Company from manufacturer keyword anywhere in the line
        company_match = _COMPANY_PAT.search(upper)
        company_raw = company_match.group(1).upper() if company_match else ""
        if company_raw in ("DAIKIN", "DAIK"):
            company = "Daikin"
        elif company_raw in ("MITSUBISHI", "MITS"):
            company = "Mitsubishi"
        else:
            company = ""

        # Qty: first 1-2 digit integer that follows the model number (avoids
        # picking up capacity numbers like 12,000 or voltage like 208).
        search_start = model_match.end() if model_match else tag_end
        nums = [int(v) for v in _INT_PAT.findall(line[search_start:])]
        qty = next((n for n in nums if 1 <= n <= 50), None)
        if qty is None:
            # Fallback: scan the whole line
            nums_all = [int(v) for v in _INT_PAT.findall(line)]
            qty = next((n for n in nums_all if 1 <= n <= 50), None)

        if "CEILING" in upper and "DUCT" in upper:
            utype = "Ceiling Concealed Ducted Unit"
        elif "WALL" in upper and "MOUNT" in upper:
            utype = "Wall Mounted"
        else:
            utype = ""

        key = (tag, str(qty), model_number)
        if key in seen:
            continue
        seen.add(key)
        rows.append({
            "page_num": page_num, "tag": tag, "qty_required": qty,
            "unit_type": utype, "model_number": model_number, "company": company,
        })
    return rows


# ─────────────────────────────────────────────────────────────────────────────
# Step 1 β€” Schedule extraction
# ─────────────────────────────────────────────────────────────────────────────

# ─────────────────────────────────────────────────────────────────────────────
# Gemini vision fallback for schedule extraction
# ─────────────────────────────────────────────────────────────────────────────

def _extract_schedule_via_gemini(pil_img: Image.Image) -> list[RowParse]:
    """
    Send the schedule page image to Gemini and ask it to return the
    INDOOR UNIT SCHEDULE table as CSV.  Returns [] if API key not set.
    """
    api_key = os.environ.get("GEMINI_API_KEY", "")
    if not api_key:
        print("  [INFO] GEMINI_API_KEY not set β€” skipping vision fallback.")
        print("         Set it with:  $env:GEMINI_API_KEY = 'your-key-here'")
        return []

    try:
        from google import genai as google_genai
        from google.genai import types as genai_types
    except ImportError:
        print("  [INFO] google-genai not installed β€” run: pip install google-genai")
        return []

    client = google_genai.Client(api_key=api_key)

    buf = io.BytesIO()
    pil_img.save(buf, format="PNG")
    img_bytes = buf.getvalue()

    prompt = (
        "Look at this HVAC mechanical blueprint page. It contains MULTIPLE tables: an outdoor "
        "unit schedule, an indoor unit schedule, fan schedules, and possibly others β€” all on the "
        "same page.\n\n"
        "YOUR TASK: Extract ONLY rows from the INDOOR UNIT SCHEDULE table (also labelled "
        "'VARIABLE REFRIGERANT VOLUME – INDOOR UNIT SCHEDULE' or similar).\n\n"
        "IMPORTANT: The indoor unit schedule may be split into several sub-sections on this page "
        "(for example: apartment units, commercial/building units, corridor units). "
        "Extract every row from EVERY sub-section of the indoor unit schedule.\n\n"
        "Return the data as CSV with exactly these 5 columns: tag,qty,unit_type,model_number,company\n\n"
        "Rules:\n"
        "- tag must exactly reproduce the tag shown in the schedule. Accepted formats:\n"
        "    Single letter  : AC-A, AC-B … AC-U\n"
        "    Multi-letter   : AC-LV, AC-R\n"
        "    Letter+number  : AC-C-1, AC-C-2 … AC-C-11\n"
        "    Number+number  : AC-1-1, AC-1-2 … AC-1-14  or  AC-2-1, AC-2-2\n"
        "- qty must be an integer (the QUANTITY column value)\n"
        "- unit_type should be the TYPE column value (e.g. CEILING CONCEALED DUCTED UNIT, "
        "WALL MOUNTED UNIT); leave blank if not shown\n"
        "- model_number should be the manufacturer part/model number "
        "(e.g. FXSQ48TAVJU, FXAQ09PVJU, MSZ-FX12NA); leave blank if not shown\n"
        "- company should be the manufacturer/brand name (e.g. Daikin, Mitsubishi); leave blank "
        "if not shown\n"
        "- Do NOT include commas inside any field value\n"
        "- Do NOT extract rows from the outdoor unit schedule, fan schedule, exhaust fan "
        "schedule, or any other non-indoor-unit table\n"
        "- Include ALL rows from all sub-sections of the indoor unit schedule, even qty=0 rows\n"
        "- Output ONLY the CSV rows β€” no header row, no explanations, no markdown."
    )

    try:
        response = client.models.generate_content(
            model="gemini-2.5-flash",
            contents=[
                prompt,
                genai_types.Part.from_bytes(data=img_bytes, mime_type="image/png"),
            ],
            config=genai_types.GenerateContentConfig(max_output_tokens=4096, temperature=0.0),
        )
    except Exception as e:
        print(f"  [WARNING] Gemini schedule call failed ({e}) β€” continuing with OCR results only.")
        print("            Check GEMINI_API_KEY in .env (get a key at https://aistudio.google.com/apikey)")
        return []

    rows: list[RowParse] = []
    for line in response.text.strip().splitlines():
        line = line.strip().strip(",")
        if not line:
            continue
        # Split on first 4 commas so remaining fields don't overflow into model_number/company
        parts = [p.strip() for p in line.split(",", 4)]
        if len(parts) < 2:
            continue
        tag = _normalize_tag(parts[0])
        if not tag:
            continue
        try:
            qty = int(parts[1])
        except ValueError:
            qty = None
        utype = parts[2] if len(parts) > 2 else ""
        model_number = parts[3] if len(parts) > 3 else ""
        company = parts[4] if len(parts) > 4 else ""
        rows.append(RowParse(
            tag=tag,
            qty_required=qty,
            unit_type=utype,
            confidence=0.95,
            source="gemini_vision",
            raw_text=line,
            model_number=model_number,
            company=company,
        ))
    return rows


_INDOOR_HEADER = re.compile(
    r"\b("
    r"INDOOR\s+UNIT\s+SCHEDULE|"
    r"INDOOR\s+UNITS?|"
    r"INDOOR\s+FAN\s+COILS?|"
    r"FAN\s+COIL\s+UNITS?|"
    r"VR[FV]\s+INDOOR"
    r")\b",
    re.IGNORECASE,
)
_OTHER_SCHEDULE = re.compile(r"(OUTDOOR|CONDENSING|EQUIPMENT|ELECTRICAL)\s+(UNIT\s+)?SCHEDULE", re.IGNORECASE)


def _extract_indoor_unit_section(lines: list[str]) -> list[str]:
    """
    Return only the lines that belong to the INDOOR UNIT SCHEDULE table.
    Starts at the header line and stops when another schedule header appears
    or when a line that looks like end-of-table notes begins.
    If no header is found, return all lines (best-effort).
    """
    start = None
    for i, line in enumerate(lines):
        if _INDOOR_HEADER.search(line):
            start = i
            break

    if start is None:
        return lines  # header not found β€” return everything, parser will filter

    result = []
    for line in lines[start:]:
        # Stop at a different schedule section
        if result and _OTHER_SCHEDULE.search(line):
            break
        # Stop at indoor unit notes block
        if result and re.match(r"INDOOR\s+UNIT\s+NOTES", line, re.IGNORECASE):
            break
        result.append(line)
    return result

def _schedule_cache_path(pdf_path: Path, out_dir: Path) -> Path:
    return out_dir / f"{pdf_path.stem}_schedule_cache.json"


def _load_schedule_cache(cache_path: Path) -> dict[str, dict] | None:
    if not cache_path.exists():
        return None
    import json
    data = json.loads(cache_path.read_text(encoding="utf-8"))
    print(f"  Loaded schedule from cache: {cache_path}")
    print(f"  (Delete that file or use --refresh-schedule to re-extract)")
    return data


def _save_schedule_cache(schedule: dict[str, dict], cache_path: Path) -> None:
    import json
    cache_path.write_text(json.dumps(schedule, indent=2), encoding="utf-8")
    print(f"  Schedule cached to: {cache_path}")


def extract_schedule(pdf_path: Path, dpi: int, schedule_page: int | None = None,
                     out_dir: Path | None = None, refresh: bool = False,
                     region: tuple[float, float, float, float] | None = None) -> dict[str, dict]:
    """
    Returns {tag: {"unit_type": str, "qty": int|None}} for all found tags.
    Tries three tiers: pdf tables β†’ pdf text β†’ OCR β†’ Gemini vision.
    Results are cached to <out_dir>/<pdf_stem>_schedule_cache.json so the
    API is only called once. Use --refresh-schedule to force re-extraction.

    region: optional (x0, y0, x1, y1) as 0-1 fractions of the page. When given
    (with schedule_page), only that rectangle is read β€” the user has drawn a box
    around the schedule table in the GUI. Forces a fresh extract (skips cache).
    """
    if region is not None:
        refresh = True   # a hand-drawn region always re-extracts
    # ── Cache check ───────────────────────────────────────────────────────────
    if out_dir is not None:
        cache_path = _schedule_cache_path(pdf_path, out_dir)
        if not refresh:
            cached = _load_schedule_cache(cache_path)
            if cached is not None:
                return cached

    schedule_pages: list[int] = []

    if schedule_page is not None:
        schedule_pages = [schedule_page]
        print(f"  Using specified schedule page: {schedule_page}")
    else:
        # Search only first 15 + last 15 pages (schedules are rarely in the middle)
        with pdfplumber.open(pdf_path) as pdf:
            total = len(pdf.pages)
            candidates_idx = sorted(set(
                list(range(1, min(16, total + 1))) +
                list(range(max(1, total - 14), total + 1))
            ))
            print(f"  Scanning {len(candidates_idx)} pages (of {total} total) for schedule…")
            # Phase 1 (sequential, cheap): native text extraction + classify.
            # pdfplumber isn't thread-safe to share across threads, and text
            # extraction is fast, so do it in one pass and note which pages still
            # need an OCR title check (the slow part).
            need_ocr: list[int] = []
            page_txt: dict[int, str] = {}
            for i in candidates_idx:
                print(f"    page {i}/{total}…", end="\r", flush=True)
                txt = pdf.pages[i - 1].extract_text() or ""
                page_txt[i] = txt
                title = _extract_page_title(txt)
                ptype = _classify_page_context(title, txt)
                if ptype == "schedule":
                    schedule_pages.append(i)
                    continue
                needs_ocr_schedule_hint = (
                    not title
                    or len(txt.strip()) < 500
                    or bool(_SCHEDULE_BODY_PAT.search(txt))
                )
                if needs_ocr_schedule_hint:
                    need_ocr.append(i)
            print()  # clear the \r line

            # Phase 2 (parallel): OCR the page titles. Tesseract runs as a
            # subprocess (releases the GIL) and each call opens its own PDF
            # handle, so several pages OCR at once β€” same result, far less wait.
            if need_ocr:
                workers = max(1, int(os.environ.get("HVAC_TILE_WORKERS", "4")))
                print(f"    OCR-checking {len(need_ocr)} page title(s) "
                      f"({workers} at a time)…", flush=True)
                from concurrent.futures import ThreadPoolExecutor

                def _ocr_check(i):
                    # Image-only schedule sheets have no native text. Two signals:
                    #  (a) the STRONG word "SCHEDULE" beside an equipment word
                    #      anywhere on the page (e.g. Dean St p16 "EQUIPMENT
                    #      SCHEDULE"), and
                    #  (b) the TITLE BLOCK saying SCHEDULE / INDOOR UNIT(S) β€” this
                    #      catches a schedule titled "INDOOR UNITS" with no
                    #      "SCHEDULE" word, WITHOUT tripping on DETAIL/SECTION
                    #      pages whose BODY says "INDOOR UNITS" (p15), since we
                    #      only read the title block here, not the notes.
                    try:
                        full = _ocr_page_fulltext(pdf_path, i - 1)
                    except Exception:
                        return i, False
                    if _SCHEDULE_STRONG.search(full):
                        return i, True
                    tb = _ocr_titleblock_text(pdf_path, i - 1)
                    title = _best_ocr_title(full, tb) or ""
                    return i, bool(_SCHEDULE_TITLE_KEYWORDS.search(title))

                with ThreadPoolExecutor(max_workers=workers) as ex:
                    for i, is_sched in ex.map(_ocr_check, need_ocr):
                        if is_sched:
                            schedule_pages.append(i)
                schedule_pages.sort()

    if not schedule_pages:
        print("  [WARNING] No schedule page found in first/last 15 pages.")
        print("  Tip: run with --schedule-page N to specify the exact page number.")
        return {}

    candidates: list[RowParse] = []
    for pnum in schedule_pages:
        logging.info(f"  Trying schedule on page {pnum}…")

        # ── Hand-drawn region: read ONLY the boxed rectangle ──────────────────
        # The user pointed at the schedule and drew a box around the table, so
        # skip the page-wide native tiers and OCR + Gemini-vision just the crop.
        if region is not None:
            rx0, ry0, rx1, ry1 = region
            ocr_dpi = 250
            doc = fitz.open(pdf_path)
            page_obj = doc.load_page(pnum - 1)
            mat = fitz.Matrix(ocr_dpi / 72.0, ocr_dpi / 72.0)
            pix = page_obj.get_pixmap(matrix=mat, alpha=False)
            full = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
            W, H = full.size
            box = (int(rx0 * W), int(ry0 * H), int(rx1 * W), int(ry1 * H))
            crop = full.crop(box)
            print(f"  Reading hand-drawn schedule region on page {pnum}: "
                  f"{box} of {W}x{H}px")

            gray = cv2.cvtColor(np.array(crop), cv2.COLOR_RGB2GRAY)
            ocr_img = Image.fromarray(gray)
            raw_lines = []
            for psm in (4, 6):
                txt = pytesseract.image_to_string(ocr_img, config=f"--oem 3 --psm {psm}")
                raw_lines.extend(ln.strip() for ln in txt.splitlines() if ln.strip())
            lines = _extract_indoor_unit_section(raw_lines)
            for row in _parse_schedule_lines_robust(lines, pnum):
                candidates.append(RowParse(
                    tag=row["tag"], qty_required=row["qty_required"],
                    unit_type=row["unit_type"], confidence=0.6,
                    source="region_ocr", raw_text="",
                    model_number=row.get("model_number", ""),
                    company=row.get("company", "")))
            # Gemini vision on the crop β€” best for an arbitrary boxed table.
            vision_rows = _extract_schedule_via_gemini(crop)
            if vision_rows:
                print(f"  Gemini returned {len(vision_rows)} rows from the region.")
                candidates.extend(vision_rows)
            continue

        t1 = extract_from_pdf_tables(pdf_path, pnum)
        t2 = extract_from_pdf_text(pdf_path, pnum)
        candidates.extend(t1)
        candidates.extend(t2)

        # Tier 3: OCR fallback when native text yields nothing
        if not t1 and not t2:
            logging.info(f"  Native extraction empty β€” falling back to OCR on page {pnum}")
            # 250 DPI β€” frombytes() bypasses PIL bomb check so large sheets are fine
            ocr_dpi = 250
            doc = fitz.open(pdf_path)
            page_obj = doc.load_page(pnum - 1)
            mat = fitz.Matrix(ocr_dpi / 72.0, ocr_dpi / 72.0)
            pix = page_obj.get_pixmap(matrix=mat, alpha=False)
            pil_img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)

            # Convert to grayscale β€” NO adaptive threshold for schedules.
            # Blueprint tables are already high-contrast; thresholding destroys
            # thin characters and causes "AC-A" to read as "sk" / "face".
            np_img = np.array(pil_img)
            gray = cv2.cvtColor(np_img, cv2.COLOR_RGB2GRAY)
            ocr_img = Image.fromarray(gray)

            # PSM 4 = single column variable-size text (best for table rows)
            # PSM 6 = uniform block (backup)
            raw_lines: list[str] = []
            for psm in (4, 6):
                txt = pytesseract.image_to_string(ocr_img, config=f"--oem 3 --psm {psm}")
                raw_lines.extend(ln.strip() for ln in txt.splitlines() if ln.strip())

            # Filter to the INDOOR UNIT SCHEDULE section only.
            # Find the header line then stop at the next all-caps schedule header.
            lines = _extract_indoor_unit_section(raw_lines)
            logging.info(f"  OCR produced {len(raw_lines)} lines; {len(lines)} in indoor unit section")
            print(f"\n  --- Indoor unit section lines ({len(lines)}) ---")
            for ln in lines:
                print(f"    {repr(ln)}")
            print(f"  --- end ---\n")

            for row in _parse_schedule_lines_robust(lines, pnum):
                candidates.append(
                    RowParse(
                        tag=row["tag"],
                        qty_required=row["qty_required"],
                        unit_type=row["unit_type"],
                        confidence=0.6,
                        source="ocr_fallback",
                        raw_text="",
                        model_number=row.get("model_number", ""),
                        company=row.get("company", ""),
                    )
                )

            # Trigger Gemini if we have few tags OR any tags are missing their type.
            # OCR text parsing reliably finds tags but rarely extracts model numbers,
            # so unit_type is usually blank even when tag count is high.
            ocr_tag_count = len({c.tag for c in candidates})
            missing_type = {c.tag for c in candidates if not c.unit_type}
            if ocr_tag_count < 5 or missing_type:
                reason = (
                    f"only {ocr_tag_count} tag(s)" if ocr_tag_count < 5
                    else f"{len(missing_type)} tag(s) missing unit type"
                )
                print(f"  {reason} β€” trying Gemini vision fallback…")
                vision_rows = _extract_schedule_via_gemini(pil_img)
                if vision_rows:
                    print(f"  Gemini returned {len(vision_rows)} rows.")
                    candidates.extend(vision_rows)

    # Deduplicate: keep highest-confidence parse per tag
    by_tag: dict[str, RowParse] = {}
    for row in candidates:
        if row.tag not in by_tag or row.confidence > by_tag[row.tag].confidence:
            by_tag[row.tag] = row

    result = {
        tag: {
            "unit_type": row.unit_type,
            "qty": row.qty_required,
            "model_number": row.model_number,
            "company": row.company,
        }
        for tag, row in by_tag.items()
        if row.qty_required is not None or row.unit_type
    }

    # Fill in missing unit types via Excel lookup
    for tag, info in result.items():
        if not info["unit_type"] and info.get("model_number"):
            looked_up = _lookup_unit_type(info.get("company", ""), info["model_number"])
            if looked_up:
                info["unit_type"] = looked_up
                print(f"  Resolved unit type for {tag} via Excel lookup: {looked_up}"
                      f"  (model: {info['model_number']})")

    # Save to cache so Gemini is never called again for this PDF
    if out_dir is not None and result:
        _save_schedule_cache(result, _schedule_cache_path(pdf_path, out_dir))

    return result


# ─────────────────────────────────────────────────────────────────────────────
# Step 2 β€” Page classification
# ─────────────────────────────────────────────────────────────────────────────

# A floor designation, found ANYWHERE in the title β€” robust to word order. Handles
# both "MECHANICAL 4TH FLOOR PLAN" and "7TH FLOOR MECHANICAL PLAN" (Dean St style),
# plus named levels and typical-floor ranges.
_FLOOR_DESIG_PAT = re.compile(
    r"\b("
    r"SUB[\s-]?CELLAR|CELLAR|BASEMENT|"
    r"GROUND(?:\s+FLOOR)?|"
    r"ROOF|BULKHEAD|PENTHOUSE|MEZZANINE|"
    r"(?:TYPICAL\s+)?\d{1,2}(?:ST|ND|RD|TH)?"
    r"(?:\s*(?:THRU|TO|-|&|/)\s*\d{1,2}(?:ST|ND|RD|TH)?)?\s*FLOOR"
    r")\b",
    re.IGNORECASE,
)


def _floor_name_from_title(title: str | None) -> str | None:
    """
    Pull a human-readable floor label out of a page title, wherever it sits.
      'MECHANICAL 4TH FLOOR PLAN'                 -> '4th Floor'
      '7TH FLOOR MECHANICAL PLAN'                 -> '7th Floor'   (Dean St order)
      'MECHANICAL TYPICAL 4TH THRU 5TH FLOOR PLAN'-> 'Typical 4th-5th Floor'
      'MECHANICAL ROOF PLAN'                      -> 'Roof'
      'MECHANICAL CELLAR PLAN'                    -> 'Cellar'
      'BULKHEAD MECHANICAL PLAN'                  -> 'Bulkhead'
    Returns None when no floor designation is present (e.g. a cover/index sheet).
    """
    if not title:
        return None
    m = _FLOOR_DESIG_PAT.search(title.upper())
    if not m:
        return None
    desig = m.group(1)
    desig = re.sub(r"\s*(?:THRU|TO|&|/)\s*", "-", desig)        # range -> 4TH-5TH
    desig = re.sub(r"\s*-\s*", "-", desig)
    desig = re.sub(r"\s{2,}", " ", desig).strip().title()
    # title() capitalizes ordinal suffixes ('7Th'); fix them back to '7th'
    desig = re.sub(r"\b(\d+)(St|Nd|Rd|Th)\b",
                   lambda mm: mm.group(1) + mm.group(2).lower(), desig)
    return desig


# A native title is "strong" (a real sheet title we can trust as-is) when it has
# the word PLAN/SCHEDULE or an ordinal floor designation. A note that merely
# contains a bare "ROOF"/"CELLAR" (e.g. "ROOF OVER CELLAR PARKING GARAGE BELOW")
# is NOT strong, so we fall back to the title block for those.
_ORDINAL_FLOOR_PAT = re.compile(
    r"\b(?:TYPICAL\s+)?\d{1,2}(?:ST|ND|RD|TH)?"
    r"(?:\s*(?:THRU|TO|-|&|/)\s*\d{1,2}(?:ST|ND|RD|TH)?)?\s*FLOOR\b",
    re.IGNORECASE,
)

# A native title is "standard" β€” a real drawing title we trust as-is β€” when it
# starts with MECHANICAL, ends with a sheet-type word (PLAN/SCHEDULE/RISERS/
# DETAILS/…), or contains an ordinal floor. A note that merely mentions a floor
# word in prose ("ROOF OVER CELLAR PARKING GARAGE BELOW") is NOT standard, so
# those pages fall through to the title-block OCR.
_SHEET_TYPE_END = re.compile(
    r"\b(PLANS?|SCHEDULES?|RISERS?|DETAILS?|DIAGRAMS?|SECTIONS?|"
    r"SPECIFICATIONS?|NOTES?|LEGEND)\s*$", re.IGNORECASE)


def _is_standard_title(s: str) -> bool:
    """A real drawing title β€” NOT a note/callout that merely ends in 'PLAN'.
    A bare '…UP ON PLAN' or floor-key 'CELLAR' is not standard; a floor title
    with PLAN, a MECHANICAL sheet, a schedule, or a detail/riser is."""
    u = s.upper().strip()
    if u.startswith("MECHANICAL"):
        return True
    if "MECHANICAL PLAN" in u or "MECHANICAL SCHEDULE" in u:
        return True
    if _SCHEDULE_TITLE_KEYWORDS.search(u):
        return True
    if re.search(r"\b(RISERS?|DIAGRAMS?|DETAILS?|SECTIONS?)\b", u):
        return True
    if _FLOOR_DESIG_PAT.search(u) and "PLAN" in u:    # "<floor> … PLAN"
        return True
    return False


def _classify_one_page(pdf_path: Path, i: int, txt: str) -> dict:
    """Classify a single page. Trusts the native (vector-text) drawing title when
    it's a standard sheet title β€” keeping crisp sets like 355 fast and unchanged.
    Only when the native title is missing or is a prose note (e.g. Dean St p5
    "ROOF OVER CELLAR…" on the 2nd-floor plan) does it OCR the TITLE BLOCK strip,
    which is far cleaner than whole-page OCR (that kept mistaking notes for the
    title)."""
    native = _extract_page_title(txt)

    body = txt
    if native and _is_standard_title(native):
        title = native                                   # crisp native title β€” trust it
    else:
        # Missing or prose native title (image-only / flattened sheet): OCR both
        # the whole page and the title block, then pick the best STANDARD title.
        full = _ocr_page_fulltext(pdf_path, i - 1)
        tb = _ocr_titleblock_text(pdf_path, i - 1)
        title = _best_ocr_title(full, tb) or native
        body = full                                      # for image-only schedule fallback

    ptype = _classify_page_context(title, body)

    # Floor name comes ONLY from the (clean) title β€” never from a whole-page
    # scan, which used to pick up a stray "ROOF"/"2ND FLOOR" from a note.
    floor_name = _floor_name_from_title(title)
    if not floor_name:
        m = _FLOOR_PAT.search(txt)
        floor_name = m.group(0).title().strip() if m else f"Page {i}"

    return {"page_num": i, "page_type": ptype, "floor_name": floor_name,
            "title": title or "(no title)"}


def classify_pages(pdf_path: Path) -> list[dict]:
    """
    Returns list of {page_num, page_type, floor_name, title} for every page.

    The per-page OCR fallback (image-only sheets) dominates the cost, so pages
    are classified concurrently β€” Tesseract runs as a subprocess and each call
    opens its own PDF handle. Native text extraction is done first in one pass
    (pdfplumber isn't thread-safe to share).
    """
    from concurrent.futures import ThreadPoolExecutor
    with pdfplumber.open(pdf_path) as pdf:
        total = len(pdf.pages)
        texts = [(i, pdf.pages[i - 1].extract_text() or "")
                 for i in range(1, total + 1)]

    workers = max(1, int(os.environ.get("HVAC_TILE_WORKERS", "4")))
    print(f"    classifying {total} pages ({workers} at a time)…", flush=True)
    manifest: list[dict] = []
    with ThreadPoolExecutor(max_workers=workers) as ex:
        for entry in ex.map(lambda it: _classify_one_page(pdf_path, it[0], it[1]), texts):
            manifest.append(entry)
    manifest.sort(key=lambda e: e["page_num"])
    return manifest


# ─────────────────────────────────────────────────────────────────────────────
# Step 3 β€” Gemini vision floor detection + YOLO label export
# ─────────────────────────────────────────────────────────────────────────────

# All 21 possible tag classes in order β€” used for YOLO class IDs
_ALL_TAGS = [f"AC-{chr(65+i)}" for i in range(21)]
_TAG_TO_CLASS = {tag: i for i, tag in enumerate(_ALL_TAGS)}

_DATASET_ROOT = Path(__file__).parent.parent / "dataset"
_UNIT_LOOKUP_XLSX = Path(__file__).parent.parent / "Mitsubishi_Daikin_Indoor_HVAC_Units_v1.xlsx"

# ── Unit-type Excel lookup ─────────────────────────────────────────────────────

_unit_lookup_rows: list[dict] | None = None


def _get_unit_lookup_rows(excel_path: Path = _UNIT_LOOKUP_XLSX) -> list[dict]:
    """Load and cache rows from the All Indoor Units sheet."""
    global _unit_lookup_rows
    if _unit_lookup_rows is not None:
        return _unit_lookup_rows
    if not excel_path.exists():
        logging.warning(f"Unit lookup Excel not found: {excel_path}")
        _unit_lookup_rows = []
        return _unit_lookup_rows
    try:
        import pandas as pd
        df = pd.read_excel(excel_path, sheet_name="All Indoor Units", header=2)
        df = df.dropna(subset=[df.columns[0]])
        _unit_lookup_rows = df.to_dict("records")
    except Exception as e:
        logging.warning(f"Could not load unit lookup Excel: {e}")
        _unit_lookup_rows = []
    return _unit_lookup_rows


def _lookup_unit_type(company: str, model_number: str,
                      excel_path: Path = _UNIT_LOOKUP_XLSX) -> str:
    """
    Return unit type by matching brand + model-number prefix against the Excel
    reference sheet.  Tries series-prefix match first, then example-model prefix.
    Returns empty string when no match is found.
    """
    model_upper = model_number.strip().upper()
    if not model_upper:
        return ""

    company_norm = company.strip().lower()
    rows = _get_unit_lookup_rows(excel_path)

    for row in rows:
        cols = list(row.keys())
        brand = str(row.get(cols[0], "")).strip().lower()
        unit_type = str(row.get(cols[2], "")).strip()
        series_raw = str(row.get(cols[3], "")).strip()
        examples_raw = str(row.get(cols[6], ""))

        if not unit_type or unit_type == "nan":
            continue

        # Brand filter β€” skip only when a company was given and clearly doesn't match
        if company_norm and company_norm not in brand and brand not in company_norm:
            continue

        # Series / Model Family prefix match (handles "FXFQ-PVJU / FXFQ-TVJU")
        for series in re.split(r"\s*/\s*", series_raw):
            prefix = series.strip().upper()
            if prefix and model_upper.startswith(prefix):
                return unit_type

        # Fallback: derive prefix from example model numbers (strip trailing digits)
        for ex in examples_raw.split(","):
            ex_prefix = re.sub(r"\d+.*$", "", ex.strip().upper()).rstrip("-")
            if len(ex_prefix) >= 4 and model_upper.startswith(ex_prefix):
                return unit_type

    return ""


def _detection_cache_path(out_dir: Path, page_num: int, floor_name: str) -> Path:
    safe = re.sub(r"[^\w]", "_", floor_name)
    return out_dir / f"floor_{page_num:03d}_{safe}_detections.json"


def _scale_image_for_api(img: Image.Image, max_px: int = 2048) -> tuple[Image.Image, float]:
    """Scale down to max_px on the longest side. Returns (scaled_img, scale_factor)."""
    w, h = img.size
    longest = max(w, h)
    if longest <= max_px:
        return img, 1.0
    factor = max_px / longest
    new_w, new_h = int(w * factor), int(h * factor)
    return img.resize((new_w, new_h), Image.LANCZOS), factor


def _tile_coords(img_size: tuple[int, int], tile_size: int = 3000, overlap: int = 300,
                 skip_right_frac: float = 0.15) -> list[tuple[int, int, int, int]]:
    """Tile (x0,y0,x1,y1) rectangles only β€” no image crops held in memory.
    Use when iterating many tiles (consensus passes) to avoid OOM."""
    W, H = img_size
    max_x = int(W * (1.0 - skip_right_frac))
    step = tile_size - overlap
    out = []
    y = 0
    while y < H:
        x = 0
        while x < max_x:
            x1 = min(x + tile_size, W)
            y1 = min(y + tile_size, H)
            out.append((x, y, x1, y1))
            if x1 >= max_x:
                break
            x += step
        if y + tile_size >= H:
            break
        y += step
    return out


def _make_tiles(img: Image.Image, tile_size: int = 3000, overlap: int = 300,
                skip_right_frac: float = 0.15) -> list[tuple[int, int, Image.Image]]:
    """
    Divide image into overlapping tiles, skipping the right title-block margin.
    Returns list of (x0, y0, tile_img).
    """
    W, H = img.size
    max_x = int(W * (1.0 - skip_right_frac))  # exclude title block
    step = tile_size - overlap
    tiles = []
    y = 0
    while y < H:
        x = 0
        while x < max_x:
            x1 = min(x + tile_size, W)
            y1 = min(y + tile_size, H)
            tile = img.crop((x, y, x1, y1))
            tiles.append((x, y, tile))
            if x1 >= max_x:
                break
            x += step
        if y + tile_size >= H:
            break
        y += step
    return tiles


def _detection_prompt_inclusive(tag_list: str) -> str:
    """Recall-first prompt: be inclusive, let the verify step handle precision."""
    return (
        "You are analyzing a SECTION (tile) of a mechanical HVAC floor plan.\n\n"
        "Find EVERY HVAC indoor unit in this tile. Your goal is to MISS NOTHING. "
        "A separate verification step removes false positives afterward, so when "
        "in doubt, INCLUDE it.\n\n"
        "Report a detection if EITHER of these is true:\n"
        "  (a) one of the schedule tags below appears as a printed label (it may be "
        "small, faint, or rotated 90Β°) β€” even if the unit symbol is partly cut off "
        "at the tile edge; OR\n"
        "  (b) you see a box/rectangle symbol with internal hatching, coil lines, or "
        "an X pattern that looks like an indoor unit, with a nearby short label.\n\n"
        "Only DON'T report: schedule tables, title blocks, and pure text-note blocks. "
        "Everything else that might be a unit β€” INCLUDE it.\n\n"
        f"SCHEDULE TAGS for this blueprint:\n{tag_list}\n\n"
        "For each detection give the tag that best matches the label (your closest "
        "guess if unsure β€” the tag is re-checked later).\n"
        "Return ONLY JSON, no markdown:\n"
        '{"detections": [{"tag": "<best tag>", "ymin": N, "xmin": N, "ymax": N, "xmax": N}, ...]}\n'
        "Box encloses the unit symbol AND its label. Coordinates are integers 0-1000 "
        'normalized to THIS TILE. Return {"detections": []} only if there is truly '
        "nothing unit-like here."
    )


def _detection_prompt(tag_list: str, inclusive: bool = False) -> str:
    if inclusive:
        return _detection_prompt_inclusive(tag_list)
    return (
        "You are analyzing a SECTION (tile) of a mechanical HVAC floor plan blueprint.\n\n"
        "Your job: find HVAC indoor unit symbols labeled with one of the equipment-schedule tags\n"
        "listed at the bottom of this prompt. The exact tag format varies per project β€” match\n"
        "the tag text EXACTLY as it appears in the schedule list (could be 'AC-D', 'FC-1',\n"
        "'IDU-A', etc.).\n\n"
        "A valid indoor unit symbol has ALL THREE of these properties:\n\n"
        "1. SHAPE β€” a rectangular box symbol. Aspect ratio and size vary by unit type:\n"
        "     * Ceiling-concealed-ducted units: longer/wider rectangles\n"
        "     * Wall-mounted units: smaller rectangles, often near a wall\n"
        "     * Cassette units: square-ish\n"
        "   The rectangle usually has INTERNAL DETAIL: parallel hatching lines (representing\n"
        "   coil fins), fan symbols, or coil patterns β€” NOT an empty box.\n\n"
        "2. CONNECTIONS β€” visible ductwork rectangles (labeled with duct sizes like '12X6',\n"
        "   '16X8') or refrigerant piping lines enter and exit the unit symbol.\n\n"
        "3. LABEL β€” an explicit text tag printed adjacent to the unit (above, below, beside,\n"
        "   or rotated 90Β°). The label must MATCH EXACTLY one of the schedule tags listed\n"
        "   below (full tag text, including any prefix).\n\n"
        "REJECT β€” these are NOT indoor units:\n"
        "* Symbols where the label is just a single letter inside a circle (e.g. 'D 4B',\n"
        "  'F 2A', 'TX 8B') β€” those are diffuser/drain/transfer designators\n"
        "* Ductwork sizing labels (numbers like '16X8'), 'VD', 'SG-N', 'EG-N', 'RG-N',\n"
        "  'CD-N', 'FD', 'BC-N', 'CAR', 'COD', 'PL-N', 'LD-N', 'EUN-N'\n"
        "* Schedule tables, legends, title blocks, notes\n"
        "* Thermostat symbols (small circles with 'T')\n"
        "* A bare rectangle without internal detail, without a matching label, or without piping\n\n"
        f"SCHEDULE TAGS for this blueprint:\n{tag_list}\n\n"
        "Return ONLY valid JSON, no markdown:\n"
        '{"detections": [{"tag": "<exact tag from list>", "ymin": N, "xmin": N, "ymax": N, "xmax": N}, ...]}\n\n'
        "The bounding box should enclose BOTH the unit rectangle AND its text label.\n"
        "Coordinates are integers 0-1000 normalized to THIS TILE's size.\n"
        'Return {"detections": []} if no valid units in this tile.'
    )


def _parse_tile_detections(raw: str, x0: int, y0: int, tile_w: int, tile_h: int,
                           known_tags: list[str],
                           coord_w: float = 1000, coord_h: float = 1000) -> list[TagHit]:
    """Parse a model's {"detections":[{tag,xmin,ymin,xmax,ymax}]} into full-image
    pixel TagHits. coord_w/coord_h are the model's coordinate space: 1000 for
    Gemini (normalized 0-1000), or the sent image's pixel size for Qwen (which
    returns absolute pixels). Shared by every detector backend."""
    import json as _json
    raw = re.sub(r"^```[a-z]*\n?", "", raw.strip(), flags=re.MULTILINE)
    raw = re.sub(r"```$", "", raw.strip())
    m = re.search(r"\{.*\}", raw, re.DOTALL)         # tolerate prose around JSON
    if m:
        raw = m.group(0)
    try:
        dets = _json.loads(raw).get("detections", [])
    except _json.JSONDecodeError:
        return []
    hits = []
    for det in dets:
        tag = _normalize_tag(det.get("tag", ""))
        if not tag or (known_tags and tag not in known_tags):
            continue
        try:
            cw, ch = coord_w, coord_h
            # auto-detect: if any coord exceeds 1000, it's absolute pixels
            if max(det["xmax"], det["ymax"]) > 1000 and coord_w == 1000:
                cw = ch = max(det["xmax"], det["ymax"])
            xn, yn = det["xmin"] / cw, det["ymin"] / ch
            xn2, yn2 = det["xmax"] / cw, det["ymax"] / ch
        except (KeyError, TypeError):
            continue
        x = x0 + int(xn * tile_w)
        y = y0 + int(yn * tile_h)
        w = max(int((xn2 - xn) * tile_w), 20)
        h = max(int((yn2 - yn) * tile_h), 20)
        hits.append(TagHit(tag=tag, x=x, y=y, w=w, h=h, conf=0.9, fuzzy=False))
    return hits


def _gemini_call_tile(
    client, genai_types, tile: Image.Image, x0: int, y0: int,
    img_w: int, img_h: int, known_tags: list[str], page_num: int,
    max_px: int = 2048, inclusive: bool = False,
) -> list[TagHit]:
    """Send one tile to Gemini and return TagHits in full-image pixel coordinates."""
    tile_w, tile_h = tile.size
    scaled, _ = _scale_image_for_api(tile, max_px)
    buf = io.BytesIO()
    scaled.save(buf, format="PNG")
    tag_list = ", ".join(sorted(known_tags)) if known_tags else "(no tags provided)"
    prompt = _detection_prompt(tag_list, inclusive)
    try:
        response = client.models.generate_content(
            model="gemini-2.5-flash",
            contents=[prompt, genai_types.Part.from_bytes(data=buf.getvalue(), mime_type="image/png")],
            config=genai_types.GenerateContentConfig(max_output_tokens=4096, temperature=0.0),
        )
        raw = response.text.strip()
    except Exception as e:
        logging.warning(f"  Tile ({x0},{y0}) Gemini error: {e}")
        return []
    return _parse_tile_detections(raw, x0, y0, tile_w, tile_h, known_tags)


def _qwen_call_tile(
    api_key: str, model: str, tile: Image.Image, x0: int, y0: int,
    img_w: int, img_h: int, known_tags: list[str], page_num: int,
    max_px: int = 2048, inclusive: bool = False,
) -> list[TagHit]:
    """Send one tile to a vision model via OpenRouter (Qwen by default) and
    return TagHits in full-image pixel coordinates. Same prompt/format as Gemini
    so the rest of the pipeline (snap, verify, cache) is identical."""
    import base64, json as _json, urllib.request
    tile_w, tile_h = tile.size
    scaled, _ = _scale_image_for_api(tile, max_px)
    buf = io.BytesIO()
    scaled.save(buf, format="PNG")
    b64 = base64.b64encode(buf.getvalue()).decode()
    tag_list = ", ".join(sorted(known_tags)) if known_tags else "(no tags provided)"
    body = {
        "model": model,
        "messages": [{"role": "user", "content": [
            {"type": "text", "text": _detection_prompt(tag_list, inclusive)},
            {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}},
        ]}],
        "max_tokens": 4096, "temperature": 0,
    }
    req = urllib.request.Request(
        "https://openrouter.ai/api/v1/chat/completions", data=_json.dumps(body).encode(),
        headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=120) as r:
            raw = _json.load(r)["choices"][0]["message"]["content"]
    except Exception as e:
        logging.warning(f"  Tile ({x0},{y0}) Qwen error: {e}")
        return []
    # Qwen returns absolute pixels of the scaled image it received
    sw, sh = scaled.size
    return _parse_tile_detections(raw, x0, y0, tile_w, tile_h, known_tags,
                                  coord_w=sw, coord_h=sh)


def gemini_detect_floor_page(
    pdf_path: Path,
    page_0idx: int,
    dpi: int,
    known_tags: set[str],
    out_dir: Path,
    page_num: int,
    floor_name: str,
    save_yolo: bool = True,
    tile_size: int = 3000,
    refresh: bool = False,
    consensus: int = 1,
    render_pdf: Path | None = None,
    detector: str = "gemini",
    qwen_model: str = "qwen/qwen2.5-vl-72b-instruct",
    recall_prompt: bool = False,
    fp_filter: bool = False,
    runs: int = 1,
    workers: int = 0,
) -> tuple[Image.Image, list[TagHit]]:
    """
    Render the floor plan at DPI, tile it, send each tile to Gemini to detect
    unit tags, merge and deduplicate, cache results, and optionally save YOLO
    labels. Returns (full-res color_img, list[TagHit]).

    render_pdf: if given, the floor IMAGE is rendered from this PDF instead of
    pdf_path (e.g. a crisp un-flattened vector PDF for sharper glyphs). It must
    share pdf_path's page order and size so coordinates stay 1:1.
    """
    import json

    cache_path = _detection_cache_path(out_dir, page_num, floor_name)

    # ── Render full-res image (needed for annotation regardless of cache) ─────
    color_img = _render_page(render_pdf or pdf_path, page_0idx, dpi)
    img_w, img_h = color_img.size

    # ── Load from cache if available ──────────────────────────────────────────
    if cache_path.exists() and not refresh:
        data = json.loads(cache_path.read_text(encoding="utf-8"))
        hits = [TagHit(**d) for d in data["hits"]]
        print(f"cached ({len(hits)} detections)")
        return color_img, hits

    # ── Set up the detection model + the verify model (Gemini) ───────────────
    # Verify/refine always uses Gemini, so we need its client either way.
    api_key = os.environ.get("GEMINI_API_KEY", "")
    if not api_key:
        print("no GEMINI_API_KEY β€” skipping")
        return color_img, []
    try:
        from google import genai as google_genai
        from google.genai import types as genai_types
    except ImportError:
        print("google-genai not installed β€” run: pip install google-genai")
        return color_img, []
    client = google_genai.Client(api_key=api_key)

    qwen_key = os.environ.get("OPENROUTER_API_KEY", "")
    if detector == "qwen" and not qwen_key:
        print("no OPENROUTER_API_KEY β€” needed for --detector qwen")
        return color_img, []

    def _call_tile(tile_img, x0, y0):
        if detector == "qwen":
            return _qwen_call_tile(qwen_key, qwen_model, tile_img, x0, y0,
                                   img_w, img_h, known_list, page_num,
                                   inclusive=recall_prompt)
        return _gemini_call_tile(client, genai_types, tile_img, x0, y0,
                                 img_w, img_h, known_list, page_num,
                                 inclusive=recall_prompt)

    # ── Tile the image and query each tile ────────────────────────────────────
    # Multi-offset consensus: run several passes whose tile boundaries fall in
    # DIFFERENT places, then union the hits. A unit split across a tile edge in
    # one pass sits mid-tile in another, so recall goes up. Extra passes cost
    # more Gemini calls; the verify step still drops false positives.
    configs = [(tile_size, tile_size // 10)]            # pass 1 (baseline grid)
    if consensus >= 2:
        configs.append((tile_size, tile_size // 3))     # shifted edges (moderate overlap)
    if consensus >= 3:
        configs.append((int(tile_size * 0.75), tile_size // 5))  # different tile size
    all_hits: list[TagHit] = []
    known_list = sorted(known_tags) if known_tags else []

    # Tile calls are network-bound (each waits on an API round-trip), so running
    # them concurrently cuts wall-clock time dramatically WITHOUT changing the
    # results β€” same calls, same hits, just not idle between them. Worker count
    # is capped low by default to stay under the Gemini free-tier rate limit;
    # override with the HVAC_TILE_WORKERS env var (e.g. 8 on a paid key).
    if workers <= 0:
        workers = int(os.environ.get("HVAC_TILE_WORKERS", "4"))
    workers = max(1, workers)

    # --runs N: repeat the whole detection N times and UNION the hits. VLM
    # detection jitters run-to-run (even at temperature 0), so a unit missed in
    # one run is caught in another β€” this beats the stochastic "close same-tag
    # neighbour" misses that a single run (or tile-offset consensus) can't.
    for run_i in range(max(1, runs)):
        if runs > 1:
            print(f"  === detection run {run_i+1}/{runs} ===")
        for p, (ts, ov) in enumerate(configs, start=1):
            # coords only β€” crop each tile just-in-time so we never hold all the
            # large crops in memory at once (consensus passes can be 50+ tiles).
            coords = _tile_coords(color_img.size, tile_size=ts, overlap=ov)
            if len(configs) > 1:
                print(f"  consensus pass {p}/{len(configs)} (tile={ts}, overlap={ov}, "
                      f"{len(coords)} tiles)")

            def _do_tile(args):
                # Crop just-in-time inside the worker so we only ever hold
                # `workers` crops in memory at once, not the whole grid.
                x0, y0, x1, y1 = args
                try:
                    return _call_tile(color_img.crop((x0, y0, x1, y1)), x0, y0)
                except Exception as e:  # one bad tile shouldn't abort the floor
                    print(f"    tile ({x0},{y0}) error: {e}", flush=True)
                    return []

            print(f"  querying {len(coords)} tiles ({workers} at a time)…",
                  flush=True)
            done = 0
            from concurrent.futures import ThreadPoolExecutor
            with ThreadPoolExecutor(max_workers=workers) as ex:
                for tile_hits in ex.map(_do_tile, coords):
                    done += 1
                    if tile_hits:
                        all_hits.extend(tile_hits)
                    if done % 10 == 0 or done == len(coords):
                        print(f"    {done}/{len(coords)} tiles, "
                              f"{len(all_hits)} hit(s) so far", flush=True)

    # ── Deduplicate / union across tiles + passes (IOU > 0.3 same tag) ────────
    hits = _deduplicate_hits(all_hits, iou_threshold=0.3)

    # ── Ground boxes on exact OCR'd tag-text positions ───────────────────────
    # Gemini knows WHAT is there but its coordinates are approximate (often off
    # by 50-300 px). For each hit, OCR a small crop around it (at 0Β°/90Β°/270Β° β€”
    # plan labels are often rotated) and snap the box to the exact tag text.
    print(f"  snapping {len(hits)} hit(s) to OCR'd tag text…", end=" ", flush=True)
    snapped: list[TagHit] = []
    unsnapped: list[TagHit] = []
    for h in hits:
        s = _local_ocr_snap(color_img, h)
        (snapped if s is not None else unsnapped).append(s if s is not None else h)
    print(f"{len(snapped)} snapped, {len(unsnapped)} unsnapped")

    # Crash-safety: persist the post-snap result NOW (snapped grounded, unsnapped
    # marked for review) so a crash in the heavy verify loop doesn't lose the
    # whole floor. Verify overwrites this at the end.
    _prelim = snapped + [u._replace(fuzzy=True, conf=0.5) for u in unsnapped]
    _prelim = _merge_nearby_same_tag(_deduplicate_hits(_prelim, 0.3), max_dist=250)
    cache_path.write_text(
        json.dumps({"hits": [h._asdict() for h in _prelim], "img_w": img_w,
                    "img_h": img_h}, indent=2), encoding="utf-8")

    # ── Verify only the uncertain hits via Gemini crop check ─────────────────
    # Snapped hits are already grounded (tag text verifiably exists there).
    import gc
    verified: list[TagHit] = []
    if unsnapped:
        print(f"  verifying {len(unsnapped)} unsnapped hit(s)…", end=" ", flush=True)
        rejected = 0
        recovered = 0
        for vi, h in enumerate(unsnapped):
            if vi % 10 == 9:
                gc.collect()
            r = _refine_hit_box(client, genai_types, color_img, h)
            if r is None:
                rejected += 1
                continue
            # One wide snap at the refined position. The tight radius already
            # failed in the main snap loop, so go straight to a 1000px search β€”
            # recovers units Gemini boxed onto a nearby feature (500-650 px off)
            # in a single OCR pass instead of three (cuts Tesseract churn 3x).
            esc = _local_ocr_snap(color_img, r, radius=1000)
            if esc is not None:
                # Recovered: tag text WAS found, just offset. conf=0.75 marks
                # it for a quick human confirm (not fuzzy/yellow).
                verified.append(esc._replace(conf=0.75))
                recovered += 1
            else:
                # Tag text never found at any radius β€” Gemini's guess only.
                # Mark fuzzy β†’ YELLOW β†’ likely hallucination, review it.
                verified.append(r._replace(fuzzy=True, conf=0.5))
        print(f"{len(verified)} kept ({recovered} recovered via wide snap), {rejected} rejected")
    hits = _deduplicate_hits(snapped + verified, iou_threshold=0.3)
    hits = _merge_nearby_same_tag(hits, max_dist=250)
    hits = _remove_overlapping_boxes(hits)

    # ── Precision pass: drop false positives via Qwen+Claude existence vote ──
    import gc as _gc
    _gc.collect()                 # free detection-run memory before fp-filter (OOM guard)
    if fp_filter and qwen_key:
        print(f"  fp-filter: verifying {sum(1 for h in hits if _review_status(h)!='confirmed')} "
              f"uncertain box(es) with Qwen+Claude…", end=" ", flush=True)
        hits = _fp_filter_hits(hits, color_img, qwen_key, qwen_model)
        hits = _remove_overlapping_boxes(hits)

    # ── Cache results ─────────────────────────────────────────────────────────
    cache_path.write_text(
        json.dumps({"hits": [h._asdict() for h in hits], "img_w": img_w, "img_h": img_h}, indent=2),
        encoding="utf-8",
    )

    # ── Save YOLO labels ──────────────────────────────────────────────────────
    if save_yolo and hits:
        _save_yolo_labels(pdf_path, page_num, color_img, hits, img_w, img_h)

    return color_img, hits


def _save_yolo_labels(
    pdf_path: Path, page_num: int, color_img: Image.Image,
    hits: list[TagHit], img_w: int, img_h: int,
) -> None:
    """
    Save image + YOLO label file into dataset/images/train and dataset/labels/train.
    Also updates dataset.yaml to list all 21 tag classes.
    """
    import json

    stem = f"{pdf_path.stem}_p{page_num:03d}"
    split = "train"  # new Gemini labels go to train by default

    img_dir = _DATASET_ROOT / "images" / split
    lbl_dir = _DATASET_ROOT / "labels" / split
    img_dir.mkdir(parents=True, exist_ok=True)
    lbl_dir.mkdir(parents=True, exist_ok=True)

    # Save image as JPG (matching existing dataset convention)
    img_path = img_dir / f"{stem}.jpg"
    color_img.save(img_path, format="JPEG", quality=92)

    # Write YOLO label file: class_id x_center y_center width height (all 0-1)
    label_lines = []
    for hit in hits:
        cls = _TAG_TO_CLASS.get(hit.tag, 0)
        xc = (hit.x + hit.w / 2) / img_w
        yc = (hit.y + hit.h / 2) / img_h
        w_n = hit.w / img_w
        h_n = hit.h / img_h
        label_lines.append(f"{cls} {xc:.6f} {yc:.6f} {w_n:.6f} {h_n:.6f}")

    lbl_path = lbl_dir / f"{stem}.txt"
    lbl_path.write_text("\n".join(label_lines), encoding="utf-8")

    # Update dataset.yaml to use multi-class names
    yaml_path = _DATASET_ROOT / "dataset.yaml"
    names_block = "\n".join(f"  {i}: {tag}" for i, tag in enumerate(_ALL_TAGS))
    yaml_path.write_text(
        f"path: {_DATASET_ROOT}\ntrain: images/train\nval: images/val\nnames:\n{names_block}\n",
        encoding="utf-8",
    )

    logging.debug(f"  YOLO labels saved: {lbl_path} ({len(hits)} boxes)")


# ─────────────────────────────────────────────────────────────────────────────
# Step 3b β€” High-DPI OCR per floor page (kept as fallback)
# ─────────────────────────────────────────────────────────────────────────────

def _refine_hit_box(
    client, genai_types, color_img: Image.Image, hit: TagHit,
    search_radius: int = 900,
) -> TagHit | None:
    """
    Re-query Gemini on a small crop centered on hit to VERIFY the unit
    actually exists there and get tighter bounds. Returns None if the unit
    can't be verified (false positive from the initial pass).
    """
    W, H = color_img.size
    cx = hit.x + hit.w // 2
    cy = hit.y + hit.h // 2
    x0 = max(0, cx - search_radius)
    y0 = max(0, cy - search_radius)
    x1 = min(W, cx + search_radius)
    y1 = min(H, cy + search_radius)
    crop = color_img.crop((x0, y0, x1, y1))
    crop_w, crop_h = crop.size

    buf = io.BytesIO()
    crop.save(buf, format="PNG")

    prompt = (
        "This is a zoomed-in section of an HVAC mechanical blueprint.\n\n"
        f"VERIFY: is there an HVAC indoor unit labeled exactly '{hit.tag}' (matching this\n"
        "exact text from the equipment schedule) visible in this image?\n\n"
        "A VALID match requires ALL of:\n"
        "  - A rectangular unit body (size/shape varies by unit type β€” ducted units are\n"
        "    longer rectangles, wall-mounted are smaller, cassettes are square-ish).\n"
        "    Internal detail is typical: parallel hatching, fan symbols, or coil patterns.\n"
        "  - Ductwork or refrigerant piping connecting to the rectangle.\n"
        f"  - The exact text label '{hit.tag}' printed adjacent to that rectangle\n"
        "    (label may be rotated 90Β°).\n\n"
        "REJECT (return verified=false) if:\n"
        f"  - The text '{hit.tag}' is not visible anywhere in this image\n"
        f"  - The text '{hit.tag}' is visible but there's no rectangular unit body next to it\n"
        "  - The only nearby symbol is a circle with a single letter (e.g. 'D 4B') β€” not a unit\n"
        "  - The only nearby labels are ductwork-related (16X8, VD, SG-N, EG-N, RG-N, CD-N,\n"
        "    FD, CAR, COD, PL-N, LD-N, BC-N)\n\n"
        "If verified: return tight bounds covering BOTH the unit rectangle AND its label.\n"
        "If NOT verified: return all zeros.\n\n"
        "Return ONLY JSON:\n"
        '{"verified": true_or_false, "ymin": N, "xmin": N, "ymax": N, "xmax": N}\n\n'
        "Coordinates 0-1000 normalized to this crop's size."
    )
    try:
        response = client.models.generate_content(
            model="gemini-2.5-flash",
            contents=[prompt, genai_types.Part.from_bytes(data=buf.getvalue(), mime_type="image/png")],
            config=genai_types.GenerateContentConfig(max_output_tokens=512, temperature=0.0),
        )
        raw = response.text.strip()
        raw = re.sub(r"```[a-zA-Z]*\n?", "", raw)
        raw = raw.replace("```", "").strip()

        # Parse verified flag
        verified = None
        m_verified = re.search(r'verified"?\s*[:=]\s*(true|false)', raw, re.IGNORECASE)
        if m_verified:
            verified = m_verified.group(1).lower() == "true"

        # Parse coords (any order)
        coords = {}
        for key in ("ymin", "xmin", "ymax", "xmax"):
            m = re.search(rf'{key}"?\s*[:=]\s*(\d+)', raw)
            if m:
                coords[key] = int(m.group(1))

        # Verification logic
        if verified is False:
            # Explicitly rejected by Gemini
            return None
        if not coords or len(coords) != 4:
            # Couldn't parse β€” keep original (conservative)
            return hit
        # All-zero box also means rejection
        if all(v == 0 for v in coords.values()):
            return None
        if coords["xmax"] <= coords["xmin"] or coords["ymax"] <= coords["ymin"]:
            return hit

        xn, yn = coords["xmin"] / 1000, coords["ymin"] / 1000
        xn2, yn2 = coords["xmax"] / 1000, coords["ymax"] / 1000
        new_x = x0 + int(xn * crop_w)
        new_y = y0 + int(yn * crop_h)
        new_w = max(int((xn2 - xn) * crop_w), 20)
        new_h = max(int((yn2 - yn) * crop_h), 20)
        return TagHit(tag=hit.tag, x=new_x, y=new_y, w=new_w, h=new_h, conf=hit.conf, fuzzy=hit.fuzzy)
    except Exception as e:
        logging.warning(f"  Verify error for {hit.tag} at ({hit.x},{hit.y}): {e}")
        return hit


def _clean_blueprint_for_ocr(gray: np.ndarray, cutoff: int = 110,
                             line_len: int = 60) -> np.ndarray:
    """
    Prepare a blueprint crop for OCR:
      1. Hard threshold β€” hatching/fill patterns are drawn in GRAY while tag
         text is BLACK, so a cutoff erases the hatching that Tesseract
         otherwise reads as 'NN'/'SS' junk.
      2. Morphological line removal β€” long horizontal/vertical strokes
         (ductwork, unit outlines) are erased so text enclosed inside unit
         rectangles isn't swallowed as a 'graphic region'.
    Measured on the 355 E 86th cellar: tags inside hatched/boxed regions go
    from undetected to conf 40-75.
    """
    _, bw = cv2.threshold(gray, cutoff, 255, cv2.THRESH_BINARY)
    inv = 255 - bw  # ink = white for morphology
    horiz = cv2.morphologyEx(inv, cv2.MORPH_OPEN,
                             cv2.getStructuringElement(cv2.MORPH_RECT, (line_len, 1)))
    vert = cv2.morphologyEx(inv, cv2.MORPH_OPEN,
                            cv2.getStructuringElement(cv2.MORPH_RECT, (1, line_len)))
    return 255 - cv2.subtract(inv, cv2.add(horiz, vert))


def _ocr_tag_boxes(gray_img: Image.Image, known_tags: set[str],
                   min_conf: float = 40.0,
                   psms: tuple[int, ...] = (11, 12)) -> list[TagHit]:
    """
    OCR a (small) grayscale image and return exact pixel boxes for every
    known-tag text occurrence. Input should already be cleaned via
    _clean_blueprint_for_ocr (adaptive threshold destroys the thin stroked
    blueprint font β€” measured: 2 vs 4 tags found on the same region).
    """
    hits: list[TagHit] = []
    for psm in psms:
        try:
            data = pytesseract.image_to_data(
                gray_img, output_type=pytesseract.Output.DATAFRAME,
                config=f"--oem 3 --psm {psm}",
            )
        except Exception as e:
            logging.debug(f"  OCR pass psm={psm} failed: {e}")
            continue
        data = data[(data["text"].notna()) & (data["conf"] >= min_conf)].copy()
        data["text"] = data["text"].astype(str).str.strip()
        data = data[data["text"] != ""].reset_index(drop=True)

        # Single tokens: 'AC-D', 'AC-C-1', 'AC-1-14' …
        for _, row in data.iterrows():
            tag = _normalize_tag(str(row["text"]))
            if tag and tag in known_tags:
                hits.append(TagHit(tag, int(row["left"]), int(row["top"]),
                                   int(row["width"]), int(row["height"]),
                                   float(row["conf"]), False))

        # Two-token merges ('AC' + 'D'), only when physically adjacent
        sort_cols = [c for c in ("block_num", "par_num", "line_num", "word_num")
                     if c in data.columns]
        if sort_cols and len(data) > 1:
            ds = data.sort_values(sort_cols).reset_index(drop=True)
            for i in range(len(ds) - 1):
                r1, r2 = ds.iloc[i], ds.iloc[i + 1]
                tag = _normalize_tag(f"{r1['text']}{r2['text']}")
                if not tag or tag not in known_tags:
                    continue
                max_h = max(int(r1["height"]), int(r2["height"]))
                gap = abs(int(r2["left"]) - (int(r1["left"]) + int(r1["width"])))
                v_off = abs(int(r1["top"]) - int(r2["top"]))
                if gap > 3 * max_h or v_off > max_h:
                    continue  # tokens too far apart to be one label
                bx = int(min(r1["left"], r2["left"]))
                by = int(min(r1["top"], r2["top"]))
                bw = int(max(r1["left"] + r1["width"], r2["left"] + r2["width"])) - bx
                bh = int(max(r1["top"] + r1["height"], r2["top"] + r2["height"])) - by
                hits.append(TagHit(tag, bx, by, max(bw, 10), max(bh, 10),
                                   float((r1["conf"] + r2["conf"]) / 2), False))
    return _deduplicate_hits(hits, iou_threshold=0.3)


def _local_ocr_snap(
    color_img: Image.Image,
    hit: TagHit,
    radius: int = 600,
    min_conf: float = 30.0,
) -> TagHit | None:
    """
    Ground a Gemini hit on the exact tag-text position via OCR of a small
    crop centered on the hit. Tag labels on plans are often rotated 90Β°,
    so the crop is OCR'd at 0Β°, 90Β° and 270Β°. min_conf is deliberately low:
    we only accept text that normalizes to the ONE tag we're looking for,
    so false positives are unlikely even at low confidence.
    Returns the hit re-centered on the nearest matching text, or None if
    the tag text isn't found.
    """
    import math

    W, H = color_img.size
    cx, cy = hit.x + hit.w // 2, hit.y + hit.h // 2
    x0, y0 = max(0, cx - radius), max(0, cy - radius)
    x1, y1 = min(W, cx + radius), min(H, cy + radius)
    crop = color_img.crop((x0, y0, x1, y1))
    cw, ch = crop.size
    gray_np = cv2.cvtColor(np.array(crop), cv2.COLOR_RGB2GRAY)
    gray = Image.fromarray(_clean_blueprint_for_ocr(gray_np))

    best: tuple[float, float, float, int, int] | None = None  # (dist, ox, oy, ow, oh)
    for scale in (1, 2):  # 2Γ— upscale rescues small/thin tag text
        if scale == 1:
            g_img = gray
        else:
            g_np = cv2.resize(np.array(gray), None, fx=scale, fy=scale,
                              interpolation=cv2.INTER_CUBIC)
            g_img = Image.fromarray(g_np)
        for rot in (0, 90, 270):
            img_r = g_img.rotate(rot, expand=True) if rot else g_img
            for o in _ocr_tag_boxes(img_r, {hit.tag}, min_conf, psms=(11, 12, 6)):
                bcx = (o.x + o.w / 2) / scale
                bcy = (o.y + o.h / 2) / scale
                ow_s, oh_s = o.w / scale, o.h / scale
                scw, sch = cw, ch  # rotation happened in scaled space; centers already unscaled
                if rot == 0:
                    ox, oy, ow, oh = bcx, bcy, ow_s, oh_s
                elif rot == 90:   # PIL rotates CCW; inverse-map rotated β†’ original
                    ox, oy, ow, oh = scw - 1 - bcy, bcx, oh_s, ow_s
                else:             # rot == 270
                    ox, oy, ow, oh = bcy, sch - 1 - bcx, oh_s, ow_s
                d = math.hypot(ox - (cx - x0), oy - (cy - y0))
                if best is None or d < best[0]:
                    best = (d, ox, oy, int(ow), int(oh))
        if best is not None:
            break  # found at native scale β€” skip the slower upscaled pass

    if best is None:
        return None
    _, ox, oy, ow, oh = best
    # Box centered on the exact text location; keep Gemini's size estimate
    # (it saw the whole unit symbol) but never smaller than text + padding.
    bw = max(hit.w, int(ow) + 80)
    bh = max(hit.h, int(oh) + 80)
    return TagHit(hit.tag, int(x0 + ox - bw / 2), int(y0 + oy - bh / 2),
                  bw, bh, 0.95, False)


def _iou(a: TagHit, b: TagHit) -> float:
    ax1, ay1, ax2, ay2 = a.x, a.y, a.x + a.w, a.y + a.h
    bx1, by1, bx2, by2 = b.x, b.y, b.x + b.w, b.y + b.h
    ix1, iy1 = max(ax1, bx1), max(ay1, by1)
    ix2, iy2 = min(ax2, bx2), min(ay2, by2)
    inter = max(0, ix2 - ix1) * max(0, iy2 - iy1)
    if inter == 0:
        return 0.0
    union = (a.w * a.h) + (b.w * b.h) - inter
    return inter / union if union > 0 else 0.0


def _merge_nearby_same_tag(hits: list[TagHit], max_dist: int = 250,
                           min_pair_dist: int = 110) -> list[TagHit]:
    """
    Drop same-tag DUPLICATES while PRESERVING genuinely adjacent same-tag units
    (e.g. two identical units back-to-back on opposite sides of a wall, serving
    different apartments β€” common on residential plans).

    A nearby same-tag hit is treated as a duplicate (dropped) only when it looks
    like a re-detection of the SAME unit:
      β€’ it OVERLAPS a kept hit (same unit boxed twice), OR
      β€’ it is ungrounded/fuzzy (no tag text of its own) and sits within max_dist
        of a kept hit (a stray body box near a real, labelled one), OR
      β€’ it is implausibly close (< min_pair_dist) β€” closer than two real
        same-size units can physically sit.

    Two GROUNDED hits (each OCR-snapped to its OWN printed tag) that do NOT
    overlap and are >= min_pair_dist apart are kept as distinct units. This is
    what recovers the missed back-to-back twin without re-introducing duplicates
    elsewhere: a doubly-detected single unit still overlaps (or one copy is
    ungrounded) and is still dropped.
    """
    import math
    kept: list[TagHit] = []
    # Prefer non-fuzzy (OCR-grounded) hits, then higher confidence
    for hit in sorted(hits, key=lambda h: (h.fuzzy, -h.conf)):
        hcx, hcy = hit.x + hit.w / 2, hit.y + hit.h / 2
        dup = False
        for k in kept:
            if k.tag != hit.tag:
                continue
            d = math.hypot(hcx - (k.x + k.w / 2), hcy - (k.y + k.h / 2))
            if d >= max_dist:
                continue
            if _overlap_frac(hit, k) > 0.15:
                dup = True; break              # same unit boxed twice
            if d < min_pair_dist:
                dup = True; break              # too close to be two real units
            if hit.fuzzy or k.fuzzy:
                dup = True; break              # ungrounded body near a real one
            # else: two grounded, non-overlapping, >= min_pair_dist apart β†’
            # two distinct printed tags β†’ keep both (back-to-back units)
        if not dup:
            kept.append(hit)
    return kept


def _overlap_frac(a: TagHit, b: TagHit) -> float:
    """Intersection area as a fraction of the SMALLER box. Unlike IOU this isn't
    diluted by the union, so it flags partial overlaps (a box mostly covering a
    smaller one) that IOU misses."""
    ix1, iy1 = max(a.x, b.x), max(a.y, b.y)
    ix2, iy2 = min(a.x + a.w, b.x + b.w), min(a.y + a.h, b.y + b.h)
    inter = max(0, ix2 - ix1) * max(0, iy2 - iy1)
    if inter == 0:
        return 0.0
    return inter / max(1, min(a.w * a.h, b.w * b.h))


def _qwen_verify_refine(api_key: str, model: str, color_img: Image.Image,
                        hit: TagHit, radius: int = 500, max_px: int = 1400):
    """Ask Qwen (conservative + tight grounding) to confirm a unit and tighten
    its box. Returns: a refined TagHit (present, box tightened) or None (Qwen
    says it's not a real unit β†’ drop the false positive)."""
    import base64, json as _json, urllib.request
    W, H = color_img.size
    cx, cy = hit.x + hit.w // 2, hit.y + hit.h // 2
    x0, y0 = max(0, cx - radius), max(0, cy - radius)
    x1, y1 = min(W, cx + radius), min(H, cy + radius)
    crop = color_img.crop((x0, y0, x1, y1))
    cw, ch = crop.size
    scaled, _ = _scale_image_for_api(crop, max_px)
    sw, sh = scaled.size
    buf = io.BytesIO(); scaled.save(buf, format="PNG")
    b64 = base64.b64encode(buf.getvalue()).decode()
    prompt = (
        "This is a zoomed crop of a mechanical HVAC floor plan.\n"
        f"Is there a REAL HVAC indoor unit here whose printed tag is exactly '{hit.tag}'? "
        "A real unit is a rectangle/box symbol (usually with internal hatching or "
        f"coil lines) with '{hit.tag}' printed next to it (label may be rotated 90Β°). "
        "Ductwork, diffusers (a letter in a circle like 'D 4B'), duct-size labels "
        "(e.g. 12X6), grilles (SG/RG/EG), and plain text are NOT units.\n"
        "If YES, give the TIGHT bounding box around the unit symbol AND its label.\n"
        'Return ONLY JSON: {"present": true or false, "xmin":N,"ymin":N,"xmax":N,"ymax":N}\n'
        "Coordinates in pixels of THIS image. If not present, return {\"present\": false}."
    )
    body = {"model": model, "messages": [{"role": "user", "content": [
        {"type": "text", "text": prompt},
        {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}}]}],
        "max_tokens": 200, "temperature": 0}
    req = urllib.request.Request(
        "https://openrouter.ai/api/v1/chat/completions", data=_json.dumps(body).encode(),
        headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=90) as r:
            raw = _json.load(r)["choices"][0]["message"]["content"]
        m = re.search(r"\{.*\}", raw, re.DOTALL)
        data = _json.loads(m.group(0)) if m else {}
    except Exception as e:
        logging.warning(f"  Qwen verify error for {hit.tag}: {e}")
        return hit            # network error β†’ keep original (conservative)
    if not data.get("present", False):
        return None           # Qwen says not a real unit β†’ drop
    try:
        xmin, ymin, xmax, ymax = data["xmin"], data["ymin"], data["xmax"], data["ymax"]
        cmax = max(xmax, ymax)
        denom = cmax if cmax > 1000 else 1000        # absolute px vs 0-1000
        # map back through the scale used for the API image
        fx, fy = cw / sw, ch / sh
        nx = x0 + int(xmin / denom * sw * fx)
        ny = y0 + int(ymin / denom * sh * fy)
        nw = max(20, int((xmax - xmin) / denom * sw * fx))
        nh = max(20, int((ymax - ymin) / denom * sh * fy))
        # Cap relocation: a big jump means Qwen latched onto a DIFFERENT unit in
        # the crop, not a tighter box for this one. Confirm presence but keep the
        # original position when the move exceeds ~250px.
        import math as _m
        if _m.hypot((nx + nw / 2) - (hit.x + hit.w / 2),
                    (ny + nh / 2) - (hit.y + hit.h / 2)) > 250:
            return hit._replace(conf=0.9, fuzzy=False)
        return TagHit(hit.tag, nx, ny, nw, nh, 0.9, False)
    except (KeyError, TypeError, ZeroDivisionError):
        return hit


def _fp_filter_hits(hits: list[TagHit], color_img: Image.Image, qwen_key: str,
                    qwen_model: str = "qwen/qwen2.5-vl-72b-instruct",
                    claude_model: str = "anthropic/claude-sonnet-4.6") -> list[TagHit]:
    """Precision pass: drop false positives WITHOUT hurting recall. Trusts the
    grounded (snapped) boxes; for each UNCERTAIN box asks Qwen "is this a unit?",
    and when Qwen says no, tiebreaks with Claude β€” dropping only when BOTH
    conservative models agree it's not a unit. Real units one model fumbles get
    rescued by the other; Gemini is excluded (it made the detection β†’ biased)."""
    import gc
    kept, dropped = [], 0
    for vi, h in enumerate(hits):
        if vi % 8 == 7:
            gc.collect()
        if _review_status(h) == "confirmed":
            kept.append(h)
            continue
        q = _qwen_verify_refine(qwen_key, qwen_model, color_img, h)
        if q is not None:
            kept.append(q._replace(conf=0.9, fuzzy=False))
            continue
        c = _qwen_verify_refine(qwen_key, claude_model, color_img, h)
        if c is None:
            dropped += 1                       # Qwen AND Claude agree: not a unit
        else:
            kept.append(c._replace(conf=0.9, fuzzy=False))   # Claude rescued it
    if dropped:
        print(f"  fp-filter: dropped {dropped} false positive(s) "
              f"(Qwen+Claude agreement)")
    return kept


def _remove_overlapping_boxes(hits: list[TagHit], same_tag_frac: float = 0.15,
                              cross_tag_frac: float = 0.4) -> list[TagHit]:
    """Non-max suppression on overlapping boxes β€” keep the higher-quality one
    (grounded over fuzzy, then higher confidence). Tag-aware: SAME-tag boxes that
    overlap even a little are almost certainly the same unit detected twice
    (low threshold); DIFFERENT-tag boxes need a big overlap before we assume a
    duplicate (so genuinely adjacent distinct units aren't merged)."""
    kept: list[TagHit] = []
    for hit in sorted(hits, key=lambda h: (h.fuzzy, -h.conf)):
        drop = False
        for k in kept:
            thr = same_tag_frac if k.tag == hit.tag else cross_tag_frac
            if _overlap_frac(hit, k) > thr:
                drop = True
                break
        if not drop:
            kept.append(hit)
    return kept


def _deduplicate_hits(hits: list[TagHit], iou_threshold: float = 0.5) -> list[TagHit]:
    kept: list[TagHit] = []
    for hit in sorted(hits, key=lambda h: -h.conf):
        if any(h.tag == hit.tag and _iou(h, hit) > iou_threshold for h in kept):
            continue
        kept.append(hit)
    return kept


def _render_page(pdf_path: Path, page_0idx: int, dpi: int) -> Image.Image:
    doc = fitz.open(pdf_path)
    page = doc.load_page(page_0idx)
    mat = fitz.Matrix(dpi / 72.0, dpi / 72.0)
    pix = page.get_pixmap(matrix=mat, alpha=False)
    # Disable PIL decompression-bomb check β€” blueprint sheets are legitimately huge
    Image.MAX_IMAGE_PIXELS = None
    return Image.frombytes("RGB", [pix.width, pix.height], pix.samples)


def _ocr_image(pil_img: Image.Image, psm: int, min_conf: float) -> "pd.DataFrame":  # type: ignore[name-defined]
    import pandas as pd  # local import keeps top-level clean if pandas missing
    gray = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2GRAY)
    thresh = cv2.adaptiveThreshold(
        gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2
    )
    data = pytesseract.image_to_data(
        Image.fromarray(thresh),
        output_type=pytesseract.Output.DATAFRAME,
        config=f"--oem 3 --psm {psm}",
    )
    data = data[(data["text"].notna()) & (data["conf"] >= min_conf)].copy()
    data["text"] = data["text"].str.strip()
    data = data[data["text"] != ""].reset_index(drop=True)
    return data


def _extract_hits_from_data(data, known_tags: set[str], psm_used: int) -> list[TagHit]:
    import pandas as pd

    hits: list[TagHit] = []

    # ── Single-token pass ──────────────────────────────────────────────────
    _SINGLE = re.compile(r"^AC[-\s]?[A-U]$", re.IGNORECASE)
    for _, row in data.iterrows():
        raw = str(row["text"]).strip()
        if _SINGLE.match(raw):
            tag = _normalize_tag(raw)
            if tag and (not known_tags or tag in known_tags):
                hits.append(TagHit(tag, int(row["left"]), int(row["top"]),
                                   int(row["width"]), int(row["height"]),
                                   float(row["conf"]), False))

    # ── Multi-token merge (handles "AC -A", "AC" + "A" split) ─────────────
    sort_cols = [c for c in ("block_num", "par_num", "line_num", "word_num") if c in data.columns]
    if sort_cols and len(data) > 1:
        ds = data.sort_values(sort_cols).reset_index(drop=True)
        for i in range(len(ds) - 1):
            w1 = str(ds.iloc[i]["text"]).upper()
            w2 = str(ds.iloc[i + 1]["text"]).upper()
            merged = re.sub(r"[\s\-]", "", w1 + w2)
            m = re.match(r"^AC([A-U])$", merged)
            if not m:
                continue
            tag = f"AC-{m.group(1)}"
            if known_tags and tag not in known_tags:
                continue
            r1, r2 = ds.iloc[i], ds.iloc[i + 1]
            x = int(r1["left"])
            y = int(min(r1["top"], r2["top"]))
            w = int(r2["left"] + r2["width"] - r1["left"])
            h = int(max(r1["top"] + r1["height"], r2["top"] + r2["height"]) - y)
            conf = float((r1["conf"] + r2["conf"]) / 2)
            hits.append(TagHit(tag, x, y, max(w, 10), max(h, 10), conf, False))

    # ── Fuzzy pass (high-conf tokens only) ────────────────────────────────
    _FUZZY = re.compile(r"^AC([A-U])$", re.IGNORECASE)
    for _, row in data[data["conf"] > 70].iterrows():
        raw = re.sub(r"[^A-Z0-9]", "", str(row["text"]).upper())
        m = _FUZZY.match(raw)
        if m:
            tag = f"AC-{m.group(1)}"
            if known_tags and tag not in known_tags:
                continue
            hits.append(TagHit(tag, int(row["left"]), int(row["top"]),
                                int(row["width"]), int(row["height"]),
                                float(row["conf"]), True))

    return hits


def ocr_floor_page(
    pdf_path: Path,
    page_0idx: int,
    dpi: int,
    psm: int,
    min_conf: float,
    known_tags: set[str],
) -> tuple[Image.Image, list[TagHit]]:
    """Render page at DPI and OCR-detect unit tags. Returns (color_img, hits)."""
    color_img = _render_page(pdf_path, page_0idx, dpi)
    data = _ocr_image(color_img, psm, min_conf)
    hits = _extract_hits_from_data(data, known_tags, psm)

    # PSM fallback if sparse results
    if len(hits) < 3 and psm != 12:
        logging.debug(f"  Page {page_0idx+1}: only {len(hits)} hits with psm {psm}, retrying with psm 12")
        data2 = _ocr_image(color_img, 12, min_conf)
        hits.extend(_extract_hits_from_data(data2, known_tags, 12))

    return color_img, _deduplicate_hits(hits)


# ─────────────────────────────────────────────────────────────────────────────
# Step 5 β€” Annotate and save image
# ─────────────────────────────────────────────────────────────────────────────

def _build_color_map(tags: list[str]) -> dict[str, tuple]:
    palette = itertools.cycle(_PALETTE)
    return {tag: next(palette) for tag in sorted(tags)}


def _review_status(hit: TagHit) -> str:
    """Map a hit's confidence/fuzzy flag to a review status label."""
    if hit.fuzzy or hit.conf < 0.7:
        return "review"        # yellow β€” likely hallucination, confirm or delete
    if hit.conf < 0.9:
        return "recovered"     # orange β€” found offset via wide snap, quick confirm
    return "confirmed"         # green β€” OCR-grounded, trust it


_STATUS_COLOR = {
    "confirmed": None,           # use tag color
    "recovered": (255, 140, 0),  # orange
    "review": (230, 220, 40),    # yellow
}


def annotate_and_save(
    floor_name: str,
    page_idx: int,
    color_img: Image.Image,
    hits: list[TagHit],
    out_dir: Path,
    tag_colors: dict[str, tuple],
) -> Path:
    img = color_img.copy()
    draw = ImageDraw.Draw(img)

    try:
        font = ImageFont.truetype("arial.ttf", 22)
        idfont = ImageFont.truetype("arialbd.ttf", 30)
    except (OSError, IOError):
        font = ImageFont.load_default()
        idfont = font

    for i, hit in enumerate(hits, start=1):
        status = _review_status(hit)
        color = _STATUS_COLOR[status] or tag_colors.get(hit.tag, (220, 50, 50))
        # Bounding box
        draw.rectangle(
            [hit.x, hit.y, hit.x + hit.w, hit.y + hit.h],
            outline=color,
            width=3,
        )
        # Label background + text above the box: "#<id> <tag>"
        label = f"#{i} {hit.tag}"
        lx, ly = hit.x, max(0, hit.y - 34)
        tw = len(label) * 16
        draw.rectangle([lx, ly, lx + tw, ly + 32], fill=color)
        draw.text((lx + 3, ly + 1), label, fill=(255, 255, 255), font=idfont)

    safe = re.sub(r"[^\w]", "_", floor_name)
    out_path = out_dir / f"floor_{page_idx:03d}_{safe}_annotated.png"
    img.save(out_path, format="PNG")
    return out_path


def write_review_csv(
    floor_name: str, page_idx: int, hits: list[TagHit], out_dir: Path,
) -> Path:
    """
    Emit a per-floor review sheet. Box #ids match the annotated image.
    You edit the `action` column:
        keep   (or blank) β€” accept the box as-is
        delete            β€” remove it (false positive / hallucination)
        AC-X              β€” relabel to a different tag
    Then run:  analyze_blueprint.py <pdf> --apply-review
    The `status` column is pre-filled so you can focus on non-'confirmed' rows.
    """
    safe = re.sub(r"[^\w]", "_", floor_name)
    path = out_dir / f"floor_{page_idx:03d}_{safe}_review.csv"
    with open(path, "w", newline="", encoding="utf-8") as f:
        w = csv.writer(f)
        w.writerow(["id", "tag", "status", "action",
                    "x", "y", "w", "h", "page_num", "floor_name"])
        for i, h in enumerate(hits, start=1):
            w.writerow([i, h.tag, _review_status(h), "",
                        h.x, h.y, h.w, h.h, page_idx, floor_name])
    return path


# ─────────────────────────────────────────────────────────────────────────────
# Step 4 β€” Console summary table
# ─────────────────────────────────────────────────────────────────────────────

def print_summary_table(floor_results: FloorResults, schedule_tags: dict[str, dict]) -> None:
    all_tags = sorted(
        set(schedule_tags.keys()) | {tag for floor in floor_results.values() for tag in floor}
    )
    floors = list(floor_results.keys())

    col_w = max((len(t) for t in all_tags), default=4) + 2
    lbl_w = max([6, len("Schedule"), len("Detected"), *(len(f) for f in floors)]) + 2

    header = f"{'Floor':<{lbl_w}}" + "".join(f"{t:>{col_w}}" for t in all_tags) + f"{'Total':>{col_w}}"
    sep = "─" * len(header)
    print()
    print(header)
    print(sep)

    detected_totals: dict[str, int] = {t: 0 for t in all_tags}
    for floor in floors:
        row_counts = {t: len(floor_results[floor].get(t, [])) for t in all_tags}
        total = sum(row_counts.values())
        for t in all_tags:
            detected_totals[t] += row_counts[t]
        row = f"{floor:<{lbl_w}}" + "".join(f"{row_counts[t]:>{col_w}}" for t in all_tags) + f"{total:>{col_w}}"
        print(row)

    print(sep)

    # Schedule row
    sched_row = f"{'Schedule':<{lbl_w}}"
    sched_total = 0
    for t in all_tags:
        qty = schedule_tags.get(t, {}).get("qty") or 0
        sched_row += f"{qty:>{col_w}}"
        sched_total += int(qty)
    print(sched_row + f"{sched_total:>{col_w}}")

    # Detected totals row
    det_total = sum(detected_totals.values())
    det_row = f"{'Detected':<{lbl_w}}" + "".join(f"{detected_totals[t]:>{col_w}}" for t in all_tags) + f"{det_total:>{col_w}}"
    print(det_row)
    print()

    # Reconciliation warnings
    for t in all_tags:
        sched_qty = int(schedule_tags.get(t, {}).get("qty") or 0)
        det_qty = detected_totals[t]
        if sched_qty > 0 and det_qty > sched_qty + 1:
            print(f"[WARNING] Detected > Schedule for {t}  ({det_qty} detected vs {sched_qty} scheduled)")
        elif sched_qty > 0 and det_qty == 0:
            print(f"[WARNING] {t} appears in schedule (qty {sched_qty}) but was not detected on any floor")


# ─────────────────────────────────────────────────────────────────────────────
# Interactive checkpoint helper
# ─────────────────────────────────────────────────────────────────────────────

_auto_yes = False  # set to True via --yes flag


def _confirm(prompt: str = "Continue? [y/n]: ") -> bool:
    if _auto_yes:
        print(prompt + "y (auto)")
        return True
    try:
        answer = input(prompt).strip().lower()
        return answer in ("y", "yes", "")
    except (EOFError, KeyboardInterrupt):
        print()
        return False


# ─────────────────────────────────────────────────────────────────────────────
# CLI entry point
# ─────────────────────────────────────────────────────────────────────────────

def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description="HVAC Blueprint Analyzer")
    p.add_argument("pdf", type=Path, help="Path to the blueprint PDF")
    p.add_argument("--dpi", type=int, default=300, help="Render DPI (default 300)")
    p.add_argument("--out-dir", type=Path, default=Path("output"), help="Output directory for annotated images")
    p.add_argument("--psm", type=int, default=11, help="Tesseract PSM mode (default 11)")
    p.add_argument("--min-conf", type=float, default=40.0, help="Minimum OCR confidence (default 40)")
    p.add_argument(
        "--step",
        choices=["schedule", "classify", "ocr-one"],
        default=None,
        help="Stop after this phase for interactive confirmation",
    )
    p.add_argument("--tile", action="store_true", help="Use tiled OCR for very large pages")
    p.add_argument("--schedule-page", type=int, default=None,
                   help="1-based page number of the equipment schedule (skips auto-detection)")
    p.add_argument("--schedule-region", type=str, default=None,
                   help="Read ONLY this rectangle of --schedule-page as the schedule, "
                        "as 0-1 fractions 'x0,y0,x1,y1' (set by the GUI's "
                        "'Manually select schedule' tool). Forces a fresh extract.")
    p.add_argument("--page", type=int, default=None,
                   help="Process ONLY this 1-based PDF page (must be a plan page). "
                        "Use for one-floor-at-a-time runs: detect this floor, review "
                        "it, then move to the next.")
    p.add_argument("--pages", type=str, default=None,
                   help="Process a RANGE/list of 1-based plan pages in order, e.g. "
                        "'4-24' or '4,6,8' or '4-9,22'. Each floor's outputs are written "
                        "as it finishes, so you can review early floors while later ones "
                        "are still detecting.")
    p.add_argument("--refresh-schedule", action="store_true",
                   help="Ignore cached schedule and re-extract (calls Gemini again)")
    p.add_argument("--refresh-detections", action="store_true",
                   help="Ignore cached floor detections and re-detect (calls Gemini again)")
    p.add_argument("--consensus", type=int, default=1, choices=[1, 2, 3],
                   help="Multi-offset tile consensus passes (2-3) to raise recall on "
                        "units that fall on tile boundaries. Costs NΓ— the Gemini calls.")
    p.add_argument("--tile-size", type=int, default=3000,
                   help="Tile size in px (default 3000). Smaller (e.g. 1800) = finer "
                        "spatial resolution so small/faint units stay larger to the "
                        "model β€” better recall on tiny units, more tiles/cost.")
    p.add_argument("--render-pdf", type=Path, default=None,
                   help="Render floor images from this (crisp/un-flattened) PDF "
                        "instead of the main PDF. Must share page order + size.")
    p.add_argument("--detector", choices=["gemini", "qwen"], default="gemini",
                   help="Which vision model finds the units (verify always uses "
                        "Gemini). Qwen runs via OpenRouter.")
    p.add_argument("--qwen-model", default="qwen/qwen2.5-vl-72b-instruct",
                   help="OpenRouter model id for --detector qwen")
    p.add_argument("--recall-prompt", action="store_true",
                   help="Use the inclusive recall-first detection prompt (be "
                        "inclusive; the verify step removes false positives)")
    p.add_argument("--fp-filter", action="store_true",
                   help="Precision pass: drop false positives via a Qwen+Claude "
                        "existence vote on uncertain boxes (needs OPENROUTER_API_KEY)")
    p.add_argument("--all-tags", action="store_true",
                   help="Search EVERY schedule tag incl. qty=0 (schedule counts are "
                        "unreliable; fp-filter + reconcile_schedule.py handle precision)")
    p.add_argument("--runs", type=int, default=1,
                   help="Run the whole detection N times and UNION the hits. Beats "
                        "run-to-run VLM jitter (stochastic close same-tag misses). "
                        "Costs NΓ— the detection calls.")
    p.add_argument("--no-yolo", action="store_true",
                   help="Skip saving YOLO training labels to dataset/")
    p.add_argument("--yes", "-y", action="store_true",
                   help="Auto-confirm all checkpoints (non-interactive run)")
    p.add_argument("--reclassify", action="store_true",
                   help="Rebuild pages_manifest.csv instead of reusing the cached one")
    p.add_argument("--classify-only", action="store_true",
                   help="Extract schedule + classify pages + write pages_manifest.csv, "
                        "then stop (no detection). Used by the GUI to list floors.")
    p.add_argument("--apply-review", action="store_true",
                   help="Ingest edited floor_*_review.csv files in --out-dir: apply "
                        "keep/delete/relabel actions, rewrite detection caches + YOLO "
                        "labels, and append corrections to corrections_log.csv")
    return p.parse_args()


# ─────────────────────────────────────────────────────────────────────────────
# Human-in-the-loop review ingestion (--apply-review)
# ─────────────────────────────────────────────────────────────────────────────

def apply_review(out_dir: Path, pdf_path: Path, dpi: int,
                 save_yolo: bool = True) -> None:
    """
    Read every floor_*_review.csv in out_dir, apply the human-entered `action`
    column, and rewrite that floor's detection cache, annotated image, and YOLO
    labels. Every change is appended to out_dir/corrections_log.csv β€” the
    evidence trail of what the detector got wrong, for later tuning / YOLO data.

    action column values (case-insensitive):
        ''/keep        accept the box as-is (status promoted to confirmed)
        delete/no/x    drop the box (false positive)
        AC-X           relabel to that tag (and keep)
    """
    import json

    review_files = sorted(out_dir.glob("floor_*_review.csv"))
    if not review_files:
        print(f"  No floor_*_review.csv files found in {out_dir}.")
        return

    log_path = out_dir / "corrections_log.csv"
    new_log = not log_path.exists()
    log_f = open(log_path, "a", newline="", encoding="utf-8")
    log_w = csv.writer(log_f)
    if new_log:
        log_w.writerow(["page_num", "floor_name", "id", "tag",
                        "old_status", "action", "result", "x", "y", "w", "h"])

    grand_kept = grand_deleted = grand_relabeled = grand_added = 0

    for rf in review_files:
        rows = list(csv.DictReader(open(rf, encoding="utf-8")))
        if not rows:
            continue
        page_num = int(rows[0]["page_num"])
        floor_name = rows[0]["floor_name"]

        kept: list[TagHit] = []
        n_del = n_relabel = n_added = 0
        for r in rows:
            action = (r.get("action") or "").strip().lower()
            tag = r["tag"]
            old_status = r.get("status", "")
            if old_status == "added":
                n_added += 1
            hit = TagHit(tag, int(r["x"]), int(r["y"]), int(r["w"]), int(r["h"]),
                         0.99, False)  # human-confirmed β†’ top confidence, not fuzzy

            if action in ("delete", "del", "no", "x", "remove"):
                n_del += 1
                log_w.writerow([page_num, floor_name, r["id"], tag, old_status,
                                action, "deleted", r["x"], r["y"], r["w"], r["h"]])
                continue

            result = "kept"
            new_tag = _normalize_tag(action) if action else None
            if new_tag and new_tag != tag:
                hit = hit._replace(tag=new_tag)
                n_relabel += 1
                result = f"relabeled {tag}->{new_tag}"
            kept.append(hit)
            # Only log rows the human actually touched or that weren't confirmed
            if action or old_status != "confirmed":
                log_w.writerow([page_num, floor_name, r["id"], hit.tag, old_status,
                                action or "keep", result,
                                hit.x, hit.y, hit.w, hit.h])

        grand_kept += len(kept)
        grand_deleted += n_del
        grand_relabeled += n_relabel
        grand_added += n_added

        # Rewrite detection cache for this floor
        color_img = _render_page(pdf_path, page_num - 1, dpi)
        img_w, img_h = color_img.size
        cache_path = _detection_cache_path(out_dir, page_num, floor_name)
        cache_path.write_text(
            json.dumps({"hits": [h._asdict() for h in kept],
                        "img_w": img_w, "img_h": img_h}, indent=2),
            encoding="utf-8",
        )
        # Redraw annotated image (all green now β€” human-confirmed)
        tag_colors = _build_color_map(sorted({h.tag for h in kept}) or ["AC-A"])
        annotate_and_save(floor_name, page_num, color_img, kept, out_dir, tag_colors)
        if save_yolo and kept:
            _save_yolo_labels(pdf_path, page_num, color_img, kept, img_w, img_h)

        print(f"  {rf.name}: {len(kept)} kept ({n_added} added), "
              f"{n_del} deleted, {n_relabel} relabeled")

    log_f.close()
    print(f"\n  Totals: {grand_kept} kept ({grand_added} of them newly added by you), "
          f"{grand_deleted} deleted, {grand_relabeled} relabeled "
          f"across {len(review_files)} floor(s).")
    print(f"  Corrections logged to: {log_path}")
    print(f"  Detection caches + YOLO labels updated with your corrections.")


def main() -> None:
    global _auto_yes
    # Force UTF-8 stdout/stderr on Windows so non-ASCII chars don't crash piped runs
    try:
        sys.stdout.reconfigure(encoding="utf-8", errors="replace")
        sys.stderr.reconfigure(encoding="utf-8", errors="replace")
    except Exception:
        pass
    args = parse_args()
    _auto_yes = args.yes

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    if not args.pdf.exists():
        logging.error(f"PDF not found: {args.pdf}")
        sys.exit(1)

    args.out_dir.mkdir(parents=True, exist_ok=True)

    # ── Apply-review mode: ingest human corrections, then exit ────────────────
    if args.apply_review:
        print(f"\n{'='*60}")
        print(f"  APPLY REVIEW β€” ingesting corrections from {args.out_dir}")
        print(f"{'='*60}\n")
        apply_review(args.out_dir, args.pdf, args.dpi, save_yolo=not args.no_yolo)
        return

    # ── Checkpoint 1: Schedule extraction ────────────────────────────────────
    print(f"\n{'='*60}")
    print(f"  CHECKPOINT 1 β€” Extracting equipment schedule")
    print(f"{'='*60}")
    print(f"  PDF : {args.pdf}")
    print()

    _region = None
    if args.schedule_region:
        try:
            _region = tuple(float(v) for v in args.schedule_region.split(","))
            assert len(_region) == 4
        except Exception:
            print(f"  [WARNING] bad --schedule-region '{args.schedule_region}' β€” ignoring")
            _region = None
    schedule_tags = extract_schedule(args.pdf, args.dpi, args.schedule_page,
                                     out_dir=args.out_dir, refresh=args.refresh_schedule,
                                     region=_region)

    if schedule_tags:
        print(f"  Found {len(schedule_tags)} unit tag(s):\n")
        for tag, info in sorted(schedule_tags.items()):
            qty_str = str(info["qty"]) if info["qty"] is not None else "?"
            utype = info["unit_type"] or "(type unknown)"
            model_str = info.get("model_number") or ""
            company_str = info.get("company") or ""
            extra = ""
            if company_str or model_str:
                extra = f"  [{' '.join(filter(None, [company_str, model_str]))}]"
            print(f"    {tag:6s}  qty={qty_str:>3}  {utype}{extra}")
    else:
        print("  [WARNING] No unit tags found in schedule β€” tags will be inferred from OCR.")

    if args.step == "schedule":
        print()
        if not _confirm("  Results look correct? Continue to page classification? [y/n]: "):
            print("  Stopped at schedule step.")
            return

    # ── Checkpoint 2: Page classification ────────────────────────────────────
    print(f"\n{'='*60}")
    print(f"  CHECKPOINT 2 β€” Classifying pages")
    print(f"{'='*60}\n")

    import csv
    manifest_path = args.out_dir / "pages_manifest.csv"

    # Reuse a cached manifest from a prior run of this blueprint (classification
    # is slow β€” it OCRs every page title β€” and never changes for a given PDF).
    if manifest_path.exists() and not args.reclassify:
        with open(manifest_path, newline="", encoding="utf-8") as f:
            page_manifest = [
                {"page_num": int(r["page_num"]), "page_type": r["page_type"],
                 "floor_name": r["floor_name"], "title": r["title"]}
                for r in csv.DictReader(f)
            ]
        print(f"  Loaded cached page manifest: {manifest_path}")
        print(f"  (use --reclassify to rebuild it)")
    else:
        page_manifest = classify_pages(args.pdf)
        with open(manifest_path, "w", newline="", encoding="utf-8") as f:
            writer = csv.DictWriter(f, fieldnames=["page_num", "page_type", "floor_name", "title"])
            writer.writeheader()
            writer.writerows(page_manifest)
        print(f"  Page manifest saved: {manifest_path}")

    plan_pages = [p for p in page_manifest if p["page_type"] == "plan"]
    for entry in page_manifest:
        skip = "  (skipped)" if entry["page_type"] != "plan" else ""
        print(f"  Page {entry['page_num']:>3}:  {entry['page_type']:<10}  {entry['floor_name']:<20}  [{entry['title']}]{skip}")
    print(f"\n  {len(plan_pages)} plan page(s) will be processed, {len(page_manifest) - len(plan_pages)} skipped.")

    if args.classify_only:
        print(f"  --classify-only: {len(plan_pages)} plan page(s) listed. Stopping.")
        return

    if not plan_pages:
        logging.error("No plan pages found. Cannot continue.")
        sys.exit(1)

    # ── --page / --pages: restrict to specific plan pages ────────────────────
    selected: list[int] | None = None
    if args.page is not None:
        selected = [args.page]
    elif args.pages:
        selected = []
        for part in args.pages.split(","):
            part = part.strip()
            if "-" in part:
                lo, hi = part.split("-", 1)
                selected.extend(range(int(lo), int(hi) + 1))
            elif part:
                selected.append(int(part))

    if selected is not None:
        plan_by_num = {p["page_num"]: p for p in plan_pages}
        bad = [n for n in selected if n not in plan_by_num]
        if bad:
            plan_nums = ", ".join(str(p["page_num"]) for p in plan_pages)
            logging.error(f"Page(s) {bad} are not plan pages. Plan pages are: {plan_nums}")
            sys.exit(1)
        # preserve requested order, de-duplicated
        seen: set[int] = set()
        plan_pages = [plan_by_num[n] for n in selected
                      if not (n in seen or seen.add(n))]
        names = ", ".join(f"{p['page_num']}={p['floor_name']}" for p in plan_pages)
        print(f"\n  Processing {len(plan_pages)} selected floor(s): {names}")

    if args.step in ("schedule", "classify"):
        print()
        if not _confirm("  Floor list correct? Continue to OCR? [y/n]: "):
            print("  Stopped at classify step.")
            return

    # ── Checkpoint 3: OCR + annotate ─────────────────────────────────────────
    # By default consider only tags with non-zero scheduled quantity (drops
    # false-positive tags). --all-tags searches EVERY schedule tag β€” the schedule
    # counts are unreliable (e.g. AC-B listed qty 0 but real units exist), so the
    # fp-filter handles precision and the schedule-reconcile step flags conflicts.
    if args.all_tags:
        known_tags = set(schedule_tags.keys())
        print(f"  --all-tags: searching all {len(known_tags)} schedule tag(s), "
              f"including qty=0 (fp-filter + reconcile handle precision)")
    else:
        known_tags = {t for t, info in schedule_tags.items() if (info.get("qty") or 0) > 0}
        if not known_tags:
            known_tags = set(schedule_tags.keys())
        skipped_zero = sorted(set(schedule_tags.keys()) - known_tags)
        if skipped_zero:
            print(f"  Skipping detection for {len(skipped_zero)} qty=0 tag(s): {', '.join(skipped_zero)}")
    all_tags = list(sorted(known_tags)) if known_tags else [f"AC-{chr(65+i)}" for i in range(21)]
    tag_colors = _build_color_map(all_tags)
    floor_results: FloorResults = {}

    pages_to_process = plan_pages[:1] if args.step == "ocr-one" else plan_pages

    print(f"\n{'='*60}")
    print(f"  CHECKPOINT 3 β€” OCR{'  (first floor only)' if args.step == 'ocr-one' else ''}")
    print(f"{'='*60}\n")

    for entry in pages_to_process:
        page_0 = entry["page_num"] - 1
        floor_name = entry["floor_name"]
        print(f"  Processing page {entry['page_num']} ({floor_name}) at {args.dpi} DPI…", end=" ", flush=True)

        try:
            color_img, hits = gemini_detect_floor_page(
                args.pdf, page_0, args.dpi, known_tags,
                args.out_dir, entry["page_num"], floor_name,
                save_yolo=not args.no_yolo,
                tile_size=args.tile_size,
                refresh=args.refresh_detections,
                consensus=args.consensus,
                render_pdf=args.render_pdf,
                detector=args.detector,
                qwen_model=args.qwen_model,
                recall_prompt=args.recall_prompt,
                fp_filter=args.fp_filter,
                runs=args.runs,
            )
        except Exception as exc:
            print(f"FAILED β€” {exc}")
            logging.warning(f"Page {entry['page_num']} detection failed: {exc} β€” skipping")
            continue

        # Accumulate into floor_results (multiple sheets may share a floor name)
        floor_results.setdefault(floor_name, {})
        for hit in hits:
            floor_results[floor_name].setdefault(hit.tag, []).append(hit)

        # Annotate and save
        out_path = annotate_and_save(
            floor_name, entry["page_num"], color_img, hits, args.out_dir, tag_colors
        )
        review_path = write_review_csv(
            floor_name, entry["page_num"], hits, args.out_dir
        )

        tag_summary = ", ".join(
            f"{t}Γ—{len(floor_results[floor_name][t])}"
            for t in sorted(floor_results[floor_name])
        )
        n_review = sum(1 for h in hits if _review_status(h) != "confirmed")
        print(f"done  ->  {tag_summary or 'no tags found'}")
        print(f"    Annotated image: {out_path}")
        print(f"    Review sheet:    {review_path}"
              f"  ({n_review} box(es) need review)" if n_review else
              f"    Review sheet:    {review_path}")

    if args.step == "ocr-one":
        print()
        if not _confirm("  Open the annotated image and verify boxes. Continue with all floors? [y/n]: "):
            print("  Stopped at ocr-one step.")
            return
        # Continue with remaining floors
        print(f"\n  Continuing with remaining {len(plan_pages) - 1} floor(s)…\n")
        for entry in plan_pages[1:]:
            page_0 = entry["page_num"] - 1
            floor_name = entry["floor_name"]
            print(f"  Processing page {entry['page_num']} ({floor_name}) at {args.dpi} DPI…", end=" ", flush=True)
            try:
                color_img, hits = gemini_detect_floor_page(
                    args.pdf, page_0, args.dpi, known_tags,
                    args.out_dir, entry["page_num"], floor_name,
                    save_yolo=not args.no_yolo,
                    tile_size=args.tile_size,
                    refresh=args.refresh_detections,
                    consensus=args.consensus,
                    render_pdf=args.render_pdf,
                    detector=args.detector,
                    qwen_model=args.qwen_model,
                    recall_prompt=args.recall_prompt,
                    fp_filter=args.fp_filter,
                    runs=args.runs,
                )
            except Exception as exc:
                print(f"FAILED β€” {exc}")
                continue
            floor_results.setdefault(floor_name, {})
            for hit in hits:
                floor_results[floor_name].setdefault(hit.tag, []).append(hit)
            out_path = annotate_and_save(
                floor_name, entry["page_num"], color_img, hits, args.out_dir, tag_colors
            )
            write_review_csv(floor_name, entry["page_num"], hits, args.out_dir)
            tag_summary = ", ".join(
                f"{t}Γ—{len(floor_results[floor_name][t])}"
                for t in sorted(floor_results[floor_name])
            )
            print(f"done  ->  {tag_summary or 'no tags found'}")
            print(f"    Annotated image: {out_path}")

    # ── Checkpoint 4: Summary table ───────────────────────────────────────────
    print(f"\n{'='*60}")
    print(f"  CHECKPOINT 4 β€” Summary")
    print(f"{'='*60}")
    print_summary_table(floor_results, schedule_tags)
    print(f"  Annotated images saved to: {args.out_dir.resolve()}")


if __name__ == "__main__":
    main()