File size: 72,117 Bytes
c05974a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
986980c
c05974a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
986980c
 
c05974a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
986980c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c05974a
 
 
 
 
 
 
 
 
986980c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c05974a
 
 
 
 
 
986980c
 
c05974a
986980c
 
 
 
 
 
 
 
 
 
 
c05974a
 
 
986980c
c05974a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
986980c
 
c05974a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
986980c
c05974a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
986980c
 
c05974a
 
 
 
 
 
 
 
 
 
 
 
 
 
986980c
c05974a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np
import random
import math
import os
from core.constants import (ROOM_MIN_AREA, ROOM_MAX_AREA, REQUIRED_ADJACENCIES,
                             VASTU_RULES, COST_PER_SQFT, PLUMBING_COST_PER_METER,
                             WALL_COST_PER_METER, CLIMATE_ZONES,
                             ADJACENCY_MATRIX, ADJ_WEIGHTS,
                             ADJ_HIGH, ADJ_MED, ADJ_LOW, ADJ_ZERO,
                             ADJ_FORBIDDEN, get_adjacency_class)


class Room:
    def __init__(self, name, x, y, w, h):
        self.name = name
        self.x = x      # left edge (ft)
        self.y = y      # bottom edge (ft)
        self.w = w      # width (ft)
        self.h = h      # height (ft)
        self.area = w * h

    @property
    def cx(self): return self.x + self.w / 2
    @property
    def cy(self): return self.y + self.h / 2
    @property
    def right(self): return self.x + self.w
    @property
    def top(self): return self.y + self.h

    def zone(self, plot_w, plot_h):
        """Return compass zone of room centre relative to plot."""
        cx_n = self.cx / plot_w   # 0-1
        cy_n = self.cy / plot_h   # 0-1 (0=south, 1=north)
        if cx_n < 0.33:
            h = "W"
        elif cx_n > 0.66:
            h = "E"
        else:
            h = "C"
        if cy_n > 0.66:
            v = "N"
        elif cy_n < 0.33:
            v = "S"
        else:
            v = "M"
        zone_map = {
            ("W","N"): "NW", ("C","N"): "N", ("E","N"): "NE",
            ("W","M"): "W",  ("C","M"): "Centre", ("E","M"): "E",
            ("W","S"): "SW", ("C","S"): "S", ("E","S"): "SE",
        }
        return zone_map.get((h, v), "Centre")

    def shares_wall(self, other, tol=0.5, min_overlap=2.0):
        """Two rooms share a wall iff their edges meet AND they have a real
        overlap along that wall (β‰₯ `min_overlap` ft). Tiny corner kisses
        (< 2 ft) don't count β€” they're geometric artefacts, not doors.
        """
        touching_v = (abs(self.right - other.x) < tol or
                      abs(other.right - self.x) < tol)
        if touching_v:
            ov = min(self.top, other.top) - max(self.y, other.y)
            if ov >= min_overlap:
                return True
        touching_h = (abs(self.top - other.y) < tol or
                      abs(other.top - self.y) < tol)
        if touching_h:
            ov = min(self.right, other.right) - max(self.x, other.x)
            if ov >= min_overlap:
                return True
        return False

    def distance_to(self, other):
        return math.sqrt((self.cx - other.cx)**2 + (self.cy - other.cy)**2)

    def overlaps(self, other, tol=0.5):
        return (self.x + tol < other.right and other.x + tol < self.right and
                self.y + tol < other.top  and other.y + tol < self.top)


class FloorPlan:
    def __init__(self, rooms, plot_w, plot_h):
        self.rooms = rooms          # list of Room objects
        self.plot_w = plot_w
        self.plot_h = plot_h
        self.scores = {}

    def get_room(self, name):
        for r in self.rooms:
            if r.name == name:
                return r
        return None


def generate_floorplan(room_names, plot_w, plot_h, seed=None):
    """
    Rule-guided rectangle packing floor plan generator.
    Places rooms using priority order and adjacency hints.
    Returns a FloorPlan object.
    """
    if seed is not None:
        random.seed(seed)
        np.random.seed(seed)

    # Sort by size priority: living first, then bedrooms, kitchen, others
    priority_order = [
        "living_room", "dining_room", "kitchen", "master_bedroom",
        "bedroom_01", "bedroom_02", "bedroom_03", "foyer",
        "attached_bathroom", "attached_bathroom_02", "common_bathroom", "pooja_room",
        "balcony", "utility_area", "study", "powder_room", "internal_corridor"
    ]
    sorted_rooms = sorted(room_names,
        key=lambda r: priority_order.index(r) if r in priority_order else 99)

    placed = []
    MARGIN = 1.0  # ft wall thickness

    # Compute target area per room (scaled to fit plot)
    plot_area = plot_w * plot_h
    usable_area = plot_area * 0.85  # 85% usable
    total_min = sum(ROOM_MIN_AREA.get(r, 80) for r in sorted_rooms)
    scale = min(usable_area / total_min, 1.6)

    def target_dims(room_name):
        min_a = ROOM_MIN_AREA.get(room_name, 80) * scale
        # Add randomness for variety
        area = min_a * random.uniform(1.0, 1.3)
        # Prefer aspect ratios between 1:1 and 1:2
        aspect = random.uniform(1.0, 1.8)
        w = math.sqrt(area * aspect)
        h = area / w
        w = max(w, 8.0)   # min 8ft
        h = max(h, 8.0)
        w = min(w, plot_w - 2 * MARGIN)
        h = min(h, plot_h - 2 * MARGIN)
        return round(w, 1), round(h, 1)

    def find_position(room_name, w, h):
        """Try to place room adjacent to a preferred neighbour, else grid pack."""
        preferred_neighbours = [a[1] if a[0]==room_name else
                                 (a[0] if a[1]==room_name else None)
                                 for a in REQUIRED_ADJACENCIES]
        preferred_neighbours = [n for n in preferred_neighbours if n]

        # Try placing next to placed preferred neighbours
        candidates = []
        for pn in preferred_neighbours:
            pr = next((r for r in placed if r.name == pn), None)
            if pr:
                # Try right of pr
                for dx, dy in [(pr.w+MARGIN, 0), (0, pr.h+MARGIN),
                                (-w-MARGIN, 0), (0, -h-MARGIN)]:
                    nx = pr.x + dx
                    ny = pr.y + dy
                    nx = max(MARGIN, min(nx, plot_w - w - MARGIN))
                    ny = max(MARGIN, min(ny, plot_h - h - MARGIN))
                    trial = Room(room_name, nx, ny, w, h)
                    if all(not trial.overlaps(p) for p in placed):
                        candidates.append((nx, ny, 0))  # 0 = preferred

        if candidates:
            candidates.sort(key=lambda c: c[2])
            return candidates[0][0], candidates[0][1]

        # Fallback: grid scan
        step = 2.0
        best = None
        best_score = float('inf')
        for gx in np.arange(MARGIN, plot_w - w - MARGIN + 0.1, step):
            for gy in np.arange(MARGIN, plot_h - h - MARGIN + 0.1, step):
                trial = Room(room_name, gx, gy, w, h)
                if all(not trial.overlaps(p) for p in placed):
                    # Score by distance to plot centre (pack centrally)
                    cx_dist = abs(gx + w/2 - plot_w/2)
                    cy_dist = abs(gy + h/2 - plot_h/2)
                    score = cx_dist + cy_dist + random.uniform(0, 3)
                    if score < best_score:
                        best_score = score
                        best = (gx, gy)
        if best:
            return best
        # Last resort: random
        return (random.uniform(MARGIN, max(MARGIN, plot_w-w-MARGIN)),
                random.uniform(MARGIN, max(MARGIN, plot_h-h-MARGIN)))

    for room_name in sorted_rooms:
        w, h = target_dims(room_name)
        x, y = find_position(room_name, w, h)
        placed.append(Room(room_name, round(x, 1), round(y, 1),
                           round(w, 1), round(h, 1)))

    return FloorPlan(placed, plot_w, plot_h)


# ── Scoring Functions ──────────────────────────────────────────────────────────

def score_adjacency_quality(fp):
    """AQ β€” 0 to 1. Uses the 4-tier ADJACENCY_MATRIX from constants:
      HIGH/MED/LOW reward sharing a wall (or being corridor-connected);
      ZERO/FORBIDDEN penalise wall-sharing.

    The internal corridor counts as a hub: any two rooms that both touch
    the corridor are treated as functionally adjacent at 80% credit, since
    circulation between them is one short doorway away.
    """
    room_map = {r.name: r for r in fp.rooms}
    names = list(room_map.keys())
    corridor = next((r for r in fp.rooms if r.name == "internal_corridor"), None)
    on_corridor = set()
    if corridor is not None:
        for r in fp.rooms:
            if r.name != "internal_corridor" and r.shares_wall(corridor):
                on_corridor.add(r.name)

    pos_total = 0.0
    pos_got   = 0.0
    penalty   = 0.0

    for i, n1 in enumerate(names):
        for n2 in names[i+1:]:
            if "internal_corridor" in (n1, n2):
                continue     # corridor handled implicitly via hub credit
            cls = get_adjacency_class(n1, n2)
            w = ADJ_WEIGHTS.get(cls, 0.0)
            ra, rb = room_map[n1], room_map[n2]
            shares = ra.shares_wall(rb)
            if w > 0:
                pos_total += w
                if shares:
                    pos_got += w
                elif n1 in on_corridor and n2 in on_corridor:
                    pos_got += w * 0.80     # corridor-hub credit
                else:
                    d = ra.distance_to(rb)
                    pos_got += w * max(0.0, 1.0 - d / (fp.plot_w * 0.6))
            elif w < 0 and shares:
                penalty += -w

    base = (pos_got / pos_total) if pos_total > 0 else 0.0
    score = max(0.0, base - 0.08 * penalty)
    return round(min(score, 1.0), 3)


def score_vastu(fp, selected_rules=None):
    """VS β€” 0 to 1. 3-tier rules (HIGH 1.0 / MED 0.5 / LOW 0.2).

    A room often has multiple rules across tiers (e.g. Kitchen HIGH=SE,
    MED=S/E). We award the BEST matching tier per room: the denominator
    counts the room's highest tier weight, the numerator the credit for
    the actually-occupied zone.
    """
    room_map = {r.name: r for r in fp.rooms}

    # Group rules by room_name
    rules_by_room = {}
    for rule_name, room_name, good_zones, weight in VASTU_RULES:
        if selected_rules and rule_name not in selected_rules:
            continue
        if room_name not in room_map:
            continue
        rules_by_room.setdefault(room_name, []).append(
            (rule_name, good_zones, weight))

    total_w = 0.0
    satisfied_w = 0.0
    details = []

    for room_name, rules in rules_by_room.items():
        zone = room_map[room_name].zone(fp.plot_w, fp.plot_h)
        # Denominator: room's top-tier weight (HIGH > MED > LOW)
        top_weight = max(w for _, _, w in rules)
        total_w += top_weight

        # Numerator: best tier whose zone the room actually sits in
        best_credit = 0.0
        best_rule = None
        best_status = "miss"
        for rname, zones, w in rules:
            if zone in zones:
                if w > best_credit:
                    best_credit = w
                    best_rule = rname
                    best_status = "match"
        satisfied_w += best_credit
        if best_rule is None:
            best_rule = rules[0][0]
        details.append((best_rule, room_name, zone, best_status))

    score = round(satisfied_w / total_w, 3) if total_w > 0 else 0.0
    return score, details


def score_spatial_efficiency(fp):
    """SE β€” 0 to 1."""
    total_room_area = sum(r.area for r in fp.rooms)
    plot_area = fp.plot_w * fp.plot_h
    area_util = min(total_room_area / plot_area, 1.0)
    # Graph connectivity β€” all rooms reachable via shared walls?
    connected = 0
    for r in fp.rooms:
        for other in fp.rooms:
            if r != other and r.shares_wall(other):
                connected += 1
                break
    connectivity = connected / len(fp.rooms) if fp.rooms else 0
    se = 0.5 * area_util + 0.5 * connectivity
    return round(se, 3)


def score_layout_compactness(fp):
    """LC β€” 0 to 1."""
    if not fp.rooms:
        return 0.0
    total_area = sum(r.area for r in fp.rooms)
    # Perimeter of bounding box of all rooms
    min_x = min(r.x for r in fp.rooms)
    max_x = max(r.right for r in fp.rooms)
    min_y = min(r.y for r in fp.rooms)
    max_y = max(r.top for r in fp.rooms)
    bbox_area = (max_x - min_x) * (max_y - min_y)
    bbox_perim = 2 * ((max_x - min_x) + (max_y - min_y))
    compactness = (4 * math.pi * bbox_area) / (bbox_perim ** 2) if bbox_perim > 0 else 0
    fill = total_area / bbox_area if bbox_area > 0 else 0
    lc = 0.4 * compactness + 0.6 * fill
    return round(min(lc, 1.0), 3)


def score_cost(fp, finishing: str = "Standard") -> float:
    """CS β€” 0 to 1. Lower estimated rupee cost per sqft β†’ higher score.
    Plans that waste walls or have far-apart wet zones are penalised.
    """
    total_area = sum(r.area for r in fp.rooms) or 1.0
    total = estimate_cost(fp, finishing=finishing)
    cost_per_sqft = total / total_area
    base_rate = COST_PER_SQFT.get(finishing, 2400)
    # Anything ≀1.05Γ— the base rate is "ideal" (score 1.0). Beyond 1.40Γ— β†’ 0.
    ratio = cost_per_sqft / base_rate
    if ratio <= 1.05:
        return 1.0
    if ratio >= 1.40:
        return 0.0
    return round(1.0 - (ratio - 1.05) / 0.35, 3)


def estimate_cost(fp, finishing="Standard"):
    """Returns estimated construction cost in β‚Ή."""
    total_area_sqft = sum(r.area for r in fp.rooms)
    base_cost = total_area_sqft * COST_PER_SQFT[finishing]

    # Wall length cost
    total_wall = 0
    for r in fp.rooms:
        total_wall += 2 * (r.w + r.h)
    # Subtract shared walls (save ~30% for shared)
    shared = 0
    for i, r1 in enumerate(fp.rooms):
        for r2 in fp.rooms[i+1:]:
            if r1.shares_wall(r2):
                shared += min(r1.w, r2.w, r1.h, r2.h)
    wall_cost = (total_wall - shared * 0.6) * WALL_COST_PER_METER * 0.3048  # ft to m

    # Plumbing cost β€” distance between wet areas
    wet_rooms = [r for r in fp.rooms if any(w in r.name for w in ["bathroom","kitchen","utility"])]
    plumbing_cost = 0
    if len(wet_rooms) > 1:
        for i in range(len(wet_rooms)-1):
            d = wet_rooms[i].distance_to(wet_rooms[i+1]) * 0.3048  # ft to m
            plumbing_cost += d * PLUMBING_COST_PER_METER

    total = base_cost + wall_cost + plumbing_cost
    return round(total)


def score_area_compliance(fp, room_names):
    """AC β€” 0 to 1."""
    scores = []
    for r in fp.rooms:
        min_a = ROOM_MIN_AREA.get(r.name, 80)
        max_a = ROOM_MAX_AREA.get(r.name, 200)
        if r.area < min_a:
            dev = (min_a - r.area) / min_a
        elif r.area > max_a:
            dev = (r.area - max_a) / max_a
        else:
            dev = 0
        scores.append(max(0, 1 - dev))
    return round(sum(scores) / len(scores), 3) if scores else 0.0


def climate_suggestions(fp, climate_zone):
    """Returns list of climate suggestion strings."""
    zone_data = CLIMATE_ZONES.get(climate_zone, {})
    suggestions = []
    wwr = zone_data.get("wwr", 0.20)
    buf = zone_data.get("buffer", "W")

    suggestions.append(f"Target Window-to-Wall Ratio: {int(wwr*100)}% "
                       f"({'smaller windows reduce heat gain' if wwr < 0.25 else 'larger windows improve daylight'})")
    suggestions.append(f"Place utility/store rooms on {buf}-facing walls as thermal buffer zones")
    suggestions.append("Ensure cross-ventilation: living room and kitchen should have openings on opposite walls")
    suggestions.append("Orient long axis of building East-West to minimise afternoon sun exposure")
    if "Hot" in climate_zone:
        suggestions.append("Use high thermal mass materials (brick/concrete) for South and West walls")
        suggestions.append("Consider roof overhang depth of 0.6–0.9m on South-facing windows")
    elif "Cold" in climate_zone:
        suggestions.append("Maximise South-facing glazing for passive solar heat gain")
        suggestions.append("Use double-glazed windows on North-facing rooms")
    return suggestions


def _ml_boxes_to_floorplan(boxes, plot_w, plot_h):
    """Convert a list of ML pipeline boxes into a FloorPlan with Room objects."""
    rooms = []
    for b in boxes:
        rooms.append(Room(b["name"],
                          round(float(b["x"]), 2),
                          round(float(b["y"]), 2),
                          round(float(b["w"]), 2),
                          round(float(b["h"]), 2)))
    return FloorPlan(rooms, plot_w, plot_h)


def _complete_and_shape_boxes(boxes, requested_rooms, plot_w, plot_h,
                              max_ratio=1.495, road_side="S", variant_index=0):
    """Keep every requested room and avoid long strip rooms.

    The slightly-below-1.5 cap survives the two-decimal rounding done by
    Room/FloorPlan conversion.
    """
    allowed_names = set(requested_rooms or []) | {"internal_corridor"}
    out = [dict(b) for b in boxes if b.get("name") in allowed_names]
    present = {b.get("name") for b in out}
    cursor = 0
    for room_name in requested_rooms or []:
        if room_name in present:
            continue
        area = max(float(ROOM_MIN_AREA.get(room_name, 60)), 25.0)
        w = max(area ** 0.5, 5.0)
        h = max(area / w, 5.0)
        x = 3.28 + (cursor % 3) * max(w, 6.0)
        y = 6.56 + (cursor // 3) * max(h, 6.0)
        out.append({
            "name": room_name,
            "x": min(x, max(plot_w - w - 3.28, 0.0)),
            "y": min(y, max(plot_h - h - 3.28, 0.0)),
            "w": w,
            "h": h,
        })
        present.add(room_name)
        cursor += 1

    shaped = []
    for b in out:
        fixed = dict(b)
        w = max(float(fixed.get("w", 1.0)), 0.1)
        h = max(float(fixed.get("h", 1.0)), 0.1)
        if fixed.get("name") in set(requested_rooms or []):
            min_area = max(float(ROOM_MIN_AREA.get(fixed["name"], 25.0)), 25.0)
            if w * h < min_area * 0.85 or min(w, h) < 3.0:
                cx = float(fixed.get("x", 0.0)) + w / 2.0
                cy = float(fixed.get("y", 0.0)) + h / 2.0
                short = max((min_area / max_ratio) ** 0.5, 3.0)
                long = short * max_ratio
                if w >= h:
                    w, h = long, short
                else:
                    w, h = short, long
                fixed["x"] = min(max(cx - w / 2.0, 0.0), max(plot_w - w, 0.0))
                fixed["y"] = min(max(cy - h / 2.0, 0.0), max(plot_h - h, 0.0))
                fixed["w"] = w
                fixed["h"] = h
        if fixed.get("name") != "internal_corridor":
            if w > h * max_ratio:
                new_w = h * max_ratio
                fixed["x"] = float(fixed.get("x", 0.0)) + (w - new_w) / 2.0
                fixed["w"] = new_w
            elif h > w * max_ratio:
                new_h = w * max_ratio
                fixed["y"] = float(fixed.get("y", 0.0)) + (h - new_h) / 2.0
                fixed["h"] = new_h
        shaped.append(fixed)
    return _enforce_backend_hard_rules(shaped, requested_rooms, plot_w, plot_h,
                                       max_ratio=max_ratio, road_side=road_side,
                                       variant_index=variant_index)


def _box_touches(a, b, tol=0.65, min_overlap=1.5):
    touching_v = abs((a["x"] + a["w"]) - b["x"]) <= tol or \
                 abs((b["x"] + b["w"]) - a["x"]) <= tol
    if touching_v:
        overlap = min(a["y"] + a["h"], b["y"] + b["h"]) - max(a["y"], b["y"])
        if overlap >= min_overlap:
            return True
    touching_h = abs((a["y"] + a["h"]) - b["y"]) <= tol or \
                 abs((b["y"] + b["h"]) - a["y"]) <= tol
    if touching_h:
        overlap = min(a["x"] + a["w"], b["x"] + b["w"]) - max(a["x"], b["x"])
        if overlap >= min_overlap:
            return True
    return False


def _boxes_overlap(a, b, tol=0.05):
    return (a["x"] + tol < b["x"] + b["w"] and b["x"] + tol < a["x"] + a["w"] and
            a["y"] + tol < b["y"] + b["h"] and b["y"] + tol < a["y"] + a["h"])


def _touches_outer_wall(b, plot_w, plot_h, tol=0.75):
    return (b["x"] <= tol or b["y"] <= tol or
            b["x"] + b["w"] >= plot_w - tol or
            b["y"] + b["h"] >= plot_h - tol)


def _clamp_box_inside(b, plot_w, plot_h):
    b["w"] = max(float(b["w"]), 1.0)
    b["h"] = max(float(b["h"]), 1.0)
    b["x"] = min(max(float(b.get("x", 0.0)), 0.0), max(plot_w - b["w"], 0.0))
    b["y"] = min(max(float(b.get("y", 0.0)), 0.0), max(plot_h - b["h"], 0.0))


def _inner_bounds(plot_w, plot_h, road_side="S"):
    road, other = 6.56, 3.28
    left = road if road_side == "W" else other
    right = road if road_side == "E" else other
    bottom = road if road_side == "S" else other
    top = road if road_side == "N" else other
    return left, bottom, plot_w - right, plot_h - top


def _swap_rectangles(boxes, name_a, name_b):
    a = next((b for b in boxes if b["name"] == name_a), None)
    b = next((b for b in boxes if b["name"] == name_b), None)
    if not a or not b:
        return False
    a["x"], b["x"] = b["x"], a["x"]
    a["y"], b["y"] = b["y"], a["y"]
    a["w"], b["w"] = b["w"], a["w"]
    a["h"], b["h"] = b["h"], a["h"]
    return True


def _resolve_backend_overlaps(boxes, plot_w, plot_h, max_passes=80):
    for _ in range(max_passes):
        changed = False
        for i in range(len(boxes)):
            for j in range(i + 1, len(boxes)):
                a, b = boxes[i], boxes[j]
                if not _boxes_overlap(a, b):
                    continue
                changed = True
                ox = min(a["x"] + a["w"], b["x"] + b["w"]) - max(a["x"], b["x"])
                oy = min(a["y"] + a["h"], b["y"] + b["h"]) - max(a["y"], b["y"])
                if ox <= oy:
                    shift = ox / 2.0 + 0.15
                    if a["x"] + a["w"] / 2 <= b["x"] + b["w"] / 2:
                        a["x"] -= shift
                        b["x"] += shift
                    else:
                        a["x"] += shift
                        b["x"] -= shift
                else:
                    shift = oy / 2.0 + 0.15
                    if a["y"] + a["h"] / 2 <= b["y"] + b["h"] / 2:
                        a["y"] -= shift
                        b["y"] += shift
                    else:
                        a["y"] += shift
                        b["y"] -= shift
                _clamp_box_inside(a, plot_w, plot_h)
                _clamp_box_inside(b, plot_w, plot_h)
        if not changed:
            return boxes
    return _non_overlapping_row_repack(boxes, plot_w, plot_h)


def _hard_rules_ok(boxes, plot_w, plot_h, road_side="S"):
    ix0, iy0, ix1, iy1 = _inner_bounds(plot_w, plot_h, road_side)
    room = {b["name"]: b for b in boxes}
    for b in boxes:
        if (b["x"] < ix0 - 0.05 or b["y"] < iy0 - 0.05 or
                b["x"] + b["w"] > ix1 + 0.05 or
                b["y"] + b["h"] > iy1 + 0.05):
            return False
    for i, a in enumerate(boxes):
        for b in boxes[i + 1:]:
            if _boxes_overlap(a, b):
                return False
    pooja = room.get("pooja_room")
    if pooja is not None:
        if pooja["y"] + pooja["h"] < iy1 - 0.75 or pooja["x"] + pooja["w"] / 2 < (ix0 + ix1) * 0.5:
            return False
    stair = room.get("external_staircase")
    if stair is not None and (abs(stair["w"] - 12.0) > 0.05 or abs(stair["h"] - 10.0) > 0.05):
        return False
    living = room.get("living_room")
    if stair is not None and living is not None and not _box_touches(stair, living):
        return False
    master = room.get("master_bedroom")
    if master is not None:
        master_area = master["w"] * master["h"]
        for name in ("bedroom_01", "bedroom_02", "bedroom_03"):
            other = room.get(name)
            if other is not None and master_area < other["w"] * other["h"] - 1.0:
                return False
    attached = room.get("attached_bathroom")
    if attached is not None:
        if not (attached["x"] <= ix0 + 0.75 or attached["y"] <= iy0 + 0.75 or
            attached["x"] + attached["w"] >= ix1 - 0.75 or
            attached["y"] + attached["h"] >= iy1 - 0.75):
            return False
        if master is not None and not _box_touches(attached, master):
            return False
    common = room.get("common_bathroom")
    if common is not None and not (
            common["x"] <= ix0 + 0.75 or common["y"] <= iy0 + 0.75 or
            common["x"] + common["w"] >= ix1 - 0.75 or
            common["y"] + common["h"] >= iy1 - 0.75):
        return False
    pooja = room.get("pooja_room")
    if pooja is not None:
        for wet_name in ("common_bathroom", "attached_bathroom", "utility_area"):
            wet = room.get(wet_name)
            if wet is not None and _box_touches(pooja, wet, tol=0.75, min_overlap=1.5):
                return False
    for wet_name in ("common_bathroom", "attached_bathroom"):
        wet = room.get(wet_name)
        if wet is not None:
            if wet["w"] * wet["h"] > ROOM_MAX_AREA.get(wet_name, 77) + 8.0:
                return False
            if max(wet["w"] / max(wet["h"], 0.1), wet["h"] / max(wet["w"], 0.1)) > 1.8:
                return False
    return True


def _constraint_layout(boxes, requested_rooms, plot_w, plot_h, max_ratio=1.495,
                       road_side="S", variant_index=0):
    ix0, iy0, ix1, iy1 = _inner_bounds(plot_w, plot_h, road_side)
    iw, ih = ix1 - ix0, iy1 - iy0
    requested = [r for r in dict.fromkeys(requested_rooms or [b["name"] for b in boxes])
                 if r != "foyer"]
    placed = []
    variant = int(variant_index or 0)
    cycle = variant // 5
    public_family = (variant + 3 * cycle) % 4

    def add(name, x, y, w, h):
        if name not in requested or any(b["name"] == name for b in placed):
            return None
        b = {"name": name, "x": round(ix0 + x, 3), "y": round(iy0 + y, 3),
             "w": round(max(w, 1.0), 3), "h": round(max(h, 1.0), 3)}
        placed.append(b)
        return b

    def add_corridor(x, y, w, h):
        b = {"name": "internal_corridor", "x": round(ix0 + x, 3),
             "y": round(iy0 + y, 3), "w": round(max(w, 1.0), 3),
             "h": round(max(h, 1.0), 3)}
        placed.append(b)
        return b

    # Real visual families: 5 public/service arrangements x 4 private-zone
    # arrangements. This deliberately changes room positions/adjacencies, not
    # just dimensions.
    service_family = variant % 3
    private_family = (variant // 3) % 7
    road_h = 10.0
    right_w = 7.4
    left_w = iw - right_w
    top_h = 16.0 if private_family in (0, 2) else 18.0
    mid_h = ih - road_h - top_h
    bath_w = 6.0
    pooja_h = 7.0
    utility_h = 8.0
    kitchen_h = 10.0

    add("external_staircase", 0, 0, 12.0, road_h)
    add("living_room", 12.0, 0, left_w - 12.0, road_h)
    add("balcony", left_w, 0, right_w, road_h)

    # Middle band: living/master/dining/service move by family.
    if service_family == 0:
        attach_w = 6.0
        add("attached_bathroom", 0, road_h, attach_w, 8.0)
        add_corridor(attach_w, road_h, max(left_w - attach_w, 1.0), 8.0)
        add("master_bedroom", 0, road_h + 8.0, left_w, mid_h - 8.0)
        add("kitchen", left_w, road_h, right_w, kitchen_h)
        add("utility_area", left_w, road_h + kitchen_h, right_w, utility_h)
        dining_h = max(ih - road_h - kitchen_h - utility_h - pooja_h, 6.0)
        add("dining_room", left_w, road_h + kitchen_h + utility_h,
            right_w, dining_h)
    elif service_family == 1:
        upper_h = 8.0
        add("attached_bathroom", 0, road_h, 6.0, upper_h)
        add_corridor(6.0, road_h, left_w - 6.0, upper_h)
        add("master_bedroom", 0, road_h + upper_h, left_w, mid_h - upper_h)
        add("kitchen", left_w, road_h, right_w, kitchen_h)
        add("utility_area", left_w, road_h + kitchen_h, right_w, utility_h)
        dining_h = max(ih - road_h - kitchen_h - utility_h - pooja_h, 6.0)
        add("dining_room", left_w, road_h + kitchen_h + utility_h,
            right_w, dining_h)
    else:
        # Balcony stays on the road but shifts next to the staircase; living is
        # a middle room touching the staircase from above.
        placed[:] = [b for b in placed if b["name"] not in ("living_room", "dining_room", "balcony")]
        add("balcony", 12.0, 0, max(left_w - 12.0, 1.0), road_h)
        add("attached_bathroom", 0, road_h, 6.0, 8.0)
        add("living_room", 6.0, road_h, 10.0, 8.0)
        add_corridor(16.0, road_h, max(left_w - 16.0, 1.0), 8.0)
        add("master_bedroom", 0, road_h + 8.0, left_w, mid_h - 8.0)
        add("kitchen", left_w, road_h, right_w, kitchen_h)
        add("utility_area", left_w, road_h + kitchen_h, right_w, utility_h)
        dining_h = max(ih - road_h - kitchen_h - utility_h - pooja_h, 6.0)
        add("dining_room", left_w, road_h + kitchen_h + utility_h,
            right_w, dining_h)

    add("pooja_room", left_w, ih - pooja_h, right_w, pooja_h)

    # Private/top band. Bedrooms touch exterior walls but are arranged in four
    # visibly different topologies.
    top_y = ih - top_h
    bedroom_order = [name for name in ("bedroom_01", "bedroom_02", "bedroom_03", "study", "lift")
                     if name in requested]
    wash_w, wash_h = 6.0, 7.5
    if private_family in (0, 3, 6):
        add("common_bathroom", 0, top_y + top_h - wash_h, wash_w, wash_h)
        if bedroom_order:
            add(bedroom_order[0], 0, top_y, wash_w, top_h - wash_h)
            bedroom_order = bedroom_order[1:]
        bed_x, bed_y, bed_w, bed_h = wash_w, top_y, left_w - wash_w, top_h
        cols = max(len(bedroom_order), 1)
        for i, name in enumerate(bedroom_order if private_family != 6 else list(reversed(bedroom_order))):
            add(name, bed_x + i * bed_w / cols, bed_y, bed_w / cols, bed_h)
    elif private_family in (1, 4):
        add("common_bathroom", 0, top_y + top_h - wash_h, wash_w, wash_h)
        if bedroom_order:
            add(bedroom_order[0], 0, top_y, wash_w, top_h - wash_h)
            bedroom_order = bedroom_order[1:]
        bed_x, bed_y, bed_w, bed_h = wash_w, top_y, left_w - wash_w, top_h
        rows = max(len(bedroom_order), 1)
        for i, name in enumerate(bedroom_order if private_family == 1 else list(reversed(bedroom_order))):
            add(name, bed_x, bed_y + i * bed_h / rows, bed_w, bed_h / rows)
    elif private_family in (2, 5):
        add("common_bathroom", 0, top_y + top_h - wash_h, wash_w, wash_h)
        if bedroom_order:
            add(bedroom_order[0], 0, top_y, wash_w, top_h - wash_h)
            bedroom_order = bedroom_order[1:]
        bed_x, bed_y, bed_w, bed_h = wash_w, top_y, left_w - wash_w, top_h
        if len(bedroom_order) == 2:
            add(bedroom_order[0], bed_x, bed_y, bed_w / 2.0, bed_h)
            add(bedroom_order[1], bed_x + bed_w / 2.0, bed_y, bed_w / 2.0, bed_h)
        elif len(bedroom_order) > 2:
            add(bedroom_order[0], bed_x, bed_y + bed_h * 0.5, bed_w / 2.0, bed_h * 0.5)
            add(bedroom_order[1], bed_x + bed_w / 2.0, bed_y + bed_h * 0.5,
                bed_w / 2.0, bed_h * 0.5)
            rest = bedroom_order[2:]
            cols = max(len(rest), 1)
            for i, name in enumerate(rest):
                add(name, bed_x + i * bed_w / cols, bed_y, bed_w / cols, bed_h * 0.5)
        else:
            for name in bedroom_order:
                add(name, bed_x, bed_y, bed_w, bed_h)

    # Safety: if any requested room was not placed, put it in a compact middle
    # slot away from walls. This rarely triggers but prevents silent omissions.
    for name in requested:
        if not any(b["name"] == name for b in placed):
            add(name, 13.0, road_h + 1.0, 6.0, 6.0)
    return placed

    right_w = min(max(iw * 0.21 + [-0.7, 0.0, 0.6, 1.0, -0.3][variant % 5] + 0.32 * cycle, 6.3), 9.6)
    left_w = iw - right_w
    bottom_h = 10.0
    middle_h = min(max((ih - bottom_h) * 0.42 + [0.0, 0.7, -0.4, 1.0, -0.8][variant % 5] + 0.32 * cycle, 16.0), 19.0)
    private_h = ih - bottom_h - middle_h
    balcony_front_w = min(max(right_w, 6.0), 8.4) if "balcony" in requested else 0.0
    living_w = max(iw - 12.0 - balcony_front_w, 8.0)

    add("external_staircase", 0, 0, 12.0, 10.0)
    attach_w = min(max(left_w * (0.20 + 0.012 * (variant % 3)), 6.0), 6.8)
    master_w = min(max(left_w * (0.58 + 0.015 * ((variant + 1) % 3)), 15.0), 16.4)
    mid_corr_w = 0.0
    dining_w = left_w - attach_w - master_w - mid_corr_w
    if dining_w < 5.0:
        master_w = max(master_w - (5.0 - dining_w), 12.0)
        dining_w = left_w - attach_w - master_w - mid_corr_w
    if public_family < 4:
        add("living_room", 12.0, 0, living_w, bottom_h)
        add("balcony", 12.0 + living_w, 0, balcony_front_w, bottom_h)
        add("attached_bathroom", 0, bottom_h, attach_w, middle_h)
        add("master_bedroom", attach_w, bottom_h, master_w, middle_h)
        if mid_corr_w > 0:
            add_corridor(attach_w + master_w, bottom_h + 1.0,
                         mid_corr_w, max(middle_h - 2.0, 1.0))
        add("dining_room", attach_w + master_w + mid_corr_w, bottom_h,
            dining_w, middle_h)
    service_family = (variant // 2) % 4
    service_h = ih - bottom_h
    kitchen_h = min(max(service_h * (0.21 + 0.01 * (variant % 3)), 9.0), 12.0)
    corridor_h = 0.0
    pooja_h = min(max(right_w, 5.0), 8.0)
    rx = left_w
    if service_family in (0, 1):
        utility_h = max(service_h - kitchen_h - pooja_h - corridor_h, 7.0)
        ry = bottom_h
        if service_family == 0:
            add("kitchen", rx, ry, right_w, kitchen_h)
            ry += kitchen_h
            add("utility_area", rx, ry, right_w, utility_h)
        else:
            add("utility_area", rx, ry, right_w, utility_h)
            ry += utility_h
            add("kitchen", rx, ry, right_w, kitchen_h)
        add("pooja_room", rx, ih - pooja_h, right_w, pooja_h)
    elif service_family == 2 and dining_w >= 14.0 and variant in (2, 10):
        # Kitchen comes into the middle, utility stays on the service wall.
        service_mid_w = min(max(dining_w * 0.55, 6.0), max(dining_w - 3.0, 6.0))
        # Replace dining area locally with kitchen + dining split.
        placed[:] = [b for b in placed if b["name"] != "dining_room"]
        dining_x = attach_w + master_w + mid_corr_w
        add("kitchen", dining_x, bottom_h, service_mid_w, middle_h)
        add("dining_room", dining_x + service_mid_w, bottom_h,
            dining_w - service_mid_w, middle_h)
        add("utility_area", rx, bottom_h, right_w, service_h - pooja_h)
        add("pooja_room", rx, ih - pooja_h, right_w, pooja_h)
    elif False:
        # Utility moves to the middle beside dining; kitchen remains on service wall.
        util_mid_w = min(max(dining_w * 0.45, 5.5), max(dining_w - 3.0, 5.5))
        placed[:] = [b for b in placed if b["name"] != "dining_room"]
        dining_x = attach_w + master_w + mid_corr_w
        add("utility_area", dining_x, bottom_h, util_mid_w, middle_h)
        add("dining_room", dining_x + util_mid_w, bottom_h,
            dining_w - util_mid_w, middle_h)
        add("kitchen", rx, bottom_h, right_w, kitchen_h)
        add("pooja_room", rx, ih - pooja_h, right_w, pooja_h)
    else:
        add("kitchen", rx, bottom_h, right_w, kitchen_h)
        add("utility_area", rx, bottom_h + kitchen_h, right_w,
            service_h - kitchen_h - pooja_h)
        add("pooja_room", rx, ih - pooja_h, right_w, pooja_h)

    top_y = bottom_h + middle_h
    top_h = ih - top_y
    bedroom_order = ("bedroom_01", "bedroom_02", "bedroom_03", "study", "lift")
    if variant % 2:
        bedroom_order = tuple(reversed(bedroom_order))
    bedroom_names = [name for name in bedroom_order
                     if name in requested]
    wet_family = (variant // 4) % 2
    if variant in (12, 15):
        wet_family = 1 - wet_family
    if len(bedroom_names) <= 2:
        wet_family = 0
    if wet_family == 0 or not bedroom_names:
        bath_w = min(max(left_w * 0.22, 6.0), 7.0)
        bedroom_area_w = left_w - bath_w
        common_h = top_h
        add("common_bathroom", 0, top_y + top_h - common_h, bath_w, common_h)
        bed_x, bed_y, bed_w, bed_h = bath_w, top_y, bedroom_area_w, top_h
    else:
        bath_w = min(max(left_w * 0.24, 7.0), 8.0)
        common_h = min(max(top_h * 0.36, 8.0), 10.0)
        add("common_bathroom", 0, top_y + top_h - common_h, bath_w, common_h)
        add(bedroom_names[0], 0, top_y, bath_w, top_h - common_h)
        bedroom_names = bedroom_names[1:]
        bed_x, bed_y, bed_w, bed_h = bath_w, top_y, left_w - bath_w, top_h
    family = public_family % 4
    if bedroom_names and family in (1, 3):
        row_h = bed_h / len(bedroom_names)
        ordered = bedroom_names if family == 1 else list(reversed(bedroom_names))
        for i, name in enumerate(ordered):
            add(name, bed_x, bed_y + i * row_h, bed_w, row_h)
    elif bedroom_names and family == 2 and len(bedroom_names) >= 2:
        top_band = bed_h * 0.52
        lower_band = bed_h - top_band
        add(bedroom_names[0], bed_x, bed_y + lower_band, bed_w / 2.0, top_band)
        add(bedroom_names[1], bed_x + bed_w / 2.0, bed_y + lower_band,
            bed_w / 2.0, top_band)
        rest = bedroom_names[2:]
        if rest:
            col_w = bed_w / len(rest)
            for i, name in enumerate(rest):
                add(name, bed_x + i * col_w, bed_y, col_w, lower_band)
        else:
            add_corridor(bed_x + 1.0, bed_y + 1.0,
                         max(bed_w - 2.0, 1.0), max(lower_band - 2.0, 1.0))
    elif bedroom_names:
        row_h = bed_h / len(bedroom_names)
        for i, name in enumerate(bedroom_names):
            add(name, bed_x, bed_y + i * row_h, bed_w, row_h)
    else:
        add_corridor(bed_x + 1.0, bed_y + 1.0,
                     max(bed_w - 2.0, 1.0), max(bed_h - 2.0, 1.0))

    x = bath_w
    y = top_y + max(1.0, top_h * 0.35)
    for name in requested:
        if any(b["name"] == name for b in placed):
            continue
        add(name, x, y, min(8.0, bed_w), min(7.0, bed_h * 0.4))
        x += 8.0

    for b in placed:
        if b["name"] == "external_staircase":
            b["w"], b["h"] = 12.0, 10.0
    return placed


def _boxes_from_gpt_column_spec(spec, plot_w, plot_h):
    boxes = []
    total_w = sum(max(float(col.get("width", 0.0)), 1e-6) for col in spec) or 1.0
    x = 0.0
    for col_index, col in enumerate(spec):
        col_w = plot_w * max(float(col.get("width", 0.0)), 1e-6) / total_w
        if col_index == len(spec) - 1:
            col_w = plot_w - x
        rooms = col.get("rooms", []) if isinstance(col, dict) else []
        total_h = sum(max(float(room.get("height", 0.0)), 1e-6)
                      for room in rooms) or 1.0
        y = 0.0
        for room_index, room in enumerate(rooms):
            name = room.get("name") if isinstance(room, dict) else None
            if not name:
                continue
            h = plot_h * max(float(room.get("height", 0.0)), 1e-6) / total_h
            if room_index == len(rooms) - 1:
                h = plot_h - y
            boxes.append({"name": name, "x": x, "y": y, "w": col_w, "h": h})
            y += h
        x += col_w
    return boxes


def _generate_gpt_backend_boxes(required_rooms, optional_rooms, plot_w, plot_h,
                                road_side, n):
    try:
        from core import gpt_layout
    except Exception:
        return []
    if not gpt_layout.gpt_available():
        return []
    specs = gpt_layout.propose_column_layouts(
        required_rooms or [], optional_rooms or [], plot_w, plot_h, road_side,
        n_variants=min(max(n, 1), 6), timeout=45.0)
    if not specs:
        return []
    return [_boxes_from_gpt_column_spec(spec, plot_w, plot_h)
            for spec in specs[:n]]


def _non_overlapping_row_repack(boxes, plot_w, plot_h, max_ratio=1.495):
    if not boxes:
        return boxes
    rows = max(1, int(math.ceil(math.sqrt(len(boxes) * plot_h / max(plot_w, 1.0)))))
    cols = max(1, int(math.ceil(len(boxes) / rows)))
    cell_w = plot_w / cols
    cell_h = plot_h / rows
    order = sorted(boxes, key=lambda b: (
        0 if b["name"] == "pooja_room" else
        1 if b["name"] in ("common_bathroom", "attached_bathroom",
                    "attached_bathroom_02") else
        2 if b["name"] == "master_bedroom" else
        3 if b["name"] == "external_staircase" else 4,
        b["name"],
    ))
    for idx, b in enumerate(order):
        row = idx // cols
        col = idx % cols
        w = min(cell_w * 0.92, cell_h * 0.92 * max_ratio)
        h = min(cell_h * 0.92, w * max_ratio)
        if b["name"] == "external_staircase":
            w, h = min(12.0, cell_w * 0.92), min(10.0, cell_h * 0.92)
        b["x"] = col * cell_w + (cell_w - w) / 2.0
        b["y"] = row * cell_h + (cell_h - h) / 2.0
        b["w"] = max(w, 1.0)
        b["h"] = max(h, 1.0)
    return boxes


def _enforce_backend_hard_rules(boxes, requested_rooms, plot_w, plot_h,
                                max_ratio=1.495, road_side="S", variant_index=0):
    boxes = [dict(b) for b in boxes]
    room = {b["name"]: b for b in boxes}

    stair = room.get("external_staircase")
    if stair is not None:
        stair["w"], stair["h"] = 12.0, 10.0
        stair["x"], stair["y"] = 0.0, 0.0
        _clamp_box_inside(stair, plot_w, plot_h)

    pooja = room.get("pooja_room")
    if pooja is not None:
        pooja["w"] = min(max(pooja["w"], 3.0), 8.0)
        pooja["h"] = min(max(pooja["h"], 3.0), 8.0)
        if pooja["w"] > pooja["h"] * max_ratio:
            pooja["w"] = pooja["h"] * max_ratio
        if pooja["h"] > pooja["w"] * max_ratio:
            pooja["h"] = pooja["w"] * max_ratio
        pooja["x"] = plot_w - pooja["w"]
        pooja["y"] = plot_h - pooja["h"]

    master = room.get("master_bedroom")
    if master is not None:
        other_beds = [room[name] for name in ("bedroom_01", "bedroom_02", "bedroom_03")
                      if name in room]
        largest_other = max((b["w"] * b["h"] for b in other_beds), default=0.0)
        if largest_other and master["w"] * master["h"] <= largest_other + 1.0:
            target_area = min(max(largest_other + 20.0, ROOM_MIN_AREA.get("master_bedroom", 150)),
                              min(plot_w * plot_h * 0.22, ROOM_MAX_AREA.get("master_bedroom", 384)))
            short = (target_area / max_ratio) ** 0.5
            master["w"], master["h"] = short * max_ratio, short
            _clamp_box_inside(master, plot_w, plot_h)

    attached = room.get("attached_bathroom")
    if attached is not None and master is not None:
        attached["w"] = min(max(attached["w"], 5.0), 7.0)
        attached["h"] = min(max(attached["h"], 5.0), 8.0)
        attached["x"] = min(master["x"] + master["w"], max(plot_w - attached["w"], 0.0))
        attached["y"] = master["y"]
        if attached["x"] <= master["x"] + master["w"] - 0.2:
            attached["x"] = max(master["x"] - attached["w"], 0.0)
        _clamp_box_inside(attached, plot_w, plot_h)

    living = room.get("living_room")
    if living is not None and stair is not None and not _box_touches(living, stair):
        living["x"] = stair["x"] + stair["w"]
        living["y"] = stair["y"]
        living["h"] = max(living["h"], min(10.0, plot_h - living["y"]))
        _clamp_box_inside(living, plot_w, plot_h)

    for wet_name in ("common_bathroom", "attached_bathroom", "attached_bathroom_02"):
        wet = room.get(wet_name)
        if wet is None or _touches_outer_wall(wet, plot_w, plot_h):
            continue
        distances = {
            "W": wet["x"],
            "E": plot_w - (wet["x"] + wet["w"]),
            "S": wet["y"],
            "N": plot_h - (wet["y"] + wet["h"]),
        }
        side = min(distances, key=distances.get)
        if side == "W":
            wet["x"] = 0.0
        elif side == "E":
            wet["x"] = plot_w - wet["w"]
        elif side == "S":
            wet["y"] = 0.0
        else:
            wet["y"] = plot_h - wet["h"]
        _clamp_box_inside(wet, plot_w, plot_h)

    for b in boxes:
        if b["name"] != "internal_corridor":
            if b["w"] > b["h"] * max_ratio:
                b["w"] = b["h"] * max_ratio
            elif b["h"] > b["w"] * max_ratio:
                b["h"] = b["w"] * max_ratio
        _clamp_box_inside(b, plot_w, plot_h)

    boxes = _resolve_backend_overlaps(boxes, plot_w, plot_h)

    # Re-check critical adjacencies after overlap repair. If repair displaced
    # them, use rectangle swaps with the nearest suitable rooms.
    room = {b["name"]: b for b in boxes}
    if "living_room" in room and "external_staircase" in room and \
            not _box_touches(room["living_room"], room["external_staircase"]):
        living = room["living_room"]
        stair = room["external_staircase"]
        living["x"] = min(stair["x"] + stair["w"], max(plot_w - living["w"], 0.0))
        living["y"] = stair["y"]
        _clamp_box_inside(living, plot_w, plot_h)
    if "attached_bathroom" in room and "master_bedroom" in room and \
            not _box_touches(room["attached_bathroom"], room["master_bedroom"]):
        attached = room["attached_bathroom"]
        master = room["master_bedroom"]
        attached["x"] = min(master["x"] + master["w"], max(plot_w - attached["w"], 0.0))
        attached["y"] = master["y"]
        _clamp_box_inside(attached, plot_w, plot_h)
    boxes = _resolve_backend_overlaps(boxes, plot_w, plot_h)
    if not _hard_rules_ok(boxes, plot_w, plot_h, road_side=road_side):
        boxes = _constraint_layout(boxes, requested_rooms, plot_w, plot_h,
                       max_ratio=max_ratio, road_side=road_side,
                       variant_index=variant_index)
    return boxes


def generate_population(room_names, plot_w, plot_h, n=20,
                          required_rooms=None, optional_rooms=None,
                          road_side="S"):
    """Generate n candidate plans.

    Returns a list of (raw_fp, optimised_fp) tuples so the UI can compare the
    AI's untouched output against the Vastu-optimised + space-tiled version.
    Falls back to the rule-based packer if the trained weights aren't present.
    """
    plans = []
    requested_rooms = list(dict.fromkeys(list(required_rooms or room_names) +
                                         list(optional_rooms or [])))
    requested_rooms = [room for room in requested_rooms if room != "foyer"]
    backend_required = [room for room in (required_rooms or room_names) if room != "foyer"]
    backend_optional = [room for room in (optional_rooms or []) if room != "foyer"]

    # Start with deterministic visual families. These indices are selected by
    # room-position signatures, so a mere 10x9 -> 9x8 resize does not count as
    # a different plan.
    family_variants = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
                       10, 11, 12, 13, 14, 17, 18, 22, 23, 26]
    for variant_index in family_variants[:max(n, 1)]:
        boxes = _constraint_layout(
            [], requested_rooms, plot_w, plot_h, road_side=road_side,
            variant_index=variant_index)
        fp = _ml_boxes_to_floorplan(boxes, plot_w, plot_h)
        fp.template_name = f"family_variant_{variant_index}"
        plans.append((fp, fp))

    if os.getenv("USE_MODEL_BACKENDS", "false").lower() not in ("1", "true", "yes"):
        return plans[:n]

    try:
        gpt_box_sets = _generate_gpt_backend_boxes(
            backend_required,
            backend_optional,
            plot_w,
            plot_h,
            road_side,
            min(n, 4),
        )
        for idx, boxes in enumerate(gpt_box_sets):
            shaped = _complete_and_shape_boxes(
                boxes, requested_rooms, plot_w, plot_h, road_side=road_side,
                variant_index=idx)
            plans.append((_ml_boxes_to_floorplan(shaped, plot_w, plot_h),
                          _ml_boxes_to_floorplan(shaped, plot_w, plot_h)))
    except Exception as e:
        print(f"[generator] GPT backend unavailable, continuing: {e}")

    # Optional external backend hook. It is disabled unless HouseGAN++ is
    # explicitly installed/configured, so the Streamlit app remains runnable.
    try:
        from core import external_houseganpp
        if os.getenv("USE_HOUSEGANPP", "false").lower() in ("1", "true", "yes") and \
            external_houseganpp.is_ready():
            external_plans = external_houseganpp.generate_population(
                room_names=[room for room in room_names if room != "foyer"],
                plot_w=plot_w,
                plot_h=plot_h,
                n=min(n, 3),
                required_rooms=backend_required,
                optional_rooms=backend_optional,
                road_side=road_side,
            )
            if external_plans:
                offset = len(plans)
                for idx, p in enumerate(external_plans):
                    raw = _complete_and_shape_boxes(
                        p["raw_boxes"], requested_rooms, plot_w, plot_h,
                        road_side=road_side, variant_index=offset + idx)
                    opt = _complete_and_shape_boxes(
                        p["boxes"], requested_rooms, plot_w, plot_h,
                        road_side=road_side, variant_index=offset + idx)
                    plans.append((_ml_boxes_to_floorplan(raw, plot_w, plot_h),
                                  _ml_boxes_to_floorplan(opt, plot_w, plot_h)))
    except Exception as e:
        print(f"[generator] HouseGAN++ backend unavailable, continuing: {e}")

    # Try the trained-model pipeline
    try:
        from core import ml_pipeline
        if ml_pipeline.is_ready():
            ml_plans = ml_pipeline.generate_population(
                plot_w=plot_w, plot_h=plot_h, n=n,
                required_rooms=backend_required,
                optional_rooms=backend_optional,
                road_side=road_side)
            offset = len(plans)
            for idx, p in enumerate(ml_plans):
                raw = _complete_and_shape_boxes(
                    p["raw_boxes"], requested_rooms, plot_w, plot_h,
                    road_side=road_side, variant_index=offset + idx)
                opt = _complete_and_shape_boxes(
                    p["boxes"], requested_rooms, plot_w, plot_h,
                    road_side=road_side, variant_index=offset + idx)
                plans.append((_ml_boxes_to_floorplan(raw, plot_w, plot_h),
                              _ml_boxes_to_floorplan(opt, plot_w, plot_h)))
            return plans[:max(n, len(plans))]
    except Exception as e:
        print(f"[generator] ML pipeline unavailable, falling back to rules: {e}")

    for i in range(max(0, n - len(plans))):
        fp = generate_floorplan(room_names, plot_w, plot_h, seed=i * 7 + 42)
        plans.append((fp, fp))   # no optimisation in fallback
    return plans


def score_space_usage(fp, road_side: str = "S") -> float:
    """SU β€” fraction of the buildable (inner-setback) area actually covered
    by rooms. Overlapping area is counted once (a 1ft x 1ft pixel grid is
    used so overlaps don't inflate the score)."""
    sb_road, sb_other = 6.56, 3.28   # 2m / 1m
    left   = sb_road if road_side == "W" else sb_other
    right  = sb_road if road_side == "E" else sb_other
    bottom = sb_road if road_side == "S" else sb_other
    top    = sb_road if road_side == "N" else sb_other
    inner_w = max(fp.plot_w - left - right, 1e-6)
    inner_h = max(fp.plot_h - bottom - top, 1e-6)
    inner_area = inner_w * inner_h

    # rasterise the inner buildable rectangle at 0.5 ft resolution
    import numpy as np
    res = 0.5
    gx = max(1, int(round(inner_w / res)))
    gy = max(1, int(round(inner_h / res)))
    grid = np.zeros((gx, gy), dtype=bool)
    for r in fp.rooms:
        x0 = max(0, int(math.floor((r.x - left) / res)))
        y0 = max(0, int(math.floor((r.y - bottom) / res)))
        x1 = min(gx, int(math.ceil((r.x + r.w - left) / res)))
        y1 = min(gy, int(math.ceil((r.y + r.h - bottom) / res)))
        if x1 > x0 and y1 > y0:
            grid[x0:x1, y0:y1] = True
    used_cells = int(grid.sum())
    used_area = used_cells * res * res
    return round(min(used_area / inner_area, 1.0), 3)


def check_hard_constraints(fp):
    """Validator that returns a dict {rule: True/False} for every hard
    constraint in the professor's spec. Failed rules drag down Fitness."""
    rooms = {r.name: r for r in fp.rooms}
    pw, ph = fp.plot_w, fp.plot_h
    results = {}

    # Setback tolerance β€” a room "touches" the setback rectangle if it
    # comes within 1 ft of it. (Setbacks are 6.56 ft road / 3.28 ft other.)
    SB_TOL = 1.0
    SB_OTHER = 3.28
    SB_ROAD  = 6.56

    def touches_west(r):  return r.x <= SB_OTHER + SB_TOL
    def touches_east(r):  return r.right >= pw - SB_OTHER - SB_TOL
    def touches_south(r): return r.y <= SB_ROAD + SB_TOL    # treat S as road by default
    def touches_north(r): return r.top >= ph - SB_OTHER - SB_TOL

    # 1. Staircase in a corner zone (touches the road edge AND a side edge)
    s = rooms.get("external_staircase")
    if s is not None:
        in_corner = (
            (touches_west(s) or touches_east(s)) and
            (touches_south(s) or touches_north(s))
        )
        results["staircase_in_corner"] = in_corner
    else:
        results["staircase_in_corner"] = True

    # 2. Pooja in NE / N / E zone (use Room.zone)
    p = rooms.get("pooja_room")
    if p is not None:
        results["pooja_in_NE_N_E"] = p.zone(pw, ph) in ("NE", "N", "E")
    else:
        results["pooja_in_NE_N_E"] = True

    # 3. HC1: Pooja must NOT share a wall with any wet room or utility area
    if p is not None:
        pooja_wet_ok = True
        for wet_name in ("common_bathroom", "attached_bathroom",
                 "attached_bathroom_02", "utility_area"):
            wet = rooms.get(wet_name)
            if wet and p.shares_wall(wet, tol=0.5, min_overlap=2.0):
                pooja_wet_ok = False
                break
        results["pooja_not_touching_wet"] = pooja_wet_ok
    else:
        results["pooja_not_touching_wet"] = True

    # 4. Min sizes
    ok = True
    for r in fp.rooms:
        if r.area < ROOM_MIN_AREA.get(r.name, 25) - 2:
            ok = False
            break
    results["min_sizes_met"] = ok

    # 5. All inside setback rectangle
    sb_road, sb_other = 6.56, 3.28
    # we don't know road_side here; use the loose check (any room outside plot)
    results["inside_plot"] = all(
        r.x >= -0.1 and r.y >= -0.1 and
        r.right <= pw + 0.1 and r.top <= ph + 0.1
        for r in fp.rooms
    )

    # 6. Balcony near road edge β€” at least one balcony touches the setback
    bals = [r for r in fp.rooms if r.name == "balcony"]
    if bals:
        touches_any_edge = any(
            touches_west(b) or touches_east(b) or
            touches_south(b) or touches_north(b)
            for b in bals
        )
        results["balcony_on_edge"] = touches_any_edge
    else:
        results["balcony_on_edge"] = True

    # 7. Master >= every other bedroom
    m = rooms.get("master_bedroom")
    if m is not None:
        other_areas = [rooms[k].area for k in
                       ("bedroom_01", "bedroom_02", "bedroom_03") if k in rooms]
        results["master_largest_bedroom"] = all(m.area >= oa - 1 for oa in other_areas)
    else:
        results["master_largest_bedroom"] = True

    # 8. No overlaps between rooms
    overlaps = 0
    rs = fp.rooms
    for i in range(len(rs)):
        for j in range(i + 1, len(rs)):
            a, b = rs[i], rs[j]
            if (a.x + 0.1 < b.right and b.x + 0.1 < a.right and
                a.y + 0.1 < b.top and b.y + 0.1 < a.top):
                overlaps += 1
    results["no_overlaps"] = overlaps == 0

    # 9. Every room touches the setback rectangle (external wall rule), with
    #    the client's per-room EXCEPTIONS:
    #      * internal_corridor β€” always exempt (interior circulation)
    #      * pooja  β€” exempt if surrounded only by living/balcony/kitchen/
    #                 dining/study
    #      * living β€” exempt if one side touches a balcony
    #      * kitchenβ€” exempt if one side touches the utility
    #      * dining β€” exempt if surrounded by living/kitchen/balcony/staircase/
    #                 study/pooja
    #      * washrooms β€” exempt if surrounded by balcony/utility/staircase
    def _on_setback(r):
        return (touches_west(r) or touches_east(r) or
                touches_south(r) or touches_north(r))

    def _touches(a_name, b_name):
        a, b = rooms.get(a_name), rooms.get(b_name)
        return bool(a and b and a.shares_wall(b, tol=0.5, min_overlap=1.5))

    def _neighbours(r):
        out = set()
        for o in fp.rooms:
            if o is r:
                continue
            if r.shares_wall(o, tol=0.5, min_overlap=1.5):
                out.add(o.name)
        return out

    _EXEMPT = {
        "pooja_room":        {"living_room", "balcony", "kitchen",
                              "dining_room", "study"},
        "living_room":       {"balcony"},
        "kitchen":           {"utility_area"},
        "dining_room":       {"living_room", "kitchen", "balcony",
                              "external_staircase", "study", "pooja_room"},
        "common_bathroom":   {"balcony", "utility_area", "external_staircase"},
        "attached_bathroom": {"balcony", "utility_area", "external_staircase"},
        "attached_bathroom_02": {"balcony", "utility_area", "external_staircase"},
    }

    rule = True
    for r in fp.rooms:
        if r.name == "internal_corridor":
            continue
        if _on_setback(r):
            continue
        exempt_set = _EXEMPT.get(r.name)
        if exempt_set is not None:
            nb = _neighbours(r)
            if r.name in ("living_room", "kitchen"):
                # exempt if AT LEAST ONE side touches the listed room
                if nb & exempt_set:
                    continue
            else:
                # exempt if SURROUNDED ONLY by the listed rooms (and corridor)
                if nb and nb <= (exempt_set | {"internal_corridor"}):
                    continue
        rule = False
        break
    results["all_rooms_on_boundary"] = rule

    # ── MANDATORY adjacencies (fail the layout if violated) ────────────────
    # staircase ↔ living, master_bedroom ↔ attached_bath
    if "external_staircase" in rooms and "living_room" in rooms:
        results["staircase_touches_living"] = _touches(
            "external_staircase", "living_room")
    else:
        results["staircase_touches_living"] = True
    if "master_bedroom" in rooms and "attached_bathroom" in rooms:
        results["master_touches_attached_bath"] = _touches(
            "master_bedroom", "attached_bathroom")
    else:
        results["master_touches_attached_bath"] = True
    # utility / common bath / attached bath MUST touch the setback rectangle
    wet_setback_ok = True
    for wet in ("utility_area", "common_bathroom", "attached_bathroom",
                "attached_bathroom_02"):
        w = rooms.get(wet)
        if w is not None and not _on_setback(w):
            # attached/common bath keep their surrounded-by exception
            ex = _EXEMPT.get(wet)
            nb = _neighbours(w) if ex else set()
            if not (ex and nb and nb <= (ex | {"internal_corridor"})):
                wet_setback_ok = False
                break
    results["wet_rooms_on_setback"] = wet_setback_ok

    # HC2: Kitchen must not share a wall with any bathroom
    kitchen = rooms.get("kitchen")
    if kitchen is not None:
        kitchen_bath_ok = True
        for wet_name in ("common_bathroom", "attached_bathroom", "attached_bathroom_02"):
            wet = rooms.get(wet_name)
            if wet and kitchen.shares_wall(wet, tol=0.5, min_overlap=2.0):
                kitchen_bath_ok = False
                break
        results["kitchen_not_touching_bathroom"] = kitchen_bath_ok
    else:
        results["kitchen_not_touching_bathroom"] = True

    # HC3: Staircase must share a wall with foyer (entry connectivity)
    stair = rooms.get("external_staircase")
    foyer_r = rooms.get("foyer")
    if stair is not None and foyer_r is not None:
        results["staircase_touches_foyer"] = stair.shares_wall(
            foyer_r, tol=0.5, min_overlap=2.0)
    else:
        results["staircase_touches_foyer"] = True

    # HC4: Pooja must not be extremely elongated (aspect ratio ≀ 2.5)
    if p is not None:
        long_side = max(p.w, p.h)
        short_side = max(min(p.w, p.h), 0.1)
        results["pooja_near_square"] = (long_side / short_side) <= 2.5
    else:
        results["pooja_near_square"] = True

    # HC5: Corridor must connect to at least one bedroom AND one public room
    corridor = rooms.get("internal_corridor")
    if corridor is not None:
        bedroom_keys = {"master_bedroom", "bedroom_01", "bedroom_02", "bedroom_03"}
        public_keys  = {"living_room", "foyer", "dining_room"}
        touches_bed = any(
            rooms[k].shares_wall(corridor, tol=0.5, min_overlap=2.0)
            for k in bedroom_keys if k in rooms
        )
        touches_pub = any(
            rooms[k].shares_wall(corridor, tol=0.5, min_overlap=2.0)
            for k in public_keys if k in rooms
        )
        results["corridor_connects_zones"] = touches_bed and touches_pub
    else:
        results["corridor_connects_zones"] = True

    # HC6: Coverage β‰₯ 0.88 (total room area / inner buildable area)
    sb_road, sb_other = 6.56, 3.28
    inner_w = max(pw - 2.0 * sb_other, 1.0)
    inner_h = max(ph - sb_road - sb_other, 1.0)
    inner_area = inner_w * inner_h
    total_room_area = sum(r.area for r in fp.rooms)
    results["coverage_adequate"] = (total_room_area / inner_area) >= 0.95

    return results


def _score_one(fp, selected_vastu_rules, weights):
    w_aq, w_vs, w_su, w_ac, w_cs, w_lc = weights
    aq = score_adjacency_quality(fp)
    se = score_spatial_efficiency(fp)
    lc = score_layout_compactness(fp)
    vs, vastu_details = score_vastu(fp, selected_vastu_rules)
    ac = score_area_compliance(fp, [r.name for r in fp.rooms])
    su = score_space_usage(fp)
    cs = score_cost(fp)

    hard = check_hard_constraints(fp)
    _CRITICAL = {"pooja_not_touching_wet", "kitchen_not_touching_bathroom",
                 "no_overlaps", "staircase_touches_living",
                 "master_touches_attached_bath", "wet_rooms_on_setback"}
    n_critical = sum(1 for k, v in hard.items() if not v and k in _CRITICAL)
    n_normal   = sum(1 for k, v in hard.items() if not v and k not in _CRITICAL)
    penalty = 0.15 * n_critical + 0.07 * n_normal

    fitness = (w_vs * vs + w_aq * aq + w_cs * cs +
               w_su * su + w_ac * ac + w_lc * lc)
    fitness = max(0.0, fitness - penalty)
    fp.scores = {
        "AQ": aq, "SE": se, "LC": lc, "VS": vs, "AC": ac, "SU": su, "CS": cs,
        "Fitness": round(fitness, 4),
        "vastu_details": vastu_details,
        "hard_constraints": hard,
        "hard_failed": n_critical + n_normal,
    }
    return fp


def _make_peak_optimised(opt_fp, selected_vastu_rules, weights, road_side="S",
                         trials=None, plan_index=0):
    """Create a stronger third-stage plan by searching multiple layout
    variants/seeds for the same selected room set and returning the highest
    scoring candidate. This is the deterministic stand-in for a future GPT
    API layout proposal.
    """
    try:
        from core import ml_pipeline
        room_names = [r.name for r in opt_fp.rooms if r.name != "internal_corridor"]
        best_fp = opt_fp
        best_score = opt_fp.scores.get("Fitness", -1)

        # Selection is Vastu-weighted: Vastu compliance is the user's top
        # priority, so it gets extra pull on top of its 30% slice of Fitness.
        def _sel(fp):
            return (-fp.scores.get("hard_failed", 0),
                    0.4 * fp.scores.get("Fitness", 0)
                    + 0.6 * fp.scores.get("VS", 0),
                    fp.scores.get("AQ", 0))

        # Best candidate found *within the pinned variant*, independent of the
        # input optimised plan. This is what keeps the six displayed plans
        # structurally distinct: if we compared against ``opt_fp`` (whose score
        # may exceed a particular variant's), low-scoring variants would be
        # discarded and every plan would collapse back to the single global best.
        variant_best_fp = None
        variant_best_key = None

        def consider(boxes):
            nonlocal best_fp, best_score, variant_best_fp, variant_best_key
            if not boxes:
                return
            # Same minimal geometry-first post-chain that generate_one_plan uses.
            boxes = ml_pipeline._optimise_designed_layout(
                boxes, opt_fp.plot_w, opt_fp.plot_h, road_side)
            candidate = _ml_boxes_to_floorplan(boxes, opt_fp.plot_w, opt_fp.plot_h)
            _score_one(candidate, selected_vastu_rules, weights)
            cand_key = _sel(candidate)
            if cand_key > _sel(best_fp):
                best_fp = candidate
                best_score = candidate.scores.get("Fitness", 0)
            if variant_best_key is None or cand_key > variant_best_key:
                variant_best_fp = candidate
                variant_best_key = cand_key

        if trials is None:
            trials = int(os.getenv("PEAK_TRIALS", "18"))

        # Optional GPT candidate. Off by default on deployment unless
        # USE_GPT_PEAK=true, because API calls can make Render restart during
        # long generations.
        if os.getenv("USE_GPT_PEAK", "false").lower() in ("1", "true", "yes"):
            try:
                from core.gpt_layout import propose_layout, get_style_hint
                setbacks = ml_pipeline.get_setbacks(road_side)
                style_hint = get_style_hint(plan_index)
                gpt_boxes = propose_layout(
                    room_names, opt_fp.plot_w, opt_fp.plot_h, road_side, setbacks,
                    timeout=float(os.getenv("GPT_TIMEOUT", "20")),
                    style_hint=style_hint)
                consider(gpt_boxes)
            except Exception as exc:
                print(f"[peak:gpt] unavailable, using deterministic candidates: {exc}")

        # Pin each generated plan to its OWN structural variant so the six
        # displayed plans are visibly different instead of all collapsing to the
        # single global best. perimeter_ring_layout derives its variant from
        # ``option_score % 6`` (which includes the seed), so we only feed seeds
        # whose variant matches this plan's index and keep the best candidate
        # *within that variant*.
        geom_offset = int(sum((r.x * 13 + r.y * 17 + r.w * 19 + r.h * 23)
                              for r in opt_fp.rooms)) % 997
        want_variant = plan_index % 6
        base = int(ml_pipeline.variant_offset(
            room_names, opt_fp.plot_w, opt_fp.plot_h, road_side))
        examined = 0
        # The variant rendered by perimeter_ring_layout is
        # ``(base + passed_seed) % 6``. We sweep ``passed_seed`` over the geom
        # offset window but only keep seeds whose variant matches this plan's
        # index, so plan ``i`` always renders variant ``i % 6``.
        seed = geom_offset
        seed_limit = geom_offset + trials * 6 + 60
        while examined < trials and seed < seed_limit:
            if (base + seed) % 6 == want_variant:
                boxes = ml_pipeline.perimeter_ring_layout(
                    room_names, opt_fp.plot_w, opt_fp.plot_h,
                    road_side=road_side, seed=seed)
                consider(boxes)
                examined += 1
            seed += 1
        # Prefer the best layout found *within this plan's pinned variant* so the
        # six displayed plans stay visibly different. The variant candidates are
        # always valid (gapless, Vastu-reassigned) template layouts, so it is
        # safe to return one even if its score trails the input plan.
        if variant_best_fp is not None:
            return variant_best_fp
        if best_fp is opt_fp:
            # Safety net: variant search produced nothing at all; fall back to
            # the original diverse-seed sweep so we still emit a plan.
            for step in range(trials):
                consider(ml_pipeline.perimeter_ring_layout(
                    room_names, opt_fp.plot_w, opt_fp.plot_h,
                    road_side=road_side, seed=101 + geom_offset + step * 7))
        return best_fp
    except Exception as exc:
        print(f"[peak] failed, using normal optimised plan: {exc}")
        return opt_fp


def rank_plans(plans, selected_vastu_rules,
               w_vs=0.30, w_aq=0.25, w_cs=0.15,
               w_su=0.15, w_ac=0.10, w_lc=0.05,
               road_side="S", regenerate_peak=True):
    """Score and rank plans. Accepts either a list of FloorPlan (legacy) or a
    list of (raw, optimised) tuples. Returns a list of dicts:
        {"raw": raw_fp, "optimised": opt_fp, "fitness_gain": float}
    sorted by the OPTIMISED plan's fitness, descending.

    Objectives (in priority order per the guide's spec):
        VS (Vastu) + AQ (Adjacency) + CS (Cost) + SU (Space) +
        AC (Area Deviation) + LC (Layout Compactness)

    ``regenerate_peak`` β€” when True (default) the displayed "peak" plan is
    re-laid-out from scratch by ``_make_peak_optimised`` (the ml_pipeline
    best-of-N search). When False the supplied OPTIMISED plan is shown AS-IS as
    the peak (used for the PDF-template source, so the displayed plan keeps the
    reference-PDF look instead of being regenerated).
    """
    weights = (w_aq, w_vs, w_su, w_ac, w_cs, w_lc)
    pairs = []
    for idx, item in enumerate(plans):
        if isinstance(item, tuple):
            raw_fp, opt_fp = item
        else:
            raw_fp = opt_fp = item
        _score_one(raw_fp, selected_vastu_rules, weights)
        _score_one(opt_fp, selected_vastu_rules, weights)
        if regenerate_peak:
            peak_fp = _make_peak_optimised(
                opt_fp, selected_vastu_rules, weights, road_side=road_side,
                plan_index=idx)
        else:
            peak_fp = opt_fp                  # show the PDF plan as-is
        pairs.append({
            "raw": raw_fp,
            "optimised": opt_fp,
            "peak": peak_fp,
            "fitness_gain": round(
                opt_fp.scores["Fitness"] - raw_fp.scores["Fitness"], 4),
            "peak_gain": round(
                peak_fp.scores["Fitness"] - raw_fp.scores["Fitness"], 4),
        })
    pairs.sort(key=lambda p: p["peak"].scores["Fitness"], reverse=True)

    def structural_signature(fp):
        key_rooms = ["living_room", "master_bedroom", "dining_room", "kitchen",
                     "utility_area", "common_bathroom", "attached_bathroom",
                     "attached_bathroom_02",
                     "bedroom_01", "bedroom_02", "bedroom_03", "pooja_room"]
        sig = []
        for name in key_rooms:
            r = fp.get_room(name)
            if r is None:
                continue
            # Position cells only; dimensions are intentionally ignored.
            sig.append((name, int((r.cx / max(fp.plot_w, 1e-6)) * 16),
                        int((r.cy / max(fp.plot_h, 1e-6)) * 16)))
        edges = []
        for i, a in enumerate(fp.rooms):
            if a.name == "internal_corridor":
                continue
            for b in fp.rooms[i + 1:]:
                if b.name == "internal_corridor":
                    continue
                if a.shares_wall(b, tol=0.75, min_overlap=1.5):
                    edges.append(tuple(sorted((a.name, b.name))))
        return (tuple(sig), tuple(sorted(set(edges))))

    diversified = []
    seen = set()
    for pair in pairs:
        sig = structural_signature(pair["peak"])
        if sig in seen:
            continue
        seen.add(sig)
        diversified.append(pair)
    if len(diversified) < len(pairs):
        used = {id(p) for p in diversified}
        diversified.extend(p for p in pairs if id(p) not in used)
    return diversified