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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
"""
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) ───────────────
_TAG_STRICT = re.compile(r"\bAC[-\s]?[A-U]\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)

# ── 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


_TITLE_KEYWORDS = re.compile(
    r"\b(MECHANICAL|HVAC|AIR\s+RISER|RISER|DIAGRAM|PLAN|SCHEDULE|DETAIL|SECTION|BULKHEAD|CELLAR|ROOF)\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
            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()


def _ocr_page_title(pdf_path: Path, page_0idx: int) -> str | None:
    """Render page at 150 DPI and search ALL OCR lines for the drawing title."""
    doc = fitz.open(pdf_path)
    pix = doc.load_page(page_0idx).get_pixmap(matrix=fitz.Matrix(150/72, 150/72), alpha=False)
    img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
    ocr_txt = pytesseract.image_to_string(img, config="--oem 3 --psm 6")
    # Try explicit DRAWING TITLE label first
    title = _extract_explicit_title(ocr_txt)
    if title and _TITLE_KEYWORDS.search(title):
        return title
    # Full-page scan picking the highest-ratio matching line
    return _extract_heuristic_title(ocr_txt, max_lines=None)


_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.upper()
    blob = f"{t}\n{x}"
    if "INDOOR UNIT SCHEDULE" in blob or "SCHEDULE" in t:
        return "schedule"
    # 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 "NOTE" in t and "PLAN" not in t:
        return "notes"
    if "PLAN" in t or "FLOOR" in t or "LEVEL" in t or "ROOF" in t or "CELLAR" in t or "BULKHEAD" in t:
        return "plan"
    return "other"


def _normalize_tag(raw: str) -> str | None:
    """Return 'AC-X' form or None."""
    raw = re.sub(r"[^A-Z0-9\-]", "", raw.upper())
    m = _TAG_STRICT.search(raw)
    if m:
        tag = m.group(0).upper().replace(" ", "-")
        if "-" not in tag:
            tag = f"AC-{tag[-1]}"
        return tag if re.match(r"^AC-[A-U]$", tag) else None
    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
        nums = [int(v) for v in _INT_PAT.findall(line)]
        qty = next((n for n in nums if 0 <= 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), utype)
        if key in seen:
            continue
        seen.add(key)
        rows.append({"page_num": page_num, "tag": tag, "qty_required": qty, "unit_type": utype})
    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. "
        "Find the table titled 'INDOOR UNIT SCHEDULE' or 'VARIABLE REFRIGERANT VOLUME – INDOOR UNIT SCHEDULE'. "
        "Extract every row from that table only (not the outdoor unit schedule or any other table). "
        "Return the data as CSV with exactly these columns: tag,qty,unit_type\n"
        "Rules:\n"
        "- tag must be in the form AC-A through AC-U\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)\n"
        "- Include all rows, even those with qty=0\n"
        "- Output ONLY the CSV rows, no headers, no explanations."
    )

    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=2048, temperature=0.0),
    )

    rows: list[RowParse] = []
    for line in response.text.strip().splitlines():
        line = line.strip().strip(",")
        if not line:
            continue
        parts = [p.strip() for p in line.split(",")]
        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 ""
        rows.append(RowParse(
            tag=tag,
            qty_required=qty,
            unit_type=utype,
            confidence=0.95,
            source="gemini_vision",
            raw_text=line,
        ))
    return rows


_INDOOR_HEADER = re.compile(r"INDOOR\s+UNIT\s+SCHEDULE", 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) -> 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.
    """
    # ── 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…")
            for i in candidates_idx:
                print(f"    page {i}/{total}…", end="\r", flush=True)
                txt = pdf.pages[i - 1].extract_text() or ""
                title = _extract_page_title(txt)
                ptype = _classify_page_context(title, txt)
                if ptype == "schedule":
                    schedule_pages.append(i)
            print()  # clear the \r line

    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}…")
        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="",
                    )
                )

            # Count unique tags found so far from this page
            ocr_tag_count = len({c.tag for c in candidates})
            if ocr_tag_count < 5:
                print(f"  OCR found only {ocr_tag_count} tag(s) β€” 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}
        for tag, row in by_tag.items()
        if row.qty_required is not None or row.unit_type
    }

    # 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
# ─────────────────────────────────────────────────────────────────────────────

def _floor_name_from_title(title: str | None) -> str | None:
    """
    Extract a human-readable floor label from a page title.
      'MECHANICAL 4TH FLOOR PLAN'               -> '4th Floor'
      'MECHANICAL TYPICAL 4TH THRU 5TH FLOOR PLAN' -> 'Typical 4th-5th Floor'
      'MECHANICAL ROOF PLAN'                     -> 'Roof'
      'MECHANICAL CELLAR PLAN'                   -> 'Cellar'
      'MECHANICAL BULKHEAD PLAN'                 -> 'Bulkhead'
    """
    if not title:
        return None
    t = title.upper()
    t = re.sub(r"^MECHANICAL\s*", "", t).strip()
    t = re.sub(r"\s*FLOOR\s*PLAN\s*$", "", t).strip()
    t = re.sub(r"\s*PLAN\s*$", "", t).strip()
    if not t:
        return None
    # Normalize ordinals: 1ST -> 1st, 2ND -> 2nd, etc.
    t = re.sub(r"\b(\d+)(ST|ND|RD|TH)\b", lambda m: m.group(1) + m.group(2).lower(), t)
    t = re.sub(r"\s+THRU\s+", "-", t)
    return t.title()


def classify_pages(pdf_path: Path) -> list[dict]:
    """
    Returns list of {page_num, page_type, floor_name, title} for every page.
    """
    manifest = []
    with pdfplumber.open(pdf_path) as pdf:
        total = len(pdf.pages)
        for i, page in enumerate(pdf.pages, start=1):
            print(f"    classifying page {i}/{total}…", end="\r", flush=True)
            txt = page.extract_text() or ""
            title = _extract_page_title(txt)

            # If pdfplumber found no usable drawing title (common on flattened pages
            # where only the title block vectors are readable), fall back to OCR and
            # search the entire page image for the drawing title.
            if title is None:
                title = _ocr_page_title(pdf_path, i - 1)

            ptype = _classify_page_context(title, txt)

            floor_name = _floor_name_from_title(title)
            if not floor_name:
                m = _FLOOR_PAT.search(txt)
                floor_name = m.group(0).title() if m else f"Page {i}"

            if i == total:
                print()  # clear the \r line
            manifest.append({
                "page_num": i,
                "page_type": ptype,
                "floor_name": floor_name,
                "title": title or "(no title)",
            })
    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"


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 _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 _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,
) -> 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 = (
        "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.'
    )

    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()
        raw = re.sub(r"^```[a-z]*\n?", "", raw, flags=re.MULTILINE)
        raw = re.sub(r"```$", "", raw.strip())
    except Exception as e:
        logging.warning(f"  Tile ({x0},{y0}) Gemini error: {e}")
        return []

    import json as _json
    try:
        dets = _json.loads(raw).get("detections", [])
    except _json.JSONDecodeError:
        dets = []

    hits = []
    for det in dets:
        tag = _normalize_tag(det.get("tag", ""))
        if not tag or (known_tags and tag not in known_tags):
            continue
        # Convert 0-1000 normalized tile coords β†’ full-image pixels
        xn, yn = det["xmin"] / 1000, det["ymin"] / 1000
        xn2, yn2 = det["xmax"] / 1000, det["ymax"] / 1000
        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_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,
) -> 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]).
    """
    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(pdf_path, page_0idx, dpi)
    img_w, img_h = color_img.size

    # ── Load from cache if available ──────────────────────────────────────────
    if cache_path.exists():
        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

    # ── Call Gemini ───────────────────────────────────────────────────────────
    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)

    # ── Tile the image and query each tile ────────────────────────────────────
    tiles = _make_tiles(color_img, tile_size=tile_size, overlap=tile_size // 10)
    all_hits: list[TagHit] = []
    known_list = sorted(known_tags) if known_tags else []

    for idx, (x0, y0, tile_img) in enumerate(tiles):
        print(f"  tile {idx+1}/{len(tiles)} ({x0},{y0})…", end=" ", flush=True)
        tile_hits = _gemini_call_tile(
            client, genai_types, tile_img, x0, y0,
            img_w, img_h, known_list, page_num,
        )
        print(f"{len(tile_hits)} hit(s)")
        all_hits.extend(tile_hits)

    # ── Deduplicate across tiles (IOU > 0.3 same tag β†’ keep one) ─────────────
    hits = _deduplicate_hits(all_hits, iou_threshold=0.3)

    # ── Verify each hit + refine its box (drops false positives) ─────────────
    if hits:
        print(f"  verifying {len(hits)} hit(s)…", end=" ", flush=True)
        verified = []
        rejected = 0
        for h in hits:
            r = _refine_hit_box(client, genai_types, color_img, h)
            if r is None:
                rejected += 1
            else:
                verified.append(r)
        hits = verified
        print(f"{len(hits)} kept, {rejected} rejected")

    # ── 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 a GENEROUS REVIEW BOX covering the complete indoor unit assembly:\n"
        "  - the full rectangular unit body\n"
        "  - the exact tag label\n"
        "  - nearby connected duct/piping stubs that make the unit identifiable\n"
        "Do NOT return a box around only the text label.\n"
        "Do NOT return a box around only a duct segment.\n"
        "If the label and unit body are separated, include both in one box.\n"
        "Prefer a slightly larger box over one that cuts off the unit or 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)
        pad_x = max(25, int(new_w * 0.08))
        pad_y = max(25, int(new_h * 0.10))
        new_x = max(0, new_x - pad_x)
        new_y = max(0, new_y - pad_y)
        new_w = min(W - new_x, new_w + 2 * pad_x)
        new_h = min(H - new_y, new_h + 2 * pad_y)
        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 _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 _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 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)
    except (OSError, IOError):
        font = ImageFont.load_default()

    for hit in hits:
        color = (220, 220, 50) if hit.fuzzy else 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
        label = hit.tag
        lx, ly = hit.x, max(0, hit.y - 20)
        tw = len(label) * 10
        draw.rectangle([lx, ly, lx + tw, ly + 18], fill=color)
        draw.text((lx + 2, ly + 1), label, fill=(255, 255, 255), font=font)

    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


# ─────────────────────────────────────────────────────────────────────────────
# 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, 10, *(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 _matches_floor_filter(entry: dict, floor_filter: str | None) -> bool:
    if not floor_filter:
        return True
    needle = floor_filter.strip().lower()
    floor_name = str(entry.get("floor_name") or "").lower()
    title = str(entry.get("title") or "").lower()
    return needle in floor_name or needle in title


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("--refresh-schedule", action="store_true",
                   help="Ignore cached schedule and re-extract (calls Gemini again)")
    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("--page", type=int, default=None,
                   help="Only process this 1-based PDF page number")
    p.add_argument("--floor", type=str, default=None,
                   help="Only process plan pages whose floor name/title contains this text")
    return p.parse_args()


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)

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

    schedule_tags = extract_schedule(args.pdf, args.dpi, args.schedule_page,
                                     out_dir=args.out_dir, refresh=args.refresh_schedule)

    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)"
            print(f"    {tag:6s}  qty={qty_str:>3}  {utype}")
    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")

    page_manifest = classify_pages(args.pdf)
    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}")

    selected_plan_pages = [
        p for p in plan_pages
        if (args.page is None or p["page_num"] == args.page)
        and _matches_floor_filter(p, args.floor)
    ]

    print(f"\n  {len(plan_pages)} plan page(s) found, {len(page_manifest) - len(plan_pages)} skipped.")
    if args.page is not None or args.floor:
        filters = []
        if args.page is not None:
            filters.append(f"page={args.page}")
        if args.floor:
            filters.append(f"floor contains '{args.floor}'")
        print(f"  Active floor filter: {', '.join(filters)}")
        print(f"  {len(selected_plan_pages)} matching plan page(s) will be processed.")
    else:
        print(f"  {len(selected_plan_pages)} plan page(s) will be processed.")

    # Save manifest so you have a permanent page β†’ floor record
    import csv
    manifest_path = args.out_dir / "pages_manifest.csv"
    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}")

    if not plan_pages:
        logging.error("No plan pages found. Cannot continue.")
        sys.exit(1)
    if not selected_plan_pages:
        logging.error("No plan pages matched the requested --floor/--page filter.")
        print("\n  Available plan pages:")
        for entry in plan_pages:
            print(f"    Page {entry['page_num']:>3}: {entry['floor_name']} [{entry['title']}]")
        sys.exit(1)

    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 ─────────────────────────────────────────
    # Only consider tags with non-zero scheduled quantity (drops false-positive tags)
    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())  # fallback: schedule has no qty info
    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 = selected_plan_pages[:1] if args.step == "ocr-one" else selected_plan_pages
    filtered_run = args.page is not None or bool(args.floor)

    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=3000,
            )
        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
        )

        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}")

    if args.step == "ocr-one" and not filtered_run:
        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=3000,
                )
            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
            )
            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()