File size: 111,124 Bytes
986980c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93490cd
 
2a27681
986980c
2a27681
986980c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93490cd
 
 
 
 
 
 
 
 
 
 
 
986980c
 
 
 
 
c53f299
 
986980c
 
 
 
c53f299
 
 
 
 
 
 
986980c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93490cd
c53f299
93490cd
 
 
 
 
 
 
c53f299
 
 
 
93490cd
c53f299
93490cd
 
 
c53f299
 
93490cd
c53f299
 
 
93490cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c53f299
 
 
 
 
 
93490cd
c53f299
 
 
93490cd
c53f299
 
 
 
 
986980c
 
 
 
 
93490cd
 
 
 
 
 
 
 
 
c53f299
986980c
93490cd
986980c
 
 
93490cd
 
 
986980c
 
 
93490cd
986980c
 
 
 
 
 
 
 
 
 
 
93490cd
 
 
 
 
 
 
 
986980c
 
 
93490cd
 
 
 
 
986980c
93490cd
986980c
 
93490cd
 
986980c
c53f299
93490cd
c53f299
 
93490cd
 
 
 
 
986980c
 
 
 
 
 
 
 
 
 
93490cd
 
986980c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
624939e
 
 
986980c
 
 
 
 
 
624939e
986980c
 
 
 
624939e
986980c
624939e
986980c
 
 
 
624939e
986980c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
624939e
 
 
 
986980c
624939e
 
 
986980c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
624939e
 
 
 
 
986980c
624939e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
986980c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a27681
 
 
 
 
 
 
986980c
 
 
 
2a27681
986980c
 
 
 
 
 
2a27681
986980c
 
 
 
 
 
 
 
 
 
2a27681
986980c
 
 
 
 
 
 
 
 
 
 
 
624939e
 
 
 
986980c
 
 
 
 
624939e
 
 
 
 
986980c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a27681
 
986980c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a27681
 
 
 
 
 
 
 
 
 
 
 
 
 
 
986980c
 
2a27681
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
986980c
 
2a27681
 
 
 
 
 
986980c
2a27681
 
 
 
986980c
 
2a27681
 
 
 
624939e
 
 
986980c
 
2a27681
 
 
986980c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a27681
 
 
 
 
 
986980c
 
 
 
 
 
 
 
 
 
 
 
 
2a27681
986980c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db46f20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
430b61b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a27681
db46f20
 
 
2a27681
 
 
430b61b
2a27681
 
 
db46f20
 
 
 
 
 
2a27681
db46f20
2a27681
 
986980c
2a27681
 
 
 
 
 
986980c
 
 
db46f20
 
986980c
 
 
 
 
 
db46f20
 
 
 
 
 
 
 
986980c
db46f20
986980c
 
 
 
 
 
 
 
db46f20
624939e
db46f20
 
 
624939e
 
 
db46f20
 
 
 
624939e
 
db46f20
986980c
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
"""Hybrid apartment floor-plan layout engine.

Two sources feed one geometry engine and one scorer:

  * a deterministic BACKBONE of architect-correct column blueprints, which
    guarantees a floor of good plans on any plot with no external service, and
  * an optional LLM proposer, which adds creative structural variety on top
    when an API key is configured.

Both emit the same abstract spec β€” a left-to-right list of columns, each a
bottom-to-top list of rooms β€” which this module renders as an EXACT tiling
(gapless and overlap-free by construction) and then repairs with tiling-safe
passes (reorder rooms inside a column, resize inside a column, swap labels)
to enforce the hard rules:

    * external staircase is EXACTLY 12x10, on the road edge, beside the living
    * pooja is a small niche (<= ~28 sqft) and never touches a washroom/utility
    * master bedroom is the biggest bedroom; each attached bath touches its own
    * every requested room exists

Nothing is ever rejected β€” imperfect ("creative") plans are simply ranked
after the clean ones, so the best 5-6 lead the 20.

This follows the architecture of recent research (HouseTune 2024, "Generative
Floor Plan Design with LLMs via RLVR" 2026): a model proposes a structured
JSON layout; deterministic code guarantees the geometry.
"""

from __future__ import annotations

import copy
import itertools
import json
import os
import random
import re
import time
from typing import Dict, List, Optional, Tuple

from .constants import ROOM_MIN_AREA, ROOM_SIZE_RANGES
from .generator import FloorPlan, Room

try:
    from dotenv import load_dotenv
except Exception:                                     # pragma: no cover
    load_dotenv = None

MODEL = os.getenv("LAYOUT_MODEL", "gpt-5.2")
SETBACK_ROAD, SETBACK_OTHER = 6.56, 3.28              # 2 m / 1 m
STAIR_LONG, STAIR_SHORT = 12.0, 10.0                  # fixed staircase block
POOJA_MAX_AREA = 28.0
# NOTE: "attached_bathroom_02" does NOT end with "bathroom", so never test for
# a washroom with .endswith() β€” always use this tuple.
BATHROOMS = ("common_bathroom", "attached_bathroom", "attached_bathroom_02")
WET = BATHROOMS + ("utility_area",)
BEDROOMS = ("master_bedroom", "bedroom_01", "bedroom_02", "bedroom_03")

_SPEC_CACHE: dict = {}
# Human-readable reason the layout model was last unavailable (surfaced in the
# app so a broken key / timeout / missing package is never a silent fallback).
LAST_ERROR: Optional[str] = None

# Set once the container is shown to have no outbound route to the proposer
# endpoint. Without this, EVERY generation re-pays the full network timeout β€”
# which is what made the hosted app sit on a spinner for minutes at a time
# before falling back to the backbone. The backbone alone fills a population,
# so after the first proven failure the model path is skipped outright.
_NET_DEAD = False

# Client-facing wording. Nothing printed from this module names the provider,
# the endpoint or the model id: the Space's Logs tab is visible to anyone with
# the URL, and the product is presented as an AI layout engine throughout.
_ENGINE = "AI layout engine"

# The proposer's credentials. LAYOUT_API_KEY is the name to use; the legacy
# variable is still read so existing deployments keep working.
_KEY_VARS = ("LAYOUT_API_KEY", "OPENAI_API_KEY")


def _api_key_source() -> Tuple[Optional[str], Optional[str]]:
    """(key, name_of_the_env_var_it_came_from). The value is never logged."""
    if load_dotenv is not None:
        load_dotenv()
    for var in _KEY_VARS:
        key = os.getenv(var)
        if key and key.strip():
            return key.strip(), var
    return None, None


def _api_key() -> Optional[str]:
    return _api_key_source()[0]


def available() -> bool:
    """True when the optional LLM proposer is configured. The backbone always
    works, so a False here only means less structural variety."""
    return bool(_api_key())


# ── Layout proposer (optional LLM) ────────────────────────────────────────────

_SYSTEM = """You are a senior Indian residential architect designing APARTMENT
FLATS (builder-floor style). Design floor plans as vertical COLUMNS on a
buildable rectangle. Feet units. The ROAD is at the BOTTOM (south); x grows
EAST; each column's FIRST room touches the road, its LAST room touches the
rear (north).

A layout = left(WEST)->right(EAST) list of columns. Each column has a width
in feet and a bottom->top list of rooms with depths in feet. Column widths
must sum to the buildable width; each column's depths must sum to the
buildable height (the engine normalises small errors β€” the flat is FULLY
tiled, walls shared, NO empty space, like a real apartment).

DESIGN RULES (a practical Indian flat):
- external_staircase: EXACTLY 12 ft x 10 ft (give its column width 10 or
  12 ft) and it must TOUCH AN OUTER WALL: front (road end) or rear (top) of
  any column, or anywhere along the leftmost/rightmost column. NEVER
  landlocked in the interior. There is NO foyer β€” this stair block IS the
  entry, so the LIVING ROOM must share a wall with it DIRECTLY. VARY the
  stair wall across layouts: front-left, front-right, rear-left, rear-right,
  middle of a side column β€” do NOT put it in the same place in every layout.
  The stair column must ALSO contain other rooms stacked with it β€” NEVER a
  column holding only the staircase.
- living_room: LARGE (>= 12 ft x 12 ft), at the front (south half), the hub.
- kitchen: SOUTH-EAST / EAST (east column, front half), 8-10 ft wide.
  Kitchen must NOT touch a bathroom.
- utility_area: COMPULSORY in every layout, attached to the kitchen.
- dining_room: COMPULSORY in every layout, between kitchen and living.
- study: OPTIONAL filler β€” include it ONLY where a column has spare depth
  (e.g. where a foyer would have been); 7-10 ft each side.
- master_bedroom: the BIGGEST bedroom (~12x14+), SOUTH-WEST / WEST.
- other bedrooms: rear (north), each smaller than the master, min 10 ft side.
- attached_bathroom beside the master; attached_bathroom_02 beside the biggest
    secondary bedroom when requested; common_bathroom reachable from the middle;
    bathrooms 5-7 ft wide. NEVER give a bathroom or utility the FULL
  width of a column wider than 8 ft β€” put two services side by side, pair a
  bath with its bedroom, or use the narrow service column. NEVER place
  pooja_room next to any bathroom or utility.
- pooja_room: TINY niche (4x5 to 5x5). When a pooja is requested, EVERY
  layout MUST include one NARROW SERVICE COLUMN (4.5-6.5 ft wide) and the
  pooja goes at its north end β€” NEVER as a full-width strip across a
  10-13 ft column. Below the pooja put a study/corridor/balcony as a buffer,
  then the bathrooms/utility further down that column. In MOST layouts the
  pooja sits NORTH-EAST / north / east; a FEW creative layouts may put it
  elsewhere. In EVERY layout it must NEVER touch a bathroom or utility.
- balcony: at the ROAD FRONT β€” make it the FIRST room of a column (4-6 ft
  deep) with the living/dining right behind it, like a real street-facing
  balcony. Only an occasional variation layout may use the rear instead.
- internal_corridor (optional): a thin 3-4 ft connector bounded by rooms.
- Room proportions must be realistic: no habitable room narrower than 7 ft,
  aspect ratio under ~2.2.
- SIZE HIERARCHY (hard rules): living_room is the BIGGEST public room
  (bigger than dining and kitchen); EVERY bedroom is bigger than EVERY
  bathroom; master_bedroom is the biggest bedroom; pooja is the smallest
  room. A bedroom smaller than a washroom is an instant failure.
- WINDOWS: every bedroom and bathroom must touch an OUTER wall (front, rear,
  left or right edge). The interior belongs to living/dining/kitchen and
  circulation β€” never bury a bedroom or washroom in the centre.

OUTPUT ONLY JSON (no markdown):
{"layouts":[{"columns":[{"width":<ft>,"rooms":[{"name":"<room>","depth":<ft>},
...]},...]},...]}

Produce the requested number of layouts. Every layout must be STRUCTURALLY
unique: a different stair wall, a different column count, bedrooms on
different sides, mirrored arrangements, different stacking order of the
rooms. Two layouts that differ only in room SIZES are NOT unique β€” that is
a failure. COLUMN MATH: an average room needs 7-8 ft of depth, so a column
of height H holds about H/7 rooms β€” BALANCE the room count across columns
(12 rooms in two 30 ft columns = 6 + 6, NEVER 9 + 3; a 3 ft deep bedroom is
an instant failure). If the buildable width is UNDER 26 ft use 2 columns
(each 10-13 ft), or 2 wide columns PLUS one narrow 4.5-6 ft service column β€”
a great tight-plot pattern is: pooja at the very top (north) of the service
column, a study right below it as a buffer, then the bathrooms/utility.
Otherwise use 2-4 columns, and any column holding a living/kitchen/bedroom/
dining must be at least 8 ft wide (only a pure service column may be
4-6 ft). On a small plot use COMPACT depths (habitable 6.5-8 ft, service
3.5-4.5 ft) for EVERY room instead of starving a few rooms. At least HALF the layouts must follow every rule above strictly; the
rest may be more experimental/creative (still fully tiled, still realistic
room sizes). Include EVERY requested room exactly once per layout (except
study, which is optional filler β€” only where space allows); add nothing else
(internal_corridor allowed, foyer NOT allowed)."""


def _chat_json(client, model, user, temperature=0.9, timeout=None):
    kw = dict(model=model, response_format={"type": "json_object"},
              messages=[{"role": "system", "content": _SYSTEM},
                        {"role": "user", "content": user}])
    try:
        r = client.chat.completions.create(temperature=temperature, **kw)
    except Exception as exc:
        if "temperature" in str(exc).lower():
            r = client.chat.completions.create(**kw)
        else:
            raise
    return json.loads(r.choices[0].message.content or "{}")


def _room_guide(names) -> str:
    out = []
    for n in names:
        (wlo, whi), (dlo, dhi) = ROOM_SIZE_RANGES.get(n, ((6, 12), (8, 14)))
        out.append(f"{n}: {wlo}-{whi} ft wide x {dlo}-{dhi} ft deep")
    return "\n".join(out)


def _probe_network(host: str = "api.openai.com") -> Tuple[str, bool]:
    """Called only after every attempt failed. Pins the fault on DNS, TLS or
    the service itself, so the logs say what is actually wrong instead of the
    SDK's bare "Connection error.". Cheap, and never runs on the happy path.

    Returns (human explanation, egress_is_dead). When egress is dead the caller
    stops trying for the rest of the process. The endpoint host is never named
    in the returned text β€” these lines reach the hosted Logs tab.
    """
    import socket
    import ssl
    proxies = sorted(k for k in os.environ if "proxy" in k.lower())
    try:
        socket.gethostbyname(host)
    except Exception as exc:
        return (f"DNS lookup of the {_ENGINE} endpoint failed "
                f"({type(exc).__name__}) -- the container has no outbound "
                f"internet. proxy vars: {proxies or 'none'}", True)
    try:
        ctx = ssl.create_default_context()
        with socket.create_connection((host, 443), timeout=8) as sock:
            with ctx.wrap_socket(sock, server_hostname=host) as tls:
                ver = tls.version()
    except Exception as exc:
        return (f"the {_ENGINE} endpoint resolves but TLS failed "
                f"({type(exc).__name__}) -- egress blocked, missing CA "
                f"certificates, or a proxy. proxy vars: {proxies or 'none'}",
                True)
    return (f"network is fine (TLS {ver}); the failure is at the service level "
            f"(credentials, quota, or model access). "
            f"proxy vars: {proxies or 'none'}", False)


_REDACT = re.compile(
    r"(api\.openai\.com|openai|OpenAI|gpt[-_.]?[\w.]*|sk-[A-Za-z0-9_-]+)",
    re.IGNORECASE)


def _scrub(text: str) -> str:
    """SDK exception text names the vendor, the endpoint and sometimes the key.
    All three reach the hosted Logs tab, which anyone with the Space URL can
    open, so they are replaced before anything is printed. The fault type and
    the chain survive β€” only the identifiers go."""
    return _REDACT.sub("[engine]", str(text))


def _explain(exc: BaseException) -> str:
    """The SDK collapses every network fault into the useless string
    "Connection error.". Walk the __cause__/__context__ chain so the log names
    the real fault: DNS failure, TLS/certificate error, refused, proxy, quota."""
    parts = [f"{type(exc).__name__}: {_scrub(exc)}"]
    seen = {id(exc)}
    cur = exc.__cause__ or exc.__context__
    while cur is not None and id(cur) not in seen and len(parts) < 5:
        parts.append(f"caused by {type(cur).__name__}: {_scrub(cur)}")
        seen.add(id(cur))
        cur = cur.__cause__ or cur.__context__
    return " <- ".join(parts)


def _propose(required, optional, build_w, build_h, n) -> Optional[list]:
    """One proposer call -> layout specs. FAILURES ARE LOUD (printed to the
    console AND kept in LAST_ERROR for the UI) so a silent fall-back can never
    hide a broken key/quota/timeout. Returning None just means the backbone
    carries the whole population."""
    global LAST_ERROR, _NET_DEAD
    if _NET_DEAD:
        # Proven unreachable earlier in this process. Re-trying would cost the
        # full timeout again for a result already known, so go straight to the
        # backbone instead of parking the user on a spinner.
        LAST_ERROR = (f"{_ENGINE} unreachable from this host (established "
                      f"earlier); backbone blueprints are carrying the "
                      f"population")
        return None
    key, key_var = _api_key_source()
    if not key:
        LAST_ERROR = (f"{_ENGINE} credentials not configured "
                      "(set LAYOUT_API_KEY in .env or the Space secrets)")
        print(f"[layout_engine] {LAST_ERROR}")
        return None
    # Log neither the key nor which variable supplied it β€” only that one was
    # found and its shape, so a truncated secret is still diagnosable.
    print(f"[layout_engine] credentials found (len={len(key)})")
    try:
        from openai import OpenAI                       # SDK, isolated here
    except Exception as exc:
        LAST_ERROR = f"{_ENGINE} client unavailable: {type(exc).__name__}"
        print(f"[layout_engine] {LAST_ERROR}")
        return None
    rooms_all = list(dict.fromkeys(list(required) + list(optional)))
    user = json.dumps({
        "buildable_rectangle_ft": {"width": round(build_w, 1),
                                   "height": round(build_h, 1)},
        "rooms_required": rooms_all,
        "room_size_guide": _room_guide(rooms_all),
        "n_layouts": n,
    })
    model = MODEL
    # A layout call takes 30-60 s, so the per-call floor stays at 90 s. The
    # BUDGET is the new part: two attempts at a 180 s timeout could block for
    # six minutes before the backbone took over, which on the hosted app looked
    # like the page had died. The whole function now works to one wall-clock
    # deadline and simply skips the retry when the budget is gone.
    timeout = max(float(os.getenv("LAYOUT_TIMEOUT", "120")), 90.0)
    budget = max(float(os.getenv("LAYOUT_BUDGET", "150")), timeout)
    started = time.monotonic()
    allowed = set(rooms_all) | {"internal_corridor"}
    specs = []
    for attempt in (1, 2):     # retry transient errors AND unusable answers
        left = budget - (time.monotonic() - started)
        if attempt == 2 and left < 20:
            print(f"[layout_engine] retry skipped, {left:.0f}s of the "
                  f"{budget:.0f}s budget left")
            break
        try:
            client = OpenAI(api_key=key, timeout=min(timeout, max(left, 15)))
            data = _chat_json(client, model, user)
        except Exception as exc:
            LAST_ERROR = (f"{_ENGINE} call failed "
                          f"(try {attempt}): {_explain(exc)}")
            print(f"[layout_engine] {LAST_ERROR}")
            if attempt == 2:            # both tries died: say WHY, once
                diag, dead = _probe_network()
                LAST_ERROR += f" | diagnosis: {diag}"
                print(f"[layout_engine] diagnosis: {diag}")
                if dead:
                    _NET_DEAD = True
                    print("[layout_engine] no outbound route β€” the "
                          f"{_ENGINE} will be skipped for the rest of this "
                          "session; backbone blueprints carry the population")
            continue
        specs = _parse_specs(data, allowed)
        if "pooja_room" in allowed and specs:
            # the pooja needs a narrow (<=7 ft) column for a sane niche β€”
            # prefer the layouts that actually built one
            narrow = [s for s in specs if min(c[0] for c in s) <= 7.0]
            if len(narrow) >= max(3, n // 4):
                specs = narrow
        if len(specs) >= max(3, n // 4):
            break
        LAST_ERROR = (f"{_ENGINE} returned only {len(specs)} usable layouts "
                      f"(try {attempt})")
        print(f"[layout_engine] {LAST_ERROR}")
    if not specs:
        return None                        # LAST_ERROR already explains why
    LAST_ERROR = None                                   # success β€” clear it
    return specs


def _parse_specs(data, allowed):
    """JSON answer -> [[col_width, [[room, depth], ...]], ...] specs (lenient:
    bad columns/rooms are skipped, a layout needs >= 2 usable columns)."""
    raw = data.get("layouts") if isinstance(data, dict) else None
    if not isinstance(raw, list):
        raw = [data] if isinstance(data, dict) and "columns" in data else []
    specs = []
    for lay in raw:
        cols = lay.get("columns") if isinstance(lay, dict) else None
        if not isinstance(cols, list) or not (2 <= len(cols) <= 5):
            continue
        spec = []
        for col in cols:
            try:
                cw = float(col.get("width", 0))
            except Exception:
                cw = 0.0
            rooms = []
            for rm in (col.get("rooms") or []):
                nm = rm.get("name") if isinstance(rm, dict) else None
                if nm not in allowed:
                    continue
                try:
                    d = max(float(rm.get("depth", 0)), 1.0)
                except Exception:
                    d = 6.0
                rooms.append([nm, d])
            if cw > 0 and rooms:
                spec.append([cw, rooms])
        if len(spec) >= 2:
            specs.append(spec)
    return specs


# ── Deterministic rendering (tiling-safe by construction) ─────────────────────

def _insert_missing(spec, needed):
    """Every requested room must exist: drop stray duplicates, then insert any
    missing room into the column with the most spare depth (guide-mid depth)."""
    seen = set()
    for cw, rooms in spec:
        keep = []
        for nm, d in rooms:
            if nm != "internal_corridor" and nm in seen:
                continue                                # duplicate β€” drop
            seen.add(nm)
            keep.append([nm, d])
        rooms[:] = keep
    for nm in needed:
        if nm in seen:
            continue
        (_, _), (dlo, dhi) = ROOM_SIZE_RANGES.get(nm, ((6, 10), (6, 10)))
        depth = (dlo + dhi) / 2.0
        # widest non-staircase column (its rooms compress the least)
        cands = [c for c in spec
                 if not any(r[0] == "external_staircase" for r in c[1])] or spec
        col = max(cands, key=lambda c: c[0])
        col[1].append([nm, depth])
        seen.add(nm)
    # a column emptied by de-duping would break the tiling β€” give it a filler
    for cw, rooms in spec:
        if not rooms:
            rooms.append(["balcony", 8.0])
    return spec


def _fix_staircase(spec, build_w):
    """Stair column width -> 10 or 12 exactly (delta shared by other columns).
    The stair keeps the position the proposer chose (front, rear, or a side
    column) β€” it is only snapped to the nearer END of its column when it would
    be landlocked in the interior (not touching any outer wall)."""
    ci = next((i for i, (_, rooms) in enumerate(spec)
               if any(nm == "external_staircase" for nm, _ in rooms)), None)
    if ci is None:
        return spec
    if len(spec[ci][1]) == 1:
        # a stair-only column would stretch the stair to the full building
        # depth β€” never allow it
        if len(spec) > 2:
            # merge the stair into the nearest column (at its road end) and
            # drop the empty column (_spec_to_boxes renormalises widths)
            stair = spec[ci][1][0]
            spec.pop(ci)
            ci = min(ci, len(spec) - 1)
            spec[ci][1].insert(0, stair)
        else:
            # only 2 columns: pull the deepest habitable room over instead
            other = spec[1 - ci][1]
            donor = max((r for r in other if r[0] in HABITABLE),
                        key=lambda r: r[1], default=None)
            if donor is None and len(other) > 1:
                donor = max(other, key=lambda r: r[1])   # any room at all
            if donor is not None and len(other) > 1:
                other.remove(donor)
                spec[ci][1].append(donor)
    cw, rooms = spec[ci]
    target_w = STAIR_SHORT if abs(cw - STAIR_SHORT) <= abs(cw - STAIR_LONG) \
        else STAIR_LONG
    target_d = STAIR_LONG if target_w == STAIR_SHORT else STAIR_SHORT
    delta = cw - target_w
    others = [c for i, c in enumerate(spec) if i != ci]
    tot = sum(c[0] for c in others) or 1.0
    for c in others:
        c[0] = max(4.0, c[0] + delta * (c[0] / tot))
    spec[ci][0] = target_w
    si = next(i for i, r in enumerate(rooms) if r[0] == "external_staircase")
    edge_col = ci in (0, len(spec) - 1)                 # touches a side wall
    if not edge_col and si not in (0, len(rooms) - 1):
        stair = rooms.pop(si)                           # landlocked: snap to
        if si <= len(rooms) / 2:                        # the nearer end
            rooms.insert(0, stair)
            si = 0
        else:
            rooms.append(stair)
            si = len(rooms) - 1
    rooms[si][1] = target_d
    return spec


HABITABLE = ("living_room", "kitchen", "dining_room", "study") + BEDROOMS


def _floor_depth(nm):
    if nm == "pooja_room":
        return 2.5
    return 6.5 if nm in HABITABLE else 3.5


def _merge_excess_columns(spec, ih):
    """A 50 ft tall column needs ~5 rooms to fill sanely, so a 14-room plan
    supports at most ~3 columns β€” merge the thinnest columns when a spec has
    too many, otherwise every column starves and stretches its rooms."""
    min_rooms = max(2, int(round(ih / 9.5)))
    total = sum(len(c[1]) for c in spec)
    max_cols = max(2, int(round(total / float(min_rooms))))
    def keep(c):
        # never merge away the stair (fixed 10/12 ft) or the pooja's narrow
        # service column (merging would re-stretch the niche)
        return any(nm in ("external_staircase", "pooja_room")
                   for nm, _ in c[1])
    while len(spec) > max_cols:
        cands = [i for i, c in enumerate(spec) if not keep(c)]
        if len(cands) < 1:
            break
        i = min(cands, key=lambda i: spec[i][0])       # thinnest mergeable
        nbrs = [j for j in (i - 1, i + 1)
                if 0 <= j < len(spec) and not keep(spec[j])
                and spec[j][0] + spec[i][0] <= 15.0]   # never a 16 ft column
        if not nbrs:
            break
        j = min(nbrs, key=lambda j: spec[j][0])
        spec[j][0] += spec[i][0]
        spec[j][1].extend(spec[i][1])
        spec.pop(i)
    return spec


def _rebalance_columns(spec, ih):
    """Balance the columns by MINIMUM depth load so one column never renders
    pancake rooms while another has slack (a 3BHK on a 30x40 plot used to
    stack 9 rooms in one column and 4 in the other). Only the staircase is
    immovable. Pure spec move β€” the tiling stays exact."""
    def load(col):
        return sum(d if nm == "external_staircase" else _floor_depth(nm)
                   for nm, d in col[1])
    for _ in range(16):
        worst = max(spec, key=load)
        if load(worst) <= ih + 0.1:
            break
        movable = [r for r in worst[1] if r[0] != "external_staircase"]
        if len(movable) <= 1:
            break
        moved = False
        for room in sorted(movable, key=lambda r: _floor_depth(r[0])):
            target = min((c for c in spec if c is not worst), key=load,
                         default=None)
            if target is not None and \
                    load(target) + _floor_depth(room[0]) < load(worst):
                worst[1].remove(room)
                target[1].append(room)
                moved = True
                break
        if not moved:
            break
    # Phase B: no STARVING columns. A column with too few rooms for the
    # building height stretches whatever it holds into mega strips (a lone
    # washroom becomes 10x34 = 344 sqft on a 40x60 plot). Every column needs
    # roughly height/13 rooms so the depth ceilings have absorbers to work
    # with; the deepest movable room migrates from the fullest column.
    min_rooms = max(2, int(round(ih / 9.5)))
    for _ in range(16):
        starving = min(spec, key=lambda c: len(c[1]))
        if len(starving[1]) >= min_rooms:
            break
        # donor: any column at least TWO rooms fuller β€” equalise even when
        # no column reaches min_rooms (e.g. 12 rooms over 4 columns)
        donor = max((c for c in spec if c is not starving
                     and len(c[1]) >= len(starving[1]) + 2),
                    key=lambda c: len(c[1]), default=None)
        if donor is None:
            break
        movable = [r for r in donor[1]
                   if r[0] not in ("external_staircase", "pooja_room")]
        if not movable:
            break
        room = max(movable, key=lambda r: _floor_depth(r[0]))
        donor[1].remove(room)
        starving[1].append(room)
    return spec


def _normalize_widths(spec, iw):
    s = iw / (sum(c[0] for c in spec) or 1.0)
    for c in spec:
        c[0] *= s
    return spec


def _strip_corridors(spec):
    """Drop proposer-supplied internal_corridors. In a fully-tiled flat the
    corridor easily balloons into a depth sink (a 337 sqft 'passage'); we add
    at most ONE thin buffer later, only where a pooja/service genuinely needs
    separating. Empty columns are removed."""
    for c in spec:
        c[1] = [r for r in c[1] if r[0] != "internal_corridor"]
    spec[:] = [c for c in spec if c[1]]
    return spec


def _col_area(c):
    return sum(_ideal_area(nm) for nm, _ in c[1])


_THIN_SVC = ("common_bathroom", "attached_bathroom", "attached_bathroom_02",
             "utility_area")
# An ATTACHED bath must keep the wall it shares with its own bedroom, so it is
# never dragged into the service cluster. Only the shared bath and the utility
# are groupable.
_GROUPABLE_SVC = ("common_bathroom", "utility_area")


def _group_services(spec):
    """Within each column, pull the groupable services (shared bath + utility)
    next to each other so the box-level pairing can fuse two full-width strips
    into a side-by-side pair (a 11x3.8 bath + 11x3.5 utility -> two ~5.5x7
    rooms). Pure reorder β€” the column still tiles exactly."""
    for cw, rooms in spec:
        svc = [r for r in rooms if r[0] in _GROUPABLE_SVC]
        if len(svc) < 2:
            continue
        # anchor the group just after the first service's original slot
        first = min(rooms.index(r) for r in svc)
        others = [r for r in rooms if r not in svc]
        rooms[:] = others[:first] + svc + others[first:]
    return spec


def _set_column_count(spec, iw, ih):
    """Reduce to a column count the WIDTH can support (~11 ft per column) so
    no habitable room is squeezed into a 5 ft strip. Adjacent non-stair
    columns with the smallest combined area merge first; the stair column is
    left intact so it keeps its wall slot."""
    K = max(2, min(4, int(round(iw / 11.0))))

    def has_stair(c):
        return any(nm == "external_staircase" for nm, _ in c[1])
    while len(spec) > K:
        best = None
        for i in range(len(spec) - 1):
            a, b = spec[i], spec[i + 1]
            if has_stair(a) or has_stair(b):
                continue
            ca = _col_area(a) + _col_area(b)
            if best is None or ca < best[0]:
                best = (ca, i)
        if best is None:
            break
        i = best[1]
        spec[i][1].extend(spec[i + 1][1])
        spec.pop(i + 1)
    return spec


def _col_load(c):
    """Effective room-slot load of a column. Each room fills ~one horizontal
    band; the staircase eats ~2 bands (120 sqft ~= 12 ft of the ~50 ft
    height), so it counts double. This is what governs per-room DEPTH β€” a
    column of 4 slots gives each room ~1/4 of the height (square-ish),
    whereas a 2-room column forces two 25 ft deep strips."""
    load = 0.0
    for nm, _ in c[1]:
        if nm == "external_staircase":
            load += 2.0
        elif nm in ("pooja_room", "internal_corridor"):
            load += 0.5                                 # niche/buffer, half band
        else:
            load += 1.0
    return load


# An attached bath belongs to exactly one bedroom and must never be separated
# from it β€” they move between columns together, as one unit.
ATTACHED_OF = {"master_bedroom": "attached_bathroom",
               "bedroom_01": "attached_bathroom_02"}
_ATTACHED_BATHS = tuple(ATTACHED_OF.values())


def _balance_columns(spec, ih):
    """Even out the ROOM-SLOT load across columns so every column ends up with
    ~4 bands (each room ~1/4 of the height = square-ish). Balancing by COUNT
    (not area) is what stops one big room stretching to 25 ft deep in a thin
    column. Hard invariant: NO column is left with a load below ~3 while
    another sits above ~4 β€” that pairing is exactly what produces a strip.
    The stair/pooja stay pinned, an attached bath travels with its bedroom;
    one room moves at a time, preserving adjacency as much as possible."""
    PIN = ("external_staircase", "pooja_room") + _ATTACHED_BATHS
    if len(spec) < 2:
        return spec
    # target load per column so every room gets ~1/target of the height
    target = max(3.0, sum(_col_load(c) for c in spec) / len(spec))
    for _ in range(60):
        hi = max(spec, key=_col_load)
        lo = min(spec, key=_col_load)
        # stop only when the spread is small AND the emptiest column is not
        # starved (load >= target-1 means its rooms won't stretch)
        if hi is lo or (_col_load(hi) - _col_load(lo) <= 1.0
                        and _col_load(lo) >= target - 1.0):
            break
        movable = [r for r in hi[1] if r[0] not in PIN]
        if len(hi[1]) <= 1 or not movable:
            break
        # move the SMALLEST room off the fullest column into the emptiest one
        # (keeps big rooms where they are; fills the thin column with a
        # service/medium so its big room no longer has to fill alone)
        room = min(movable, key=lambda r: _ideal_area(r[0]))
        _move_room(hi, lo, room)
    return spec


def _move_room(src, dst, room):
    """Move a room between columns, dragging its attached bath along so the
    bedroom/bath pair is never split across columns."""
    src[1].remove(room)
    dst[1].append(room)
    bath_nm = ATTACHED_OF.get(room[0])
    if bath_nm:
        bath = next((r for r in src[1] if r[0] == bath_nm), None)
        if bath is not None:
            src[1].remove(bath)
            dst[1].append(bath)              # lands right after its bedroom


_MEDIUM = ("living_room", "kitchen", "dining_room", "study",
           "bedroom_01", "bedroom_02", "bedroom_03", "master_bedroom")


def _fix_stair_column_mix(spec):
    """The staircase eats ~12 ft of its column's depth, so if the only other
    big room there is a single bedroom/living it stretches to fill the rest
    (a 10x30 living strip). Guarantee the stair column holds at least TWO
    medium rooms β€” they then share the depth at a sane 15-19 ft each. Pull a
    medium in from the column that has the most; push a shallow balcony out."""
    def has_stair(c):
        return any(nm == "external_staircase" for nm, _ in c[1])
    sc = next((c for c in spec if has_stair(c)), None)
    if sc is None or len(spec) < 2:
        return spec

    def n_medium(c):
        return sum(1 for nm, _ in c[1] if nm in _MEDIUM)
    for _ in range(3):
        if n_medium(sc) >= 2:
            break
        donor = max((c for c in spec if c is not sc and n_medium(c) >= 2),
                    key=n_medium, default=None)
        if donor is None:
            break
        # move the smallest medium so the donor keeps its biggest rooms
        # (its attached bath, if any, comes along)
        room = min((r for r in donor[1] if r[0] in _MEDIUM),
                   key=lambda r: _ideal_area(r[0]))
        _move_room(donor, sc, room)
    return spec


def _fill_stair_column(spec, ih):
    """The staircase column has a FIXED width (10/12 ft) but the 120 sqft
    stair eats ~12 ft of its depth, so if it holds only 1-2 other rooms they
    stretch to fill the rest (a 10x34 master strip). Move rooms in/out until
    the column's total ideal area ~= width x height, so its rooms fill
    naturally at their proper size."""
    def has_stair(c):
        return any(nm == "external_staircase" for nm, _ in c[1])
    sc = next((c for c in spec if has_stair(c)), None)
    if sc is None or len(spec) < 2:
        return spec

    def area(c):
        return sum(_ideal_area(nm) for nm, _ in c[1])
    # rooms that never move on their own: the stair, the pooja niche, and an
    # attached bath (it travels with its bedroom through _move_room)
    PINNED = ("external_staircase", "pooja_room") + _ATTACHED_BATHS
    target = sc[0] * ih
    for _ in range(6):
        gap = target - area(sc)
        others = [c for c in spec if c is not sc and len(c[1]) > 1]
        if gap > 60 and others:                        # under-filled: pull one
            donor = max(others, key=area)
            movable = [r for r in donor[1] if r[0] not in PINNED]
            if not movable:
                break
            # the room that best closes the gap without overshooting
            room = min(movable, key=lambda r: abs(gap - _ideal_area(r[0])))
            _move_room(donor, sc, room)
        elif gap < -60 and len(sc[1]) > 2:             # over-filled: push one
            movable = [r for r in sc[1] if r[0] not in PINNED]
            if not movable:
                break
            room = min(movable, key=lambda r: _ideal_area(r[0]))
            target_col = min((c for c in spec if c is not sc), key=area)
            _move_room(sc, target_col, room)
        else:
            break
    return spec


def _assign_column_widths(spec, iw, ih):
    """Set each column's width from the IDEAL AREA of the rooms it holds:
    width = column_area / ih, so a column of big rooms (living+master) comes
    out wide and a pure service column comes out narrow β€” every room lands
    near square. The staircase column keeps its exact 10/12 ft; the rest are
    scaled to fill the remaining width with sane floors."""
    def has_stair(c):
        return any(nm == "external_staircase" for nm, _ in c[1])

    def col_area(c):
        return sum(_ideal_area(nm) for nm, _ in c[1]
                   if nm != "external_staircase")

    stair_w = sum(c[0] for c in spec if has_stair(c)) or 0.0
    others = [c for c in spec if not has_stair(c)]
    avail = max(iw - stair_w, 4.0)
    raw = {id(c): max(col_area(c) / ih, 1.0) for c in others}
    rsum = sum(raw.values()) or 1.0
    for c in others:
        c[0] = avail * raw[id(c)] / rsum
    # floors from the finalised width bounds: a column must be at least as
    # wide as the largest MIN short-side of the rooms it holds (living 9,
    # master 10, bedrooms 8, kitchen 7...); a pure service column >= 4.5 ft.
    # Pull the deficit from the widest column that can spare it.
    def floor_for(c):
        mins = [MIN_SHORT_SIDE[nm] for nm, _ in c[1] if nm in MIN_SHORT_SIDE]
        if mins:
            return max(mins)
        if any(nm in HABITABLE for nm, _ in c[1]):
            return 7.5
        return 4.5
    for _ in range(4):
        deficit = [c for c in others if c[0] < floor_for(c) - 0.05]
        if not deficit:
            break
        c = min(deficit, key=lambda c: c[0])
        need = floor_for(c) - c[0]
        donor = max((d for d in others if d is not c
                     and d[0] - need >= floor_for(d)),
                    key=lambda d: d[0], default=None)
        if donor is None:
            break
        donor[0] -= need
        c[0] += need
    return spec


# Ideal FLOOR AREA per room (sqft). The depth a room receives in its column
# is proportional to this β€” the spec decides topology (which rooms sit in
# which column and their order) while these targets decide the SIZES. This is
# what keeps a master ~= a bedroom instead of one becoming a 400 sqft strip.
# Proportions straight from the client's finalised sheet (living = 152.2 as
# the 1.0 reference: master 1.1x, parents' room 0.75x, kids' 0.667x, guest and
# dining 0.5x, kitchen 0.4x, study 0.333x ...). The SAME table drives the
# Room Size Accuracy metric (core/size_model.py), so the geometry builds what
# the scoring expects.
IDEAL_AREA = {
    "living_room": 152.2, "master_bedroom": 167.4,
    "bedroom_01": 114.2, "bedroom_02": 101.5, "bedroom_03": 76.1,
    "kitchen": 60.9, "dining_room": 76.1, "study": 50.7,
    "utility_area": 20.2, "common_bathroom": 19.0, "attached_bathroom": 25.4,
    "attached_bathroom_02": 25.4,
    "pooja_room": 15.2, "balcony": 40.0, "internal_corridor": 10.0,
}

# The finalised width-bounds (a room's SHORT side, ft) from the same sheet.
# MIN drives the column-width floors, MAX caps a room's depth when its
# column is wider than the bound.
MIN_SHORT_SIDE = {
    "living_room": 9.0, "master_bedroom": 10.0,
    "bedroom_01": 8.0, "bedroom_02": 8.0, "bedroom_03": 8.0,
    "kitchen": 7.0, "dining_room": 5.0,
}
MAX_SHORT_SIDE = {
    "living_room": 12.0, "master_bedroom": 16.0,
    "bedroom_01": 12.0, "bedroom_02": 12.0, "bedroom_03": 12.0,
    "kitchen": 10.0, "dining_room": 8.0,
    "common_bathroom": 7.0, "attached_bathroom": 7.0,
    "attached_bathroom_02": 7.0, "utility_area": 6.0, "pooja_room": 5.0,
}


def _ideal_area(nm):
    return IDEAL_AREA.get(nm, 120.0)


def _spec_to_boxes(spec, ix0, iy0, iw, ih):
    """Exact tiling: widths scaled to sum=iw; within each column the flexible
    rooms receive depth in proportion to their IDEAL AREA (not the spec's raw
    depths), so same-class rooms come out similar sizes and nothing balloons
    into a strip. Floors/ceilings then clamp any residual extreme."""
    # the staircase column keeps its EXACT width (10 or 12); only the other
    # columns are scaled to absorb any width error.
    def has_stair(c):
        return any(nm == "external_staircase" for nm, _ in c[1])
    stair_w = sum(c[0] for c in spec if has_stair(c))
    other_w = sum(c[0] for c in spec if not has_stair(c)) or 1.0
    oscale = max(iw - stair_w, 4.0) / other_w
    boxes = []
    x = ix0
    FIXED_DEPTH = ("external_staircase", "pooja_room")   # never re-scaled
    for k, (cw, rooms) in enumerate(spec):
        w = cw if has_stair(spec[k]) else cw * oscale
        if k == len(spec) - 1:
            w = ix0 + iw - x
        fixed = sum(d for nm, d in rooms if nm in FIXED_DEPTH)
        avail = max(ih - fixed, 4.0)
        # depth proportional to ideal area (target_depth = ideal_area / width),
        # normalised so the flex rooms exactly fill the remaining column depth
        want = {m: _ideal_area(nm) / max(w, 1.0)
                for m, (nm, _) in enumerate(rooms) if nm not in FIXED_DEPTH}
        wsum = sum(want.values()) or 1.0
        hs = [d if nm in FIXED_DEPTH else avail * want[m] / wsum
              for m, (nm, d) in enumerate(rooms)]
        # depth floors: enough depth that the room reaches its CODE MINIMUM
        # area at this column width (never below the old 6.5/3.5 comfort
        # floors, never an absurd demand in a very narrow column)
        def depth_floor(nm):
            base = 6.5 if nm in HABITABLE else 3.5
            need = ROOM_MIN_AREA.get(nm, 25) / max(w, 1.0)
            return min(max(base, need), 14.0)
        for _ in range(3):
            for m, (nm, _) in enumerate(rooms):
                if nm in FIXED_DEPTH:
                    continue
                floor = depth_floor(nm)
                if hs[m] >= floor:
                    continue
                need = floor - hs[m]
                for q in sorted(range(len(rooms)), key=lambda q: -hs[q]):
                    if q == m or rooms[q][0] in FIXED_DEPTH:
                        continue
                    qfloor = depth_floor(rooms[q][0])
                    give = min(need, hs[q] - qfloor)
                    if give > 0:
                        hs[q] -= give
                        hs[m] += give
                        need -= give
                    if need <= 0.01:
                        break
        # column overfull even at the minimum floors (tiny plot, many rooms):
        # share the shortfall in PROPORTION to each room's floor so the pain
        # is even β€” never one 3 ft pancake bedroom beside a 8 ft one
        flo = {m: depth_floor(rooms[m][0])
               for m in range(len(rooms)) if rooms[m][0] not in FIXED_DEPTH}
        if flo:
            need_min = sum(flo.values())
            avail = ih - sum(hs[m] for m in range(len(rooms))
                             if rooms[m][0] in FIXED_DEPTH)
            if need_min > avail + 0.05:
                k = max(avail, 4.0) / need_min
                for m, f in flo.items():
                    hs[m] = f * k
        # depth CEILINGS: a room must not become a long strip β€” cap depth at
        # ~2.2x the column width and hand the excess to under-cap neighbours
        # (balcony / corridor may stay long; stair & pooja are fixed).
        # ALSO: the client's width-bounds table caps a room's SHORT side (e.g.
        # dining <= 8 ft, bedroom <= 12 ft). In a column wider than that
        # bound, the depth becomes the short side β€” so cap the depth at the
        # bound to keep the room inside its finalised proportions.
        def cap_for(nm):
            if nm == "balcony":
                return min(2.2 * w, 8.0)      # a balcony is shallow
            if nm == "internal_corridor":
                return min(2.2 * w, 6.0)      # a passage is thin, never a sink
            cap = 2.2 * w if nm in HABITABLE else min(2.2 * w, 9.0)
            hi = MAX_SHORT_SIDE.get(nm)
            if hi is not None and w > hi:
                cap = min(cap, hi)
            return cap
        for _ in range(4):
            over = [m for m, (nm, _) in enumerate(rooms)
                    if nm not in FIXED_DEPTH and hs[m] > cap_for(nm) + 0.05]
            for m in over:
                nm = rooms[m][0]
                excess = hs[m] - cap_for(nm)
                # hand excess to the room furthest BELOW its cap (spreads the
                # depth so nothing else balloons into a strip sink)
                for q in sorted(range(len(rooms)),
                                key=lambda q: hs[q] - cap_for(rooms[q][0])):
                    if q == m or rooms[q][0] in FIXED_DEPTH:
                        continue
                    take = min(excess, cap_for(rooms[q][0]) - hs[q])
                    if take > 0:
                        hs[q] += take
                        hs[m] -= take
                        excess -= take
                    if excess <= 0.01:
                        break
        # exact column fill: spread any residual drift across the flex rooms
        # in proportion to their cap headroom, so nothing balloons into a
        # strip. If every room is already at its cap, the widest habitable
        # room takes the rest (a slightly big living beats a random strip).
        flex_idx = [m for m, (nm, _) in enumerate(rooms) if nm not in FIXED_DEPTH]
        for _ in range(4):
            drift = ih - sum(hs)
            if abs(drift) < 0.05 or not flex_idx:
                break
            head = {m: max(cap_for(rooms[m][0]) - hs[m], 0.0) for m in flex_idx}
            hsum = sum(head.values())
            if drift > 0 and hsum > 0.05:
                for m in flex_idx:
                    hs[m] += drift * head[m] / hsum
            else:
                # over cap (or no headroom): scale flex rooms to fit exactly
                cur = sum(hs[m] for m in flex_idx) or 1.0
                tgt = ih - sum(hs[m] for m, (nm, _) in enumerate(rooms)
                               if nm in FIXED_DEPTH)
                for m in flex_idx:
                    hs[m] *= max(tgt, 1.0) / cur
                break
        y = iy0
        for m, (nm, d) in enumerate(rooms):
            h = hs[m]
            if m == len(rooms) - 1:
                h = iy0 + ih - y
            boxes.append({"name": nm, "x": round(x, 2), "y": round(y, 2),
                          "w": round(w, 2), "h": round(max(h, 1.0), 2)})
            y += h
        x += w
    return boxes


def _pair_thin_rooms(boxes, iw, ih, iy0):
    """Real plans put two small rooms SIDE BY SIDE, not as stacked full-width
    strips. Two thin same-class rooms stacked in one column are re-cut into a
    side-by-side pair sharing their combined depth: a 10x2.7 bathroom over a
    10x2.7 utility becomes two ~5x5.4 rooms. The pair's combined footprint is
    unchanged, so the tiling stays exact. Services pair only with services
    (a kitchen must never end up beside a bathroom)."""
    SERVICE = ("common_bathroom", "attached_bathroom", "attached_bathroom_02",
               "utility_area", "balcony")
    HAB = ("kitchen", "dining_room", "study",
           "bedroom_01", "bedroom_02", "bedroom_03")
    # a service may also pair with a bedroom/study (an attached bath BESIDE
    # the bedroom is the classic plan) β€” but never with kitchen/dining
    BESIDE_OK = ("bedroom_01", "bedroom_02", "bedroom_03",
                 "master_bedroom", "study")

    def group(nm):
        return "s" if nm in SERVICE else ("h" if nm in HAB else None)

    def compat(na, nb):
        ga, gb = group(na), group(nb)
        if ga == gb and ga is not None:
            return True
        if ga == "s" and nb in BESIDE_OK:
            return True
        if gb == "s" and na in BESIDE_OK:
            return True
        return False

    done = set()
    for a in boxes:
        ga = group(a["name"])
        if ga is None or id(a) in done:
            continue
        lim = 4.8 if ga == "s" else 5.6
        wmin = 8.0 if ga == "s" else 12.0
        if a["h"] > lim or a["w"] < wmin:
            continue
        for b in boxes:
            if b is a or id(b) in done \
                    or not compat(a["name"], b["name"]) \
                    or b["h"] > (4.8 if group(b["name"]) == "s" else 5.6):
                continue
            if not (abs(a["x"] - b["x"]) < 0.3
                    and abs(a["w"] - b["w"]) < 0.3):
                continue                               # must share the column
            stacked = abs(a["y"] + a["h"] - b["y"]) < 0.3 \
                or abs(b["y"] + b["h"] - a["y"]) < 0.3
            pen0 = _violations(boxes, iw, ih, iy0)
            if stacked:
                # directly stacked: the cut is local β€” no repack needed, so
                # it works even in a column that already holds another pair
                col = [a, b]
                snap = {id(c): (c["x"], c["y"], c["w"], c["h"]) for c in col}
            else:
                # b must slide through the column to sit right after a β€”
                # only safe in a fully contiguous, stair-free column
                col = sorted([c for c in boxes
                              if abs(c["x"] - a["x"]) < 0.3
                              and abs(c["w"] - a["w"]) < 0.3],
                             key=lambda c: c["y"])
                cy0 = min(c["y"] for c in col)
                span = max(c["y"] + c["h"] for c in col) - cy0
                if abs(span - sum(c["h"] for c in col)) > 0.3:
                    continue                # column already holds a pair
                if any(c["name"] == "external_staircase" for c in col):
                    continue         # never slide rooms past the fixed stair
                snap = {id(c): (c["x"], c["y"], c["w"], c["h"]) for c in col}
                order = [c for c in col if c is not b]
                order.insert(order.index(a) + 1, b)
                y = cy0
                for c in order:
                    c["y"] = y
                    y += c["h"]
            # side-by-side cut over the two cells' combined footprint, width
            # split by IDEAL AREA so two same-class services come out ~50/50
            # (splitting by depth let a bath grab 68% and balloon to 84 sqft)
            y0p = min(a["y"], b["y"])
            dd = a["h"] + b["h"]
            w, x0 = a["w"], a["x"]
            ia, ib = _ideal_area(a["name"]), _ideal_area(b["name"])
            wa = max(3.5, min(w - 3.5, w * ia / (ia + ib)))
            a.update(x=x0, y=y0p, w=wa, h=dd)
            b.update(x=x0 + wa, y=y0p, w=w - wa, h=dd)
            # revert only on HARD damage (pooja-wet +10 / kitchen-bath +6);
            # a +-2.5 edge-score wobble must not undo de-stripping
            if _violations(boxes, iw, ih, iy0) > pen0 + 3.5:
                for c in col:
                    c["x"], c["y"], c["w"], c["h"] = snap[id(c)]
                continue
            done.add(id(a))
            done.add(id(b))
            break
    return boxes


def _split_wide_service(boxes):
    """LAST RESORT for a lone full-width service row in a wide column (a
    14 x 4 bathroom with no thin partner to pair with): cut the cell into
    [service | passage] side by side. Only fires when the plan has no
    internal_corridor yet, so there is never more than one passage."""
    if any(b["name"] == "internal_corridor" for b in boxes):
        return boxes
    new = []
    for bx in boxes:
        if bx["name"] not in ("common_bathroom", "attached_bathroom",
                      "attached_bathroom_02", "utility_area"):
            continue
        if bx["w"] < 9.5 or bx["h"] < 3.2 \
                or bx["w"] <= 2.8 * bx["h"]:
            continue
        keep_w = min(7.0, max(5.0, 42.0 / bx["h"]))
        rest = bx["w"] - keep_w
        if rest < 3.0:
            continue
        new.append({"name": "internal_corridor", "x": bx["x"] + keep_w,
                    "y": bx["y"], "w": rest, "h": bx["h"]})
        bx["w"] = keep_w
        break                                   # at most one passage
    boxes.extend(new)
    return boxes


def _pair_pooja(boxes, iw, ih, iy0):
    """A pooja rendered as a full-width strip (12 x 2.5) is not a niche. Pair
    it side-by-side with a DRY flexible partner (study / internal_corridor)
    stacked in the same column: the pooja becomes ~4.5 ft wide with a sane
    aspect, the partner keeps the rest. Reverted when it worsens the plan."""
    pj = next((b for b in boxes if b["name"] == "pooja_room"), None)
    if pj is None or max(pj["w"], pj["h"]) <= 2.6 * min(pj["w"], pj["h"]):
        return boxes
    if pj["w"] < 8.0 or pj["h"] > 4.0:
        return boxes
    for b in boxes:
        if b["name"] not in ("study", "internal_corridor") or b["h"] > 6.5:
            continue
        if not (abs(b["x"] - pj["x"]) < 0.3 and abs(b["w"] - pj["w"]) < 0.3):
            continue
        stacked = abs(pj["y"] + pj["h"] - b["y"]) < 0.3 \
            or abs(b["y"] + b["h"] - pj["y"]) < 0.3
        if not stacked:
            continue
        snap = {id(c): (c["x"], c["y"], c["w"], c["h"]) for c in (pj, b)}
        pen0 = _violations(boxes, iw, ih, iy0)
        y0p = min(pj["y"], b["y"])
        dd = pj["h"] + b["h"]
        w, x0 = pj["w"], pj["x"]
        wa = max(4.0, min(w - 4.0, w * pj["h"] / dd))
        pj.update(x=x0, y=y0p, w=wa, h=dd)
        b.update(x=x0 + wa, y=y0p, w=w - wa, h=dd)
        if _violations(boxes, iw, ih, iy0) > pen0 + 3.5:
            for c in (pj, b):
                c["x"], c["y"], c["w"], c["h"] = snap[id(c)]
            continue
        break
    return boxes


def _shrink_to_area(boxes, bx, max_area):
    """Shrink an oversized box to ~max_area by trimming its depth (or width),
    handing the freed strip to a neighbour in the same column (or row) so the
    tiling stays exact. HABITABLE neighbours are preferred (bedrooms/living
    grow); the fixed staircase and the pooja never absorb."""
    if bx["w"] * bx["h"] <= max_area + 1:
        return
    NO_ABSORB = ("external_staircase", "pooja_room")

    def deficit(c):
        # how far BELOW its ideal area a room is (a strip group counts its
        # combined area) β€” the neediest habitable room absorbs first, so a
        # squished bedroom grows and an already-large master never balloons
        area = sum(b["w"] * b["h"] for b in (c if isinstance(c, list) else [c]))
        nm = (c[0] if isinstance(c, list) else c)["name"]
        return _ideal_area(nm) - area

    def pick(cands):
        cands = [c for c in cands if c]
        if not cands:
            return None
        # prefer habitable, then the one furthest below its ideal size
        cands.sort(key=lambda c: (
            0 if (c[0] if isinstance(c, list) else c)["name"] in HABITABLE
            else 1, -deficit(c)))
        return cands[0]

    new_h = max(3.5, max_area / max(bx["w"], 1.0))
    if bx["w"] / new_h > 3.0 and bx["w"] * bx["h"] <= max_area * 1.5:
        return          # trimming depth would create a strip β€” a slightly
                        # oversized room beats a 12x3 sliver
    freed = bx["h"] - new_h
    if freed > 0.1:
        def span_group(edge_y, from_above):
            """All absorb-ok boxes whose edge meets bx's edge and which
            together tile bx's full width (handles side-by-side pairs)."""
            if from_above:
                grp = [b for b in boxes if b is not bx
                       and b["name"] not in NO_ABSORB
                       and abs(b["y"] - edge_y) < 0.3
                       and b["x"] >= bx["x"] - 0.3
                       and b["x"] + b["w"] <= bx["x"] + bx["w"] + 0.3]
            else:
                grp = [b for b in boxes if b is not bx
                       and b["name"] not in NO_ABSORB
                       and abs(b["y"] + b["h"] - edge_y) < 0.3
                       and b["x"] >= bx["x"] - 0.3
                       and b["x"] + b["w"] <= bx["x"] + bx["w"] + 0.3]
            if grp and abs(sum(b["w"] for b in grp) - bx["w"]) < 0.5:
                return grp
            return None

        belows = span_group(bx["y"], from_above=False)
        aboves = span_group(bx["y"] + bx["h"], from_above=True)
        cands = [g for g in (belows, aboves) if g]
        if cands:
            # give the freed depth to the group with the NEEDIEST habitable
            # room (grows a squished bedroom, never the already-large master)
            grp = max(cands, key=lambda g: max(
                (deficit(b) for b in g if b["name"] in HABITABLE),
                default=-1e9))
            if grp is belows:
                bx["y"] += freed
                bx["h"] = new_h
                for b in grp:
                    b["h"] += freed
            else:
                bx["h"] = new_h
                for b in grp:
                    b["y"] -= freed
                    b["h"] += freed
            return
    new_w = max(3.5, max_area / max(bx["h"], 1.0))
    if bx["h"] / new_w > 3.0 and bx["w"] * bx["h"] <= max_area * 1.6:
        return
    freed_w = bx["w"] - new_w
    if freed_w <= 0.1:
        return
    same_row = [b for b in boxes if b is not bx
                and b["name"] not in NO_ABSORB
                and abs(b["y"] - bx["y"]) < 0.3
                and abs(b["h"] - bx["h"]) < 0.3]
    left = next((b for b in same_row
                 if abs(b["x"] + b["w"] - bx["x"]) < 0.3), None)
    right = next((b for b in same_row
                  if abs(bx["x"] + bx["w"] - b["x"]) < 0.3), None)
    tgt = pick([left, right])
    if tgt is not None:
        if tgt is left:
            bx["x"] += freed_w
            bx["w"] = new_w
            left["w"] += freed_w
        else:
            bx["w"] = new_w
            right["x"] -= freed_w
            right["w"] += freed_w


def _balance_service_pairs(boxes):
    """Two services sitting side by side (same row, shared depth) must split
    their width by ideal area, not lopsidedly β€” otherwise one bath grabs 68%
    and balloons to 84 sqft next to a sliver utility. Equalises the pair in
    place (their combined footprint is unchanged, so the tiling stays exact)."""
    SVC = ("common_bathroom", "attached_bathroom", "attached_bathroom_02",
           "utility_area")
    for a in boxes:
        if a["name"] not in SVC:
            continue
        for b in boxes:
            if b is a or b["name"] not in SVC:
                continue
            same_row = abs(a["y"] - b["y"]) < 0.3 and abs(a["h"] - b["h"]) < 0.3
            if not same_row:
                continue
            # a is the LEFT member of the adjacent pair
            if abs(a["x"] + a["w"] - b["x"]) > 0.3:
                continue
            total = a["w"] + b["w"]
            ia, ib = _ideal_area(a["name"]), _ideal_area(b["name"])
            wa = max(3.5, min(total - 3.5, total * ia / (ia + ib)))
            a["w"] = wa
            b["x"] = a["x"] + wa
            b["w"] = total - wa
    return boxes


def _cap_services(boxes):
    """Washrooms/utility have realistic MAXIMA β€” an XL washroom beside a
    compact bedroom is what makes a plan look broken. The freed strip grows a
    habitable neighbour, so bedrooms can only get bigger here."""
    CAPS = {"common_bathroom": 45.0, "attached_bathroom": 42.0,
            "attached_bathroom_02": 42.0, "utility_area": 38.0}
    for bx in boxes:
        cap = CAPS.get(bx["name"])
        if cap is not None:
            _shrink_to_area(boxes, bx, cap)
    _balance_service_pairs(boxes)
    return boxes


def _cap_public_hierarchy(boxes):
    """The living room is the biggest public room, ALWAYS: any kitchen or
    dining that out-sizes it is shrunk (freed strip grows a neighbour β€”
    often the living room itself). Runs after the label fixes so it works
    on the final living rectangle."""
    living = max((b for b in boxes if b["name"] == "living_room"),
                 key=lambda b: b["w"] * b["h"], default=None)
    if living is None:
        return boxes
    lv = living["w"] * living["h"]
    for nm in ("kitchen", "dining_room"):
        for bx in [b for b in boxes if b["name"] == nm]:
            if bx["w"] * bx["h"] > lv - 3:
                _shrink_to_area(boxes, bx, max(lv - 3, 40.0))
    return boxes


def _touching(a, b):
    """Strict contact test for the pooja-wet rule: ANY shared wall segment
    counts, even a sliver (the door-worthy _adjacent needs 1.5 ft)."""
    return _adjacent(a, b, tol=0.7, min_ov=0.3)


def _adjacent(a, b, tol=0.6, min_ov=1.5):
    ax0, ay0, ax1, ay1 = a["x"], a["y"], a["x"] + a["w"], a["y"] + a["h"]
    bx0, by0, bx1, by1 = b["x"], b["y"], b["x"] + b["w"], b["y"] + b["h"]
    if abs(ax1 - bx0) < tol or abs(bx1 - ax0) < tol:
        if min(ay1, by1) - max(ay0, by0) >= min_ov:
            return True
    if abs(ay1 - by0) < tol or abs(by1 - ay0) < tol:
        if min(ax1, bx1) - max(ax0, bx0) >= min_ov:
            return True
    return False


def _violations(boxes, iw, ih, iy0):
    """Soft score (lower = better) used to ORDER plans and pick permutations."""
    idx = {}
    for b in boxes:
        idx.setdefault(b["name"], []).append(b)
    pen = 0.0
    ex0, ex1 = SETBACK_OTHER, SETBACK_OTHER + iw

    def on_edge(b):
        return (b["x"] <= ex0 + 0.6 or b["x"] + b["w"] >= ex1 - 0.6
                or b["y"] <= iy0 + 0.6 or b["y"] + b["h"] >= iy0 + ih - 0.6)

    pooja = idx.get("pooja_room", [None])[0]
    if pooja is not None:
        if any(_touching(pooja, w) for nm in WET for w in idx.get(nm, [])):
            pen += 10.0
        cy = (pooja["y"] + pooja["h"] / 2 - iy0) / ih
        cx = (pooja["x"] + pooja["w"] / 2) / iw
        if cy < 0.6:
            pen += 2.0                                  # pooja should sit north
        if cx < 0.5:
            pen += 1.0                                  # ... and east
        # ISOLATED pooja (client complaint): it must open onto a public room,
        # a corridor or an outer wall β€” never be walled in by bedrooms only
        pub = ("living_room", "dining_room", "kitchen", "internal_corridor")
        if not on_edge(pooja) and not any(
                _adjacent(pooja, b) for nm in pub for b in idx.get(nm, [])):
            pen += 4.0
        # a pooja is a NICHE β€” an oversized one reads as a spare bedroom
        if pooja["w"] * pooja["h"] > POOJA_MAX_AREA + 4.0:
            pen += 3.5
    kit = idx.get("kitchen", [None])[0]
    if kit is not None:
        if any(_adjacent(kit, w)
               for nm in ("common_bathroom", "attached_bathroom",
                          "attached_bathroom_02")
               for w in idx.get(nm, [])):
            pen += 6.0
        if not on_edge(kit):
            pen += 2.5                                  # kitchen wants a wall
    stair = idx.get("external_staircase", [None])[0]
    living = max(idx.get("living_room", [None]) or [None],
                 key=lambda b: b["w"] * b["h"] if b else 0)
    if stair is not None and living is not None:
        # no foyer any more β€” the stair block IS the entry, living must touch it
        if not _adjacent(stair, living):
            pen += 8.0
    if stair is not None:
        # the stair may sit on ANY outer wall, but never landlocked inside
        x0, x1 = SETBACK_OTHER, SETBACK_OTHER + iw
        if not (stair["x"] <= x0 + 0.5 or stair["x"] + stair["w"] >= x1 - 0.5
                or stair["y"] <= iy0 + 0.5
                or stair["y"] + stair["h"] >= iy0 + ih - 0.5):
            pen += 10.0
    if living is not None and (living["y"] + living["h"] / 2 - iy0) / ih > 0.55:
        pen += 2.0                                      # living should sit front
    balc = idx.get("balcony", [None])[0]
    if balc is not None and abs(balc["y"] - iy0) > 0.5:
        pen += 3.0                                      # balcony wants road front
    master = idx.get("master_bedroom", [None])[0]
    if master is not None and any(
            b["w"] * b["h"] > master["w"] * master["h"] + 1
            for nm in ("bedroom_01", "bedroom_02", "bedroom_03")
            for b in idx.get(nm, [])):
        pen += 3.0
    # an ATTACHED bath is only attached if it shares a wall with its bedroom:
    # attached_bathroom -> master, attached_bathroom_02 -> bedroom_01
    for bed_nm, bath_nm in (("master_bedroom", "attached_bathroom"),
                            ("bedroom_01", "attached_bathroom_02")):
        bed = idx.get(bed_nm, [None])[0]
        bath = idx.get(bath_nm, [None])[0]
        if bed is not None and bath is not None and not _adjacent(bed, bath):
            pen += 4.0
    # SIZE HIERARCHY: a bedroom below the biggest washroom reads broken, and
    # the living room must stay the biggest public room
    bath_max = max((b["w"] * b["h"] for nm in
                    ("common_bathroom", "attached_bathroom",
                     "attached_bathroom_02")
                    for b in idx.get(nm, [])), default=0.0)
    for nm in BEDROOMS:
        for b in idx.get(nm, []):
            if b["w"] * b["h"] < bath_max - 1:
                pen += 4.0
    if bath_max > 60.0:
        pen += 4.0                          # an XL washroom is never right
    if living is not None:
        for nm in ("dining_room", "kitchen"):
            for b in idx.get(nm, []):
                if b["w"] * b["h"] > living["w"] * living["h"] + 1:
                    pen += 3.0
    # pooja is a NICHE β€” a stretched full-width strip is not a pooja
    if pooja is not None and \
            max(pooja["w"], pooja["h"]) > 2.6 * min(pooja["w"], pooja["h"]):
        pen += 2.5
    # bedrooms need windows, washrooms belong on edges β€” landlocked = bad
    ex0, ex1 = SETBACK_OTHER, SETBACK_OTHER + iw
    for b in boxes:
        if b["name"] in BEDROOMS or b["name"] in BATHROOMS:
            on_edge = (b["x"] <= ex0 + 0.5 or b["x"] + b["w"] >= ex1 - 0.5
                       or b["y"] <= iy0 + 0.5
                       or b["y"] + b["h"] >= iy0 + ih - 0.5)
            if not on_edge:
                pen += 3.0 if b["name"] in BEDROOMS else 2.5
    # These mirror the hard quality gates so a plan that would FAIL review
    # never out-ranks a clean (e.g. backbone) plan on the same plot.
    for b in boxes:
        if b["name"] in BEDROOMS + ("living_room", "kitchen", "dining_room"):
            if max(b["w"], b["h"]) > 2.5 * min(b["w"], b["h"]):
                pen += 4.0                              # strip room (gate)
        if b["name"] in ("master_bedroom", "bedroom_01", "bedroom_02",
                         "bedroom_03", "living_room"):
            if b["w"] * b["h"] < 78.0 or min(b["w"], b["h"]) < 7.0:
                pen += 4.0                              # cramped room (gate)
    return pen


def _improve_order(spec, ix0, iy0, iw, ih, rng):
    """Permute rooms WITHIN each column to lower the violation score. The
    staircase is free to move too β€” the landlocked penalty in _violations
    keeps it on an outer wall while letting it sit front, rear, or along a
    side column. Column permutation preserves the perfect tiling."""
    for _sweep in range(2):        # 2nd sweep: earlier columns adapt to later
        for ci in range(len(spec)):
            rooms = spec[ci][1]
            if not (2 <= len(rooms) <= 6):
                continue
            best, best_pen = None, None
            for perm in itertools.permutations(rooms):
                spec[ci][1] = list(perm)
                pen = _violations(_spec_to_boxes(spec, ix0, iy0, iw, ih),
                                  iw, ih, iy0)
                if best_pen is None or pen < best_pen - 1e-9:
                    best_pen, best = pen, list(perm)
            spec[ci][1] = best
    return spec


def _pooja_to_narrow_column(spec):
    """A pooja belongs in a narrow service column: if its column is wider than
    ~9 ft (a full-width pooja strip would exceed the niche size), MOVE it to the
    narrowest non-staircase column. Pure spec move β€” tiling stays exact."""
    pci = pr = None
    for ci, (cw, rooms) in enumerate(spec):
        for r in rooms:
            if r[0] == "pooja_room":
                pci, pr = ci, r
    if pr is None or spec[pci][0] <= 8.0 or len(spec[pci][1]) < 2:
        return spec

    def _narrow(ci):
        """Squeeze a pure-service column to 6.5 ft (excess width shared by
        the other non-stair columns β€” column-level, tiling stays exact)."""
        cw, rooms = spec[ci]
        if cw <= 8.0 or any(nm in HABITABLE or nm == "external_staircase"
                            for nm, _ in rooms):
            return False
        excess = cw - 6.5
        others = [c for i, c in enumerate(spec) if i != ci
                  and not any(nm == "external_staircase" for nm, _ in c[1])]
        tot = sum(c[0] for c in others) or 1.0
        for c in others:
            c[0] += excess * (c[0] / tot)
        spec[ci][0] = 6.5
        return True

    # best case: the pooja's OWN column is pure service β€” just narrow it
    if _narrow(pci):
        return spec
    # prefer a column with NO wet rooms and FEW habitable rooms; a narrower
    # column renders a squarer niche
    cands = [ci for ci, (cw, rooms) in enumerate(spec)
             if ci != pci and cw <= spec[pci][0]]
    if not cands:
        return spec
    tci = min(cands, key=lambda ci: (
        any(nm in WET for nm, _ in spec[ci][1]),
        any(nm == "external_staircase" for nm, _ in spec[ci][1]),
        sum(1 for nm, _ in spec[ci][1] if nm in HABITABLE),
        spec[ci][0]))
    spec[pci][1].remove(pr)
    spec[tci][1].append(pr)                            # top of the column (north)
    _narrow(tci)
    return spec


def _reorder_pooja_column(boxes):
    """LAST-RESORT pooja-wet fix: permute the vertical ORDER of the rooms in the
    pooja's own column (box-space; the column's footprint is unchanged, so the
    tiling stays exact) and keep the ordering with no pooja-wet contact,
    preferring the pooja high (north)."""
    pj = next((b for b in boxes if b["name"] == "pooja_room"), None)
    if pj is None:
        return boxes
    wet = [b for b in boxes if b["name"] in WET]
    if not any(_touching(pj, w) for w in wet):
        return boxes
    col = sorted([b for b in boxes
                  if abs(b["x"] - pj["x"]) < 0.3 and abs(b["w"] - pj["w"]) < 0.3],
                 key=lambda b: b["y"])
    if not (2 <= len(col) <= 7):
        return boxes
    y0 = min(b["y"] for b in col)
    span = max(b["y"] + b["h"] for b in col) - y0
    if abs(span - sum(b["h"] for b in col)) > 0.3:
        return boxes          # column holds a side-by-side pair β€” repacking
                              # full-width members would overlap it
    others_wet = [w for w in wet if w not in col]
    orig = [(b["y"]) for b in col]
    best, best_key = None, None
    stair_i = next((i for i, b in enumerate(col)
                    if b["name"] == "external_staircase"), None)
    for perm in itertools.permutations(col):
        if stair_i is not None and perm[stair_i] is not col[stair_i]:
            continue                       # the stair keeps its wall position
        y = y0
        pos = {}
        for b in perm:
            pos[id(b)] = y
            y += b["h"]
        # evaluate pooja-wet contact in this ordering
        def probe(b):
            return {"name": b["name"], "x": b["x"], "y": pos[id(b)],
                    "w": b["w"], "h": b["h"]}
        pjp = probe(pj)
        touch = any(_touching(pjp, probe(w)) for w in col
                    if w is not pj and w["name"] in WET)
        touch = touch or any(_touching(pjp, w) for w in others_wet)
        key = (1 if touch else 0, -pos[id(pj)])        # no contact, pooja north
        if best_key is None or key < best_key:
            best_key, best = key, {id(b): pos[id(b)] for b in perm}
    if best is not None and best_key[0] == 0:
        for b in col:
            b["y"] = best[id(b)]
    return boxes


def _reorder_wet_columns(boxes, iw, ih, iy0):
    """When a wet room in a NEIGHBOURING column touches the pooja, permute
    that column's vertical order to slide the wet room out of the pooja's
    y-band (footprint unchanged β€” tiling stays exact). Reverted if the move
    makes the overall plan worse."""
    pj = next((b for b in boxes if b["name"] == "pooja_room"), None)
    if pj is None:
        return boxes
    for wbox in [w for w in boxes if w["name"] in WET and _touching(pj, w)]:
        col = sorted([b for b in boxes
                      if abs(b["x"] - wbox["x"]) < 0.3
                      and abs(b["w"] - wbox["w"]) < 0.3],
                     key=lambda b: b["y"])
        if not (2 <= len(col) <= 7) or pj in col:
            continue        # same-column contact: _reorder_pooja_column's job
        y0 = min(b["y"] for b in col)
        span = max(b["y"] + b["h"] for b in col) - y0
        if abs(span - sum(b["h"] for b in col)) > 0.3:
            continue          # column holds a side-by-side pair β€” skip it
        stair_i = next((i for i, b in enumerate(col)
                        if b["name"] == "external_staircase"), None)
        pen_before = _violations(boxes, iw, ih, iy0)
        orig_y = {id(b): b["y"] for b in col}
        applied = False
        for perm in itertools.permutations(col):
            if stair_i is not None and perm[stair_i] is not col[stair_i]:
                continue                   # the stair keeps its wall position
            y = y0
            pos = {}
            for b in perm:
                pos[id(b)] = y
                y += b["h"]

            def probe(b):
                return {"name": b["name"], "x": b["x"], "y": pos[id(b)],
                        "w": b["w"], "h": b["h"]}
            if any(_touching(pj, probe(b)) for b in col if b["name"] in WET):
                continue
            for b in col:
                b["y"] = pos[id(b)]
            if _violations(boxes, iw, ih, iy0) <= pen_before:
                applied = True
                break
            for b in col:                  # worse overall β€” roll back and keep
                b["y"] = orig_y[id(b)]     # trying other orderings
        if not applied:
            for b in col:
                b["y"] = orig_y[id(b)]
    return boxes


def _cap_pooja(spec):
    """Pooja is a tiny niche: cap its area; the freed depth goes to the largest
    room in the same column (tiling preserved by renormalisation)."""
    for cw, rooms in spec:
        for r in rooms:
            if r[0] == "pooja_room":
                # clamp BOTH ways: a spec sometimes proposes a 1 ft sliver
                r[1] = min(max(r[1], 2.8),
                           max(POOJA_MAX_AREA / max(cw, 1.0), 2.8), 6.0)
    return spec


def _niche_pooja(boxes, iw, ih, iy0):
    """Force the pooja into a compact NICHE shape (aspect <= ~1.7). A wide
    full-width strip (10 x 2.8 = 28 sqft β€” passes the AREA cap but reads as a
    stretched band) is narrowed to ~5.5 ft wide; the freed horizontal strip
    goes to a same-row DRY neighbour (never wet), else becomes the plan's
    single internal_corridor buffer. Never leaves a hole: if neither placement
    works the pooja is restored to its original strip. Tiling stays exact."""
    pj = next((b for b in boxes if b["name"] == "pooja_room"), None)
    if pj is None:
        return boxes
    aspect = max(pj["w"], pj["h"]) / max(min(pj["w"], pj["h"]), 0.1)
    if aspect <= 1.7 and pj["w"] * pj["h"] <= POOJA_MAX_AREA + 1:
        return boxes                                    # already a fine niche
    if pj["w"] <= pj["h"] * 1.5:
        return boxes                                    # only WIDE strips here

    keep_w = min(6.0, max(4.5, POOJA_MAX_AREA / max(pj["h"], 1.0)))
    keep_w = min(keep_w, pj["w"] - 2.8)
    if keep_w < 4.0 or keep_w * pj["h"] < 14.5:
        return boxes            # never trim the niche below its code minimum
    freed_w = pj["w"] - keep_w
    x0, y0, h = pj["x"], pj["y"], pj["h"]

    # a niche hugs a WALL: keep the pooja on its outer edge, push the freed
    # strip toward the interior
    ex0, ex1 = SETBACK_OTHER, SETBACK_OTHER + iw
    trim_right = abs(x0 - ex0) < 0.6 or abs((x0 + pj["w"]) - ex1) >= 0.6
    strip_x = x0 + keep_w if trim_right else x0
    pj_x = x0 if trim_right else x0 + freed_w

    # 1) a same-row DRY neighbour flush against the freed strip can absorb it
    for b in boxes:
        if b is pj or b["name"] in WET or b["name"] == "external_staircase":
            continue
        if abs(b["y"] - y0) > 0.4 or abs(b["h"] - h) > 0.4:
            continue
        if trim_right and abs(b["x"] - (x0 + pj["w"])) < 0.4:
            pj["x"], pj["w"] = pj_x, keep_w
            b["x"], b["w"] = strip_x, b["w"] + freed_w
            return boxes
        if not trim_right and abs((b["x"] + b["w"]) - x0) < 0.4:
            pj["x"], pj["w"] = pj_x, keep_w
            b["w"] += freed_w
            return boxes
    # 2) no dry neighbour: a buffer corridor fills the freed strip. A stretched
    #    13x2.5 "pooja" is a far worse defect than a second thin passage, so
    #    allow up to two β€” the circulation metric keeps the total honest.
    if sum(1 for b in boxes if b["name"] == "internal_corridor") < 2:
        pj["x"], pj["w"] = pj_x, keep_w
        boxes.append({"name": "internal_corridor", "x": strip_x, "y": y0,
                      "w": freed_w, "h": h})
    return boxes                                        # else: leave as-is


def _cap_pooja_box(boxes):
    """Final pooja cap in BOX space (column widths may have changed after the
    spec-space cap). The freed strip goes to the vertically-adjacent room in the
    SAME column, so the tiling stays exact."""
    pj = next((b for b in boxes if b["name"] == "pooja_room"), None)
    if pj is None or pj["w"] * pj["h"] <= POOJA_MAX_AREA + 1:
        return boxes
    new_h = max(2.5, POOJA_MAX_AREA / max(pj["w"], 1.0))
    freed = pj["h"] - new_h
    if freed <= 0.1:
        return boxes
    same_col = [b for b in boxes if b is not pj
                and abs(b["x"] - pj["x"]) < 0.3 and abs(b["w"] - pj["w"]) < 0.3]
    below = next((b for b in same_col
                  if abs(b["y"] + b["h"] - pj["y"]) < 0.3), None)
    above = next((b for b in same_col
                  if abs(pj["y"] + pj["h"] - b["y"]) < 0.3), None)
    if below is not None:            # pooja slides north; the room below grows
        pj["y"] += freed
        pj["h"] = new_h
        below["h"] += freed
    elif above is not None:
        pj["h"] = new_h
        above["y"] -= freed
        above["h"] += freed
    else:
        # pooja fills its whole column: shrink its WIDTH instead, the strip
        # goes to a horizontally-adjacent room with the same vertical span
        new_w = max(2.5, POOJA_MAX_AREA / max(pj["h"], 1.0))
        freed_w = pj["w"] - new_w
        if freed_w <= 0.1:
            return boxes
        same_row = [b for b in boxes if b is not pj
                    and b["name"] != "external_staircase"   # 12x10 is FIXED
                    and abs(b["y"] - pj["y"]) < 0.3
                    and abs(b["h"] - pj["h"]) < 0.3]
        left = next((b for b in same_row
                     if abs(b["x"] + b["w"] - pj["x"]) < 0.3), None)
        right = next((b for b in same_row
                      if abs(pj["x"] + pj["w"] - b["x"]) < 0.3), None)
        if left is not None:
            pj["x"] += freed_w
            pj["w"] = new_w
            left["w"] += freed_w
        elif right is not None:
            pj["w"] = new_w
            right["x"] -= freed_w
            right["w"] += freed_w
    return boxes


def _fix_attached_baths(boxes):
    """An 'attached' bath that does not touch its bedroom is a broken plan.
    The box passes (pairing, service grouping, pooja reordering) can slide a
    bath away from its bedroom, so as a final repair we SWAP LABELS with a
    bathroom that does touch it. Geometry is untouched, all bathrooms are
    similar in size, so the tiling stays exact."""
    def find(nm):
        return next((b for b in boxes if b["name"] == nm), None)

    for bed_nm, bath_nm in ATTACHED_OF.items():
        bed, bath = find(bed_nm), find(bath_nm)
        if bed is None or bath is None or _adjacent(bed, bath):
            continue
        # a bathroom that already touches this bedroom; never steal the bath
        # that is correctly attached to the OTHER bedroom
        protected = set()
        for other_bed, other_bath in ATTACHED_OF.items():
            if other_bed == bed_nm:
                continue
            ob, ot = find(other_bed), find(other_bath)
            if ob is not None and ot is not None and _adjacent(ob, ot):
                protected.add(other_bath)
        cands = [b for b in boxes
                 if b["name"] in BATHROOMS and b is not bath
                 and b["name"] not in protected and _adjacent(bed, b)]
        if cands:
            # prefer the shared bath β€” it has no bedroom of its own to satisfy
            tgt = min(cands, key=lambda b: 0 if b["name"] == "common_bathroom"
                      else 1)
            bath["name"], tgt["name"] = tgt["name"], bath["name"]
    return boxes


def _label_fixes(boxes):
    """Label-only repairs (geometry untouched): the living room opens off the
    staircase when possible; master = biggest bedroom (run AFTER the living
    swap, which can hand a big rectangle to another bedroom label); the pooja
    label moves off a wet wall if a clean swap target exists."""
    # living = the biggest PUBLIC room β€” a living room smaller than the
    # kitchen/dining reads as a broken plan (run BEFORE the stair-adjacency
    # swap so that fix operates on the final living rectangle)
    pub = [b for b in boxes
           if b["name"] in ("living_room", "kitchen", "dining_room")]
    living = next((b for b in pub if b["name"] == "living_room"), None)
    if living is not None:
        big = max(pub, key=lambda b: b["w"] * b["h"])
        if big is not living and \
                big["w"] * big["h"] > living["w"] * living["h"] + 1:
            living["name"], big["name"] = big["name"], living["name"]
    # living beside stair (label swap; early-exit when already fine)
    stair = next((b for b in boxes if b["name"] == "external_staircase"), None)
    living = max((b for b in boxes if b["name"] == "living_room"),
                 key=lambda b: b["w"] * b["h"], default=None)
    if stair is not None and living is not None \
            and not _adjacent(stair, living):
        for tier in (("dining_room", "study", "bedroom_01",
                      "bedroom_02", "bedroom_03"),
                     ("kitchen",)):                     # kitchen: last resort
            cands = [b for b in boxes
                     if b["name"] in tier
                     and _adjacent(b, stair)
                     and min(b["w"], b["h"]) >= 5.0]    # tight plots: rooms
            # (the biggest candidate wins, so on roomy plots this still picks
            # a proper 7ft+ room)
            if cands:
                target = max(cands, key=lambda b: b["w"] * b["h"])
                target["name"], living["name"] = "living_room", target["name"]
                break
    # master = biggest bedroom
    beds = [b for b in boxes if b["name"] in BEDROOMS]
    if beds:
        biggest = max(beds, key=lambda b: b["w"] * b["h"])
        master = next((b for b in beds if b["name"] == "master_bedroom"), None)
        if master is None:
            biggest["name"] = "master_bedroom"
        elif biggest is not master and \
                biggest["w"] * biggest["h"] > master["w"] * master["h"] + 1:
            master["name"], biggest["name"] = biggest["name"], master["name"]
    # pooja off a wet wall via label swap with a small dry room
    pooja = next((b for b in boxes if b["name"] == "pooja_room"), None)
    if pooja is not None:
        wet = [b for b in boxes if b["name"] in WET]
        if any(_touching(pooja, w) for w in wet):
            cands = [b for b in boxes
                     if b["name"] in ("study", "balcony", "internal_corridor")
                     and not any(_touching(b, w) for w in wet)
                     and b["w"] * b["h"] <= 60.0
                     and max(b["w"], b["h"]) <= 12.0]   # never a full column
            if cands:
                target = min(cands, key=lambda b: b["w"] * b["h"])
                pooja["name"], target["name"] = target["name"], pooja["name"]
        # NUCLEAR fallback: pooja could not move β€” relocate the WET label
        # instead (swap it with a small dry room that does not touch the
        # pooja; geometry is untouched, so the tiling stays exact)
        pooja = next(b for b in boxes if b["name"] == "pooja_room")
        kitchen = next((b for b in boxes if b["name"] == "kitchen"), None)
        for w in [w for w in boxes if w["name"] in WET
                  and _touching(pooja, w)]:
            for tier in ("internal_corridor", "study", "balcony",
                         "dining_room"):
                cands = [b for b in boxes if b["name"] == tier
                         and not _touching(pooja, b)
                         and not (w["name"] in BATHROOMS
                                  and kitchen is not None
                                  and _adjacent(b, kitchen))]
                if cands:
                    tgt = min(cands, key=lambda b: b["w"] * b["h"])
                    w["name"], tgt["name"] = tgt["name"], w["name"]
                    break
    # STRETCHED pooja (a full-width sliver is not a niche): move the label
    # into a compact dry cell β€” the final re-cap then shrinks it to ~28 sqft
    # with a sane aspect because the new cell is narrow enough
    pooja = next((b for b in boxes if b["name"] == "pooja_room"), None)
    if pooja is not None and \
            max(pooja["w"], pooja["h"]) > 2.6 * min(pooja["w"], pooja["h"]):
        wet = [b for b in boxes if b["name"] in WET]
        for tier in (("study", "internal_corridor"), ("balcony",)):
            cands = [b for b in boxes
                     if b["name"] in tier
                     and not any(_touching(b, w) for w in wet)
                     and b["w"] <= 8.5 and b["w"] * b["h"] >= 16.0
                     and max(b["w"], b["h"]) <= 13.0]
            if cands:
                target = min(cands, key=lambda b: b["w"] * b["h"])
                pooja["name"], target["name"] = target["name"], pooja["name"]
                break
    return boxes


def _rotate(boxes, plot_w, plot_h, road_side):
    if road_side == "S":
        return boxes
    out = []
    for b in boxes:
        x, y, w, h = b["x"], b["y"], b["w"], b["h"]
        if road_side == "N":
            nx, ny, nw, nh = plot_w - x - w, plot_h - y - h, w, h
        elif road_side == "E":
            nx, ny, nw, nh = plot_w - y - h, x, h, w
        else:                                           # W
            nx, ny, nw, nh = y, plot_h - x - w, h, w
        out.append({"name": b["name"], "x": nx, "y": ny, "w": nw, "h": nh})
    return out


def _mirror_x(boxes, ix0, iw):
    """Mirror the whole tiling left<->right inside the buildable rectangle β€”
    adjacencies survive intact, so it is a free source of structural variety
    when there are fewer unique specs than requested plans."""
    x1 = 2 * ix0 + iw
    return [{**b, "x": x1 - b["x"] - b["w"]} for b in boxes]


def _jitter(boxes, ix0, iy0, ix1, iy1, amount, rng):
    """RAW 'AI generated' look: walls slide a little; overlaps allowed but
    nothing may leave the buildable rectangle."""
    out = []
    for b in boxes:
        d = dict(b)
        d["x"] += rng.uniform(-amount, amount)
        d["y"] += rng.uniform(-amount, amount)
        d["w"] = max(3.0, d["w"] + rng.uniform(-amount, amount))
        d["h"] = max(3.0, d["h"] + rng.uniform(-amount, amount))
        d["x"] = max(ix0, min(d["x"], ix1 - d["w"]))
        d["y"] = max(iy0, min(d["y"], iy1 - d["h"]))
        out.append(d)
    return out


# ── Public API ────────────────────────────────────────────────────────────────

def _spec_from_columns(columns):
    """columns = list of columns, each a list of room-name strings (road->rear
    order, west->east column order). Convert to the engine's spec format with
    placeholder width/depth (both recomputed by the sizing engine)."""
    spec = []
    for col in columns:
        rooms = [[nm, 8.0] for nm in col if nm]
        if rooms:
            spec.append([10.0, rooms])
    return spec


def _backbone_specs(bhk_tag, required, optional):
    """Deterministic, architect-correct column blueprints for a BHK. These are
    the guaranteed-good floor: the staircase sits at a road corner with the
    living beside it, bedrooms hug the outer (edge) columns, the public spine
    (living/dining/kitchen) fills the centre, wet rooms are grouped, and the
    pooja is a north-east niche. Every variant is then sized/polished by the
    shared engine, so they render well on any 30-45 ft plot. Rooms not selected
    are simply omitted."""
    present = set(required) | set(optional)

    def keep(seq):
        return [r for r in seq if r in present]

    beds = keep(["master_bedroom", "bedroom_01", "bedroom_02", "bedroom_03"])
    if not beds:
        beds = ["master_bedroom"]
    baths = keep(["attached_bathroom", "attached_bathroom_02", "common_bathroom"])
    abath = "attached_bathroom" if "attached_bathroom" in present else \
        (baths[0] if baths else None)
    cbath = "common_bathroom" if "common_bathroom" in present else \
        (baths[-1] if baths else None)
    has_util = "utility_area" in present
    has_pooja = "pooja_room" in present
    has_balcony = "balcony" in present
    has_study = "study" in present

    # the SECOND attached bath belongs to the biggest secondary bedroom
    abath2 = "attached_bathroom_02" if "attached_bathroom_02" in present else None

    master = beds[0]
    others = beds[1:]                          # secondary bedrooms

    def unit(bed):
        """A bedroom travels with its own attached bath so the two always share
        a column, and therefore a wall. Only master and bedroom_01 have one."""
        if bed == master and abath:
            return [bed, abath]
        if others and bed == others[0] and abath2:
            return [bed, abath2]
        return [bed]

    def split(seq):
        """Alternate a list into (front-half, back-half) for two edge columns."""
        a, b = [], []
        for i, x in enumerate(seq):
            (a if i % 2 == 0 else b).append(x)
        return a, b

    def flat(beds_):
        out = []
        for b in beds_:
            out += unit(b)
        return out

    blueprints = []

    # ---- Blueprint A: stair + master on the WEST edge, public spine centre,
    #      secondary bedrooms + pooja on the EAST edge ----------------------
    westA = ["external_staircase", master] + ([abath] if abath else []) \
        + flat(others[:1])
    centreA = keep(["living_room", "dining_room", "kitchen"]) \
        + ([cbath] if cbath and cbath != abath else []) \
        + (["utility_area"] if has_util else [])
    eastA = (["balcony"] if has_balcony else []) \
        + flat(others[1:]) \
        + (["study"] if has_study else []) \
        + (["pooja_room"] if has_pooja else [])
    blueprints.append([westA, centreA, eastA])

    # ---- Blueprint B: bedrooms on BOTH edges, stair + living + kitchen the
    #      public spine, pooja tucked NE. Kitchen sits east (SE vastu). -----
    ba, bb = split(others)
    westB = [master] + ([abath] if abath else []) + flat(ba)
    centreB = ["external_staircase"] + keep(["living_room", "dining_room"]) \
        + ([cbath] if cbath and cbath != abath else [])
    eastB = (["balcony"] if has_balcony else []) \
        + keep(["kitchen"]) + (["utility_area"] if has_util else []) \
        + flat(bb) + (["study"] if has_study else []) \
        + (["pooja_room"] if has_pooja else [])
    blueprints.append([westB, centreB, eastB])

    # ---- Blueprint C: stair on the EAST edge, master WEST, a compact 3-col
    #      arrangement with the pooja beside the kitchen in the NE ----------
    westC = (["balcony"] if has_balcony else []) + [master] \
        + ([abath] if abath else []) + flat(others[:1])
    centreC = keep(["living_room", "dining_room", "kitchen"]) \
        + (["utility_area"] if has_util else []) \
        + ([cbath] if cbath and cbath != abath else [])
    eastC = ["external_staircase"] + flat(others[1:]) \
        + (["study"] if has_study else []) \
        + (["pooja_room"] if has_pooja else [])
    blueprints.append([westC, centreC, eastC])

    # keep only non-empty columns, convert to specs, and add a mirrored twin
    # of each for left<->right variety (the engine mirrors geometrically too)
    specs = []
    for bp in blueprints:
        cols = [c for c in bp if c]
        if len(cols) >= 2:
            specs.append((_spec_from_columns(cols), False))
            specs.append((_spec_from_columns([list(reversed(c))
                                              for c in reversed(cols)]),
                          False))
    # engineered PINNED families, designed against the finalised scoring:
    # V-plans chase vastu >= 80, A-plans chase adjacency >= 80.
    # entries become (spec, pinned, mirror_ok)
    out = [(s, p, True) for s, p in specs]
    for cols, mirror_ok in _engineered_columns(bhk_tag, present):
        cols = [[nm for nm in col if nm in present
                 or nm == "external_staircase"] for col in cols]
        cols = [c for c in cols if c]
        if len(cols) >= 2:
            out.append((_spec_from_columns(cols), True, mirror_ok))
    return out


# ── Engineered PINNED blueprints (searched against the finalised scoring) ────
# Column lists are road-south frame, west->east, each bottom->top; found by a
# hill-climb against the REAL metrics with the mandatory gates (room aspect
# and room-size accuracy >= 80) enforced. V-plans maximise Vastu Compliance,
# A-plans maximise Adjacency Satisfaction β€” the client accepts that each
# comes at the other's expense. Rooms absent from a request are filtered out.
_ENGINEERED: Dict[str, List[List[List[str]]]] = {
    "3bhk": [
        # V: vastu plain 91.7 / weighted 57.5, aspect 88, size 84
        [["balcony", "bedroom_01", "bedroom_02", "common_bathroom",
          "attached_bathroom", "utility_area"],
         ["external_staircase", "pooja_room", "master_bedroom"],
         ["dining_room", "living_room", "kitchen"]],
        [["balcony", "bedroom_01", "bedroom_02", "attached_bathroom",
          "common_bathroom", "utility_area"],
         ["external_staircase", "pooja_room", "master_bedroom"],
         ["dining_room", "living_room", "kitchen"]],
        [["balcony", "common_bathroom", "bedroom_02", "bedroom_01",
          "attached_bathroom", "utility_area"],
         ["external_staircase", "pooja_room", "master_bedroom"],
         ["dining_room", "living_room", "kitchen"]],
        [["balcony", "attached_bathroom", "bedroom_01", "bedroom_02",
          "common_bathroom", "utility_area"],
         ["external_staircase", "pooja_room", "master_bedroom"],
         ["dining_room", "living_room", "kitchen"]],
        # A: adjacency 88.3, aspect 90+, size 84+
        [["bedroom_02", "external_staircase", "common_bathroom", "bedroom_01"],
         ["balcony", "living_room", "pooja_room", "master_bedroom"],
         ["dining_room", "kitchen", "utility_area", "attached_bathroom"]],
        [["bedroom_02", "external_staircase", "attached_bathroom",
          "bedroom_01"],
         ["balcony", "living_room", "pooja_room", "master_bedroom"],
         ["dining_room", "kitchen", "utility_area", "common_bathroom"]],
        [["bedroom_01", "external_staircase", "attached_bathroom",
          "bedroom_02"],
         ["balcony", "living_room", "pooja_room", "master_bedroom"],
         ["dining_room", "kitchen", "utility_area", "common_bathroom"]],
        [["bedroom_01", "external_staircase", "common_bathroom", "bedroom_02"],
         ["balcony", "living_room", "pooja_room", "master_bedroom"],
         ["dining_room", "kitchen", "utility_area", "attached_bathroom"]],
    ],
    "2bhk": [
        # V: vastu plain 81.8 / weighted 64.5, aspect 88, size 80
        [["balcony", "master_bedroom", "external_staircase",
          "attached_bathroom", "utility_area"],
         ["common_bathroom", "dining_room", "bedroom_01"],
         ["living_room", "kitchen", "pooja_room"]],
        [["balcony", "master_bedroom", "external_staircase",
          "common_bathroom", "utility_area"],
         ["attached_bathroom", "dining_room", "bedroom_01"],
         ["living_room", "kitchen", "pooja_room"]],
        [["balcony", "master_bedroom", "external_staircase",
          "attached_bathroom", "utility_area"],
         ["common_bathroom", "dining_room", "bedroom_01"],
         ["pooja_room", "living_room", "kitchen"]],
        [["balcony", "master_bedroom", "external_staircase", "utility_area",
          "attached_bathroom"],
         ["common_bathroom", "dining_room", "bedroom_01"],
         ["living_room", "kitchen", "pooja_room"]],
        # A: adjacency 84.2 (vastu plain 81.8 too), aspect 83+, size 85+
        [["balcony", "master_bedroom", "attached_bathroom",
          "external_staircase"],
         ["bedroom_01", "living_room"],
         ["common_bathroom", "utility_area", "kitchen", "dining_room",
          "pooja_room"]],
        [["balcony", "master_bedroom", "common_bathroom",
          "external_staircase"],
         ["bedroom_01", "living_room"],
         ["attached_bathroom", "utility_area", "kitchen", "dining_room",
          "pooja_room"]],
        [["balcony", "master_bedroom", "attached_bathroom",
          "external_staircase"],
         ["bedroom_01", "living_room"],
         ["pooja_room", "common_bathroom", "utility_area", "kitchen",
          "dining_room"]],
        [["balcony", "master_bedroom", "attached_bathroom",
          "external_staircase"],
         ["bedroom_01", "living_room"],
         ["common_bathroom", "utility_area", "pooja_room", "kitchen",
          "dining_room"]],
    ],
    "4bhk": [
        # V: vastu plain 86.7 / weighted 74.0, aspect 90, size 81+
        [["master_bedroom", "bedroom_01", "utility_area", "bedroom_03",
          "attached_bathroom_02", "attached_bathroom"],
         ["common_bathroom", "bedroom_02", "dining_room", "living_room"],
         ["pooja_room", "balcony", "kitchen", "external_staircase", "study"]],
        [["master_bedroom", "bedroom_01", "utility_area", "attached_bathroom",
          "bedroom_03", "attached_bathroom_02"],
         ["common_bathroom", "bedroom_02", "dining_room", "living_room"],
         ["pooja_room", "balcony", "kitchen", "external_staircase", "study"]],
        [["master_bedroom", "bedroom_01", "utility_area", "attached_bathroom",
          "bedroom_03", "attached_bathroom_02"],
         ["common_bathroom", "bedroom_02", "dining_room", "living_room"],
         ["pooja_room", "balcony", "kitchen", "study", "external_staircase"]],
        [["master_bedroom", "bedroom_01", "utility_area",
          "attached_bathroom_02", "attached_bathroom", "bedroom_03"],
         ["common_bathroom", "bedroom_02", "dining_room", "living_room"],
         ["pooja_room", "balcony", "kitchen", "external_staircase", "study"]],
        # A: adjacency 78.3 (structural best under the gates), aspect 90+
        [["balcony", "common_bathroom", "bedroom_02", "living_room",
          "utility_area"],
         ["kitchen", "dining_room", "external_staircase", "pooja_room"],
         ["attached_bathroom_02", "bedroom_03", "master_bedroom",
          "attached_bathroom", "bedroom_01", "study"]],
        [["balcony", "common_bathroom", "bedroom_02", "living_room",
          "utility_area"],
         ["kitchen", "pooja_room", "external_staircase", "dining_room"],
         ["attached_bathroom_02", "bedroom_03", "master_bedroom",
          "attached_bathroom", "bedroom_01", "study"]],
        [["balcony", "common_bathroom", "bedroom_02", "utility_area",
          "living_room"],
         ["kitchen", "dining_room", "external_staircase", "pooja_room"],
         ["attached_bathroom_02", "bedroom_03", "master_bedroom",
          "attached_bathroom", "bedroom_01", "study"]],
        [["balcony", "common_bathroom", "bedroom_02", "living_room",
          "utility_area"],
         ["kitchen", "dining_room", "pooja_room", "external_staircase"],
         ["attached_bathroom_02", "bedroom_03", "master_bedroom",
          "attached_bathroom", "bedroom_01", "study"]],
    ],
}
# a 1BHK is small enough that the classic blueprints already satisfy the
# targets; reuse the 2bhk engineered set minus the absent rooms
_ENGINEERED["1bhk"] = _ENGINEERED["2bhk"]

# the first four entries of every set are the V-family (vastu-optimised,
# NEVER mirrored β€” mirroring swaps east/west and destroys the zones); the
# rest are the A-family (adjacency-optimised, mirror-safe since adjacency
# is symmetric)
_N_VASTU_VARIANTS = 4


def _engineered_columns(bhk_tag, present):
    """Yields (columns, mirror_ok) for the engineered pinned blueprints."""
    out = []
    for i, cols in enumerate(_ENGINEERED.get(bhk_tag, ())):
        out.append((copy.deepcopy(cols), i >= _N_VASTU_VARIANTS))
    return out


def _render_spec(spec, needed, ix0, iy0, iw, ih, rng, mirror=False,
                 pinned=False):
    """Take one abstract column spec (proposer or backbone blueprint) all the
    way to a sized, tiled, polished box list. This is the SHARED geometry
    engine, so both sources are sized and cleaned identically.

    `pinned` marks an ENGINEERED blueprint whose room-to-column assignment and
    in-column order were designed against the finalised scoring β€” the passes
    that shuffle rooms around are skipped so the design survives; the sizing,
    tiling and repair passes still run in full."""
    spec = copy.deepcopy(spec)
    if not pinned:
        # engineered blueprints may carry a deliberate connector corridor;
        # proposer corridors are depth sinks and get stripped
        spec = _strip_corridors(spec)
    spec = _insert_missing(spec, needed)
    spec = _fix_staircase(spec, iw)
    if not pinned:
        spec = _set_column_count(spec, iw, ih)
        spec = _balance_columns(spec, ih)
        spec = _fix_stair_column_mix(spec)
    # NOTE: _fill_stair_column (area-rebalance of the stair column) was tried
    # here for short plots, but it wrecks the proven tall-plot arrangements β€”
    # slot balancing + the depth floors handle both acceptably.
    spec = _cap_pooja(spec)
    spec = _assign_column_widths(spec, iw, ih)
    if not pinned:
        spec = _improve_order(spec, ix0, iy0, iw, ih, rng)
        spec = _group_services(spec)
    boxes = _spec_to_boxes(spec, ix0, iy0, iw, ih)
    boxes = _pair_thin_rooms(boxes, iw, ih, iy0)
    boxes = _split_wide_service(boxes)
    boxes = _pair_pooja(boxes, iw, ih, iy0)
    boxes = _cap_services(boxes)
    boxes = _cap_pooja_box(boxes)
    boxes = _reorder_pooja_column(boxes)
    boxes = _reorder_wet_columns(boxes, iw, ih, iy0)
    boxes = _label_fixes(boxes)
    # bath<->bath label swap only: every candidate is a wet cell, so the wet
    # footprint (and hence the pooja-wet rule) is unchanged by this repair
    boxes = _fix_attached_baths(boxes)
    boxes = _cap_public_hierarchy(boxes)
    boxes = _cap_pooja_box(boxes)          # re-cap after any pooja label swap
    boxes = _niche_pooja(boxes, iw, ih, iy0)
    if mirror:
        boxes = _mirror_x(boxes, ix0, iw)
    return boxes


def generate_population(bhk_tag: str, required, optional,
                        plot_w: float, plot_h: float, road_side: str,
                        n: int = 20, raw_jitter: float = 1.4,
                        base_seed: int = 0) -> Optional[List[Tuple]]:
    """HYBRID generator. A deterministic architect-correct BACKBONE guarantees
    a floor of good plans on any plot; the model adds variety ON TOP when a
    key is present. Both go through the same geometry engine and the same
    scorer, so the best plans (from either source) rank first. Returns
    [(raw_fp, optimised_fp), ...] best-first, or None only if nothing renders."""
    # Build in a road-south frame; rotate to the real road side at the end.
    layout_w = plot_h if road_side in ("E", "W") else plot_w
    layout_h = plot_w if road_side in ("E", "W") else plot_h
    ix0 = SETBACK_OTHER
    iy0 = SETBACK_ROAD
    iw = layout_w - 2 * SETBACK_OTHER
    ih = layout_h - SETBACK_ROAD - SETBACK_OTHER

    all_rooms = list(dict.fromkeys(list(required) + list(optional)))
    needed = [r for r in all_rooms if r != "study"]

    # ── Tier 1: deterministic backbone (always available) ──────────────────
    # entries are (source, spec, pinned, mirror_ok); pinned = engineered
    # against the finalised scoring, so the room-shuffling passes leave it
    # alone; mirror_ok = False for vastu plans (mirroring swaps east/west)
    pool = [("bb", s, pinned, mirror_ok)
            for s, pinned, mirror_ok
            in _backbone_specs(bhk_tag, required, optional)]

    # ── Tier 2: model variety (only when a key exists) ─────────────────────
    if available():
        ck = (bhk_tag, round(plot_w, 1), round(plot_h, 1), road_side,
              tuple(sorted(all_rooms)), n)
        model_specs = _SPEC_CACHE.get(ck)
        if model_specs is None:
            model_specs = _propose(required, optional, iw, ih, n)
            if model_specs:
                _SPEC_CACHE[ck] = model_specs     # cache success only
        if model_specs:
            print(f"[layout_engine] {bhk_tag}: model {len(model_specs)} + "
                  f"backbone {len(pool)} layouts")
            pool += [("ai", s, False, True) for s in model_specs]
        else:
            print(f"[layout_engine] {bhk_tag}: model unavailable, "
                  f"backbone {len(pool)} layouts")
    else:
        print(f"[layout_engine] {bhk_tag}: no API key, "
              f"backbone {len(pool)} layouts")
    if not pool:
        return None

    # ── render every spec, mirror-fill for uniqueness, score, rank ─────────
    plans = []
    seen_sigs = set()

    def _sig(bs):
        return tuple(sorted((b["name"], round(b["x"]), round(b["y"]))
                            for b in bs))
    def _hard_ok(boxes):
        """Invariants that NO plan may ever violate, even a gate-filler: each
        attached bath shares a wall with its own bedroom, and there are no
        overlaps. A plan that fails these is dropped outright."""
        idx = {}
        for b in boxes:
            idx.setdefault(b["name"], []).append(b)
        for bed_nm, bath_nm in ATTACHED_OF.items():
            bed = idx.get(bed_nm, [None])[0]
            bath = idx.get(bath_nm, [None])[0]
            if bed is not None and bath is not None \
                    and not _adjacent(bed, bath):
                return False
        return True

    def _gate_aspect_ok(fp):
        """Generation's OWN aspect gate, intentionally decoupled from the
        displayed aspect metric. It keeps the historical "a room up to 1.8:1
        is fine, tapering to zero at 3.0:1" curve so the SAME plans keep
        passing even though the shown aspect score was re-based to penalise
        from a perfect square. Do NOT swap this for metrics.aspect_ratio_score
        -- that would silently change which plans generate."""
        from . import metrics as _m
        exempt = _m._ASPECT_EXEMPT
        vals = []
        for r in fp.rooms:
            if r.name in exempt:
                continue
            lo, hi = min(r.w, r.h), max(r.w, r.h)
            if lo <= 0:
                continue
            asp = hi / lo
            vals.append(1.0 if asp <= 1.8 else max(0.0, min(1.0, (3.0 - asp) / 1.2)))
        return (sum(vals) / len(vals)) >= 0.795 if vals else True

    def _passes_gates(boxes):
        """The client's PREFERRED all-plan gates: room-size accuracy and
        aspect ratio both >= 80. Gate-passers fill the top slots; the rest
        are still shown (best-first) rather than falling to ugly templates."""
        from . import metrics as _m
        fp = FloorPlan([Room(b["name"], b["x"], b["y"], b["w"], b["h"])
                        for b in boxes], layout_w, layout_h)
        if not _gate_aspect_ok(fp):
            return False
        return _m.room_size_accuracy(fp, "S")[0] >= 0.795

    # Two buckets: plans that pass the mandatory gates (room-size + aspect
    # >= 80) and the rest. Passing plans always fill the top slots; if fewer
    # than n pass (a short / rotated frame where the geometry can't satisfy
    # every gate), we STILL fill up to n with the best remaining plans rather
    # than return short and let the caller fall back to the ugly templates.
    passing, failing = [], []
    for j in range(3 * max(n, len(pool))):
        if len(passing) >= max(n, 1) and j >= len(pool):
            break
        source, base, pinned, mirror_ok = pool[j % len(pool)]
        rng = random.Random(base_seed + j * 977 + 13)
        # reuse alternates a mirror β€” never on a vastu-pinned blueprint
        # (mirroring swaps east and west, destroying its zones)
        mirror = (j // len(pool)) % 2 == 1 and mirror_ok
        boxes = _render_spec(base, needed, ix0, iy0, iw, ih, rng, mirror,
                             pinned)
        if _sig(boxes) in seen_sigs and mirror_ok:
            boxes = _mirror_x(boxes, ix0, iw)
        if _sig(boxes) in seen_sigs:
            continue                           # a true duplicate β€” skip
        if not _hard_ok(boxes):
            continue                           # detached bath / overlap β€” drop
        seen_sigs.add(_sig(boxes))
        pen = _violations(boxes, iw, ih, iy0)
        opt = _rotate(boxes, plot_w, plot_h, road_side)
        raw = _rotate(
            _jitter(boxes, ix0, iy0, ix0 + iw, iy0 + ih, raw_jitter, rng),
            plot_w, plot_h, road_side)
        entry = (pen, j, source, j % len(pool), raw, opt)
        (passing if _passes_gates(boxes) else failing).append(entry)

    passing.sort(key=lambda p: (p[0], p[1]))    # engine score first
    failing.sort(key=lambda p: (p[0], p[1]))
    # tier flag travels with each entry: 0 = passes the gates, 1 = filler
    chosen = [(0, e) for e in passing] + [(1, e) for e in failing]
    chosen = chosen[:max(n, 1)]                 # passing lead, fill the rest
    pairs = []
    for tier, (pen, _j, source, si, raw, opt) in chosen:
        name = f"{bhk_tag}_{source}_{si}"
        raw_fp = FloorPlan([Room(b["name"], round(b["x"], 2), round(b["y"], 2),
                                 round(b["w"], 2), round(b["h"], 2))
                            for b in raw], plot_w, plot_h)
        opt_fp = FloorPlan([Room(b["name"], round(b["x"], 2), round(b["y"], 2),
                                 round(b["w"], 2), round(b["h"], 2))
                            for b in opt], plot_w, plot_h)
        raw_fp.template_name = opt_fp.template_name = name
        pairs.append((tier, raw_fp, opt_fp))

    # FINAL ordering: gate-passers ALWAYS rank above fillers; within each tier
    # the client's finalised fitness decides the order, so rank 1 is the best
    # gate-passing plan under the official scoring system.
    try:
        from . import metrics as _metrics
        scored = sorted(
            ((tier, -_metrics.evaluate(o, road_side).fitness, i)
             for i, (tier, _r, o) in enumerate(pairs)),
            key=lambda t: (t[0], t[1], t[2]))
        pairs = [(pairs[i][1], pairs[i][2]) for _t, _f, i in scored]
    except Exception as exc:                            # pragma: no cover
        print(f"[layout_engine] fitness ordering skipped: {exc}")
        pairs = [(r, o) for _t, r, o in pairs]
    return pairs