File size: 69,312 Bytes
c05974a
 
 
 
 
 
 
 
 
986980c
23b1e19
 
 
 
 
c05974a
 
 
 
 
5896096
23b1e19
c05974a
 
 
 
 
 
 
731c1e1
c05974a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e45560
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c05974a
23b1e19
8e45560
23b1e19
8e45560
c05974a
 
00b0961
 
 
 
 
 
 
 
 
 
 
 
8e45560
c05974a
8e45560
 
 
 
431ece4
c05974a
8e45560
 
431ece4
8e45560
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
431ece4
8e45560
431ece4
 
8e45560
431ece4
c05974a
8e45560
 
 
c05974a
8e45560
 
 
431ece4
8e45560
 
 
 
431ece4
8e45560
 
c05974a
8e45560
431ece4
8e45560
431ece4
8e45560
 
 
 
 
fca5520
8e45560
fca5520
 
fb7da99
8e45560
 
fca5520
c05974a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23b1e19
b20d338
 
 
23b1e19
 
b20d338
 
8e45560
 
b20d338
 
 
8e45560
 
 
 
 
 
 
 
 
 
 
b20d338
23b1e19
b20d338
 
8e45560
b20d338
 
23b1e19
 
 
fb7da99
 
 
23b1e19
 
 
 
 
 
 
8e45560
 
 
 
 
 
fb7da99
 
8e45560
 
fb7da99
23b1e19
 
431ece4
 
 
 
 
 
 
 
 
 
 
 
 
fb7da99
 
 
 
 
 
431ece4
 
 
 
 
 
 
986980c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30a3026
 
 
 
 
 
 
 
 
 
 
c05974a
731c1e1
 
dae3466
30a3026
 
 
c05974a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5896096
c05974a
 
 
 
 
 
 
 
 
 
 
 
 
5896096
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
624939e
 
 
 
d84e229
 
 
 
 
 
12697c3
8e45560
d84e229
 
 
12697c3
 
d84e229
 
 
 
 
 
 
 
d4f41d0
 
 
d84e229
12697c3
d4f41d0
 
d84e229
 
 
d4f41d0
 
 
 
 
 
12697c3
 
d84e229
 
 
 
12697c3
 
 
 
50f9caa
 
 
 
 
 
 
23b1e19
 
 
50f9caa
23b1e19
 
 
b20d338
 
731c1e1
b20d338
 
 
 
731c1e1
b20d338
 
50f9caa
 
b20d338
2870d22
 
 
 
 
 
 
 
 
 
 
 
 
 
1508872
 
 
 
 
2870d22
 
1508872
50f9caa
4823593
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
098489e
 
 
b20d338
 
098489e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b20d338
 
 
 
 
4823593
 
1508872
 
 
 
2870d22
 
1508872
 
 
 
 
 
 
 
 
 
624939e
 
 
 
8aad035
1508872
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2870d22
 
1508872
ee0cf05
 
 
 
8aad035
1508872
 
8aad035
 
 
1508872
 
8aad035
 
624939e
 
 
 
0d71fce
 
 
 
098489e
 
3b6c718
098489e
3b6c718
 
 
ee0cf05
 
dae3466
624939e
3b6c718
 
 
 
 
 
0d71fce
3b6c718
0d71fce
098489e
 
 
0d71fce
 
098489e
 
 
 
3b6c718
 
0d71fce
3b6c718
 
 
 
 
 
 
624939e
ee0cf05
 
624939e
c6f0e80
624939e
c6f0e80
 
 
12697c3
 
 
 
c6f0e80
 
 
 
 
12697c3
c6f0e80
 
 
0d71fce
c6f0e80
624939e
c6f0e80
 
 
 
624939e
c6f0e80
 
12697c3
 
 
 
 
624939e
ee0cf05
731c1e1
624939e
 
0d71fce
 
 
c6f0e80
 
 
 
 
 
624939e
 
 
 
c6f0e80
624939e
 
 
ee0cf05
 
624939e
 
0d71fce
3b6c718
 
 
 
 
 
 
 
 
624939e
0d71fce
3b6c718
 
0d71fce
624939e
3b6c718
 
624939e
ee0cf05
 
0d71fce
 
 
 
 
 
 
23b1e19
 
c6f0e80
0d71fce
 
c6f0e80
 
0d71fce
ee0cf05
 
624939e
c6f0e80
 
 
 
 
 
 
 
 
 
624939e
ee0cf05
 
624939e
3b6c718
624939e
3b6c718
 
 
 
 
 
 
 
624939e
3b6c718
 
 
 
 
 
 
8e45560
 
 
 
 
624939e
ee0cf05
 
0d71fce
624939e
d84e229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12697c3
d84e229
 
8e45560
23b1e19
12697c3
 
 
 
 
 
 
c6f0e80
 
 
 
 
 
 
 
ee0cf05
 
c6f0e80
 
 
 
 
 
624939e
ee0cf05
 
624939e
 
 
 
 
 
 
 
 
d4f41d0
b3aaad4
 
 
 
 
 
 
5896096
 
 
16f17a1
 
 
 
 
 
 
 
5896096
b3aaad4
 
 
16f17a1
 
 
 
b3aaad4
5896096
16f17a1
5896096
 
 
d4f41d0
 
 
16f17a1
 
5896096
 
 
 
b3aaad4
 
 
 
 
 
 
5896096
b3aaad4
 
 
 
5896096
 
b3aaad4
5896096
b3aaad4
 
 
 
 
5896096
 
16f17a1
 
 
 
 
 
 
 
 
 
d4f41d0
 
 
 
 
 
 
5896096
 
 
 
 
 
 
16f17a1
 
 
 
 
 
 
 
 
 
 
 
 
 
5896096
 
16f17a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4f41d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16f17a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5896096
 
 
 
c05974a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
731c1e1
 
c05974a
 
 
 
 
 
 
 
 
 
23b1e19
c05974a
 
 
 
 
 
 
 
 
 
 
 
 
 
23b1e19
5896096
c05974a
 
 
23b1e19
c05974a
 
 
 
23b1e19
 
 
 
 
 
 
c05974a
23b1e19
 
c05974a
986980c
c05974a
23b1e19
 
986980c
 
 
23b1e19
c05974a
23b1e19
986980c
 
c05974a
23b1e19
431ece4
c05974a
 
 
 
 
 
 
731c1e1
 
c05974a
 
986980c
 
5896096
624939e
 
 
 
986980c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f65ca8
986980c
 
 
 
 
 
 
 
 
 
c05974a
 
731c1e1
 
c05974a
 
 
 
 
 
 
 
 
 
 
 
 
30a3026
 
 
 
 
 
 
c05974a
 
 
731c1e1
c05974a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a43805
db46f20
986980c
 
c05974a
23b1e19
db46f20
 
 
 
23b1e19
 
 
 
 
 
 
 
 
 
 
 
 
c05974a
b20d338
 
 
 
 
 
431ece4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23b1e19
431ece4
 
 
23b1e19
431ece4
 
 
 
22078f9
 
 
 
 
 
 
 
 
 
731c1e1
 
22078f9
 
 
 
 
 
 
 
 
 
431ece4
731c1e1
1e12981
 
 
 
 
 
 
00b0961
 
1e12981
 
c05974a
23b1e19
b20d338
23b1e19
 
 
 
4823593
731c1e1
 
624939e
1e12981
731c1e1
8aad035
c05974a
1e12981
 
 
 
 
 
 
c05974a
50f9caa
 
 
 
 
 
 
 
 
d4f41d0
 
 
 
 
 
 
 
50f9caa
 
d4f41d0
50f9caa
d4f41d0
 
c05974a
731c1e1
b20d338
 
 
 
731c1e1
b20d338
 
23b1e19
b20d338
23b1e19
 
8e45560
 
 
 
b20d338
 
 
 
 
 
 
098489e
23b1e19
b20d338
 
23b1e19
b20d338
 
 
 
 
 
 
 
23b1e19
b20d338
 
 
23b1e19
 
 
b20d338
 
 
23b1e19
 
 
b20d338
 
 
 
 
 
 
 
 
 
 
 
23b1e19
 
b20d338
 
 
23b1e19
c05974a
 
 
 
731c1e1
 
c05974a
 
 
 
 
731c1e1
c05974a
 
731c1e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c05974a
 
 
 
 
 
 
 
 
 
 
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
import os
import sys
import time

import pandas as pd
import streamlit as st

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from core import metrics as plan_metrics
from core.constants import VASTU_RULES
try:
    from core.constants import ROOM_COLORS as _ROOM_COLORS
except Exception:
    _ROOM_COLORS = {}
from core.generator import FloorPlan, Room, _score_one, generate_population, rank_plans
from core.visualizer import draw_comparison, fig_to_bytes
from core import pdf_templates
from core import pdf_templates_2bhk
from core import pdf_templates_3bhk
from core import pdf_templates_4bhk
from core.render_plan import fig_comparison, fig_floorplan
from floorplan_editor import floor_plan_editor


APP_LAYOUT_VERSION = "2026-06-25-drag-editor-v1"


st.set_page_config(
    page_title="Architectural Floor Plan Generation System",
    page_icon="🏠",
    layout="wide",
    initial_sidebar_state="expanded",
)


if st.session_state.get("app_layout_version") != APP_LAYOUT_VERSION:
    st.session_state.pop("last_top_plans", None)
    st.session_state.pop("last_road_side", None)
    st.session_state["app_layout_version"] = APP_LAYOUT_VERSION


st.markdown(
    """
<style>
    /* ── Light theme ───────────────────────────────────────────────────────
       White surfaces, ink-dark text. Nothing lighter than #5A6B80 is used for
       text, so every label stays readable on white. Base sizes are a step up
       from Streamlit's defaults for legibility on a projector. */
    :root {
        --bg: #FFFFFF; --card: #F7FAFC; --line: #D8E1EA;
        --accent: #1F4E79; --accent-2: #2E75B6;
        --ink: #14213D; --ink-2: #41546B; --ink-3: #5A6B80;
    }
    html, body, .stApp { background: var(--bg); color: var(--ink); }
    .stApp, .stMarkdown, p, li, span, label, div[data-testid="stMarkdownContainer"] {
        font-size: 1.02rem; color: var(--ink);
    }
    .block-container { padding-top: 2.0rem; max-width: 1560px; }

    .main-header {
        background: #0a2a54;
        padding: 1.7rem 2rem;
        border-radius: 12px;
        margin-bottom: 1.5rem;
        text-align: center;
    }
    /* The band is navy, so its text MUST be forced light β€” Streamlit's own
       heading rules are more specific than a bare `.main-header h1` and were
       repainting the title in --ink, i.e. dark navy on dark navy. */
    .main-header h1, .main-header h1 * {
        color: #FFFFFF !important; font-size: 2.15rem; margin: 0;
        letter-spacing: 0.3px; font-weight: 800; line-height: 1.2;
    }
    .main-header p, .main-header p * {
        color: #E8F1FB !important; font-size: 1.08rem; margin: 0.45rem 0 0 0;
        font-weight: 500;
    }
    .main-header a { display: none !important; }   /* anchor-link icon */

    .section-header {
        border-left: 5px solid var(--accent-2);
        padding-left: 0.85rem;
        margin: 1.8rem 0 0.8rem 0;
        font-size: 1.35rem; font-weight: 700; color: var(--accent);
        letter-spacing: 0.2px;
    }

    /* Metric tiles as clean white cards */
    div[data-testid="stMetric"] {
        background: var(--card); border: 1px solid var(--line);
        border-radius: 12px; padding: 0.85rem 1rem;
    }
    div[data-testid="stMetricLabel"] p { font-size: 0.95rem; color: var(--ink-2); }
    div[data-testid="stMetricValue"] { font-size: 1.6rem; font-weight: 700;
                                       color: var(--ink); }

    /* Tables */
    div[data-testid="stDataFrame"] { font-size: 1.0rem; }
    div[data-testid="stDataFrame"] * { color: var(--ink); }

    /* Expanders / tabs */
    div[data-testid="stExpander"] summary p { font-size: 1.05rem; font-weight: 600;
                                              color: var(--accent); }
    button[data-baseweb="tab"] p { font-size: 0.98rem; }

    /* Captions must stay readable β€” Streamlit's default grey is too light */
    div[data-testid="stCaptionContainer"], div[data-testid="stCaptionContainer"] p {
        color: var(--ink-3) !important; font-size: 0.92rem;
    }

    /* Plan gallery tiles */
    .plan-tile img {
        border-radius: 10px; border: 1px solid var(--line);
        background: #fff; transition: all 0.15s ease;
    }
    .plan-tile-sel img { border: 2px solid var(--accent-2);
                         box-shadow: 0 0 0 3px rgba(46,117,182,0.18); }

    .room-list {
        background: var(--card); border: 1px solid var(--line);
        border-radius: 8px; padding: 0.7rem 0.9rem;
        font-size: 0.95rem; line-height: 1.5;
    }

    /* Buttons */
    .stButton>button { border-radius: 9px; font-weight: 600; font-size: 1.0rem;
                       transition: all 0.15s ease; }
    .stButton>button[kind="primary"] {
        background: linear-gradient(135deg, var(--accent), var(--accent-2));
        border: none; color: #FFFFFF;
    }
    .stButton>button[kind="primary"]:hover { transform: translateY(-1px); }
    .stButton>button[kind="secondary"] {
        background: #FFFFFF; border: 1px solid var(--line); color: var(--ink-2);
    }
    .stButton>button[kind="secondary"]:hover { border-color: var(--accent-2);
                                               color: var(--accent); }

    /* Sidebar: light, and pinned so the room key stays visible while the
       gallery scrolls. */
    section[data-testid="stSidebar"] {
        background: #F4F8FC; border-right: 1px solid var(--line);
        position: sticky !important; top: 0 !important;
        align-self: flex-start; height: 100vh !important;
    }
    section[data-testid="stSidebar"] > div:first-child { height: 100%; overflow-y: auto; }
    section[data-testid="stSidebar"] * { color: var(--ink); }
    div[data-testid="stSidebarUserContent"] { min-height: 100%; padding-bottom: 1rem; }
</style>
""",
    unsafe_allow_html=True,
)


def pretty_room(name: str) -> str:
    return (
        name.replace("_", " ")
        .replace("01", "1")
        .replace("02", "2")
        .replace("03", "3")
        .title()
    )


def render_side_scores(raw_fp, opt_fp, road_side, selected_vastu=None):
    """Compact scorecard for the column beside the plans. Rendered as small HTML
    rows rather than st.metric tiles so that EVERY metric β€” fitness down to
    functional zoning β€” fits within the height of the plan next to it."""
    cr = plan_metrics.evaluate(raw_fp, road_side, selected_vastu)
    co = plan_metrics.evaluate(opt_fp, road_side, selected_vastu)

    def row(lab, val, dv, big=False):
        col = "#1B7F3B" if dv > 0.05 else ("#C0392B" if dv < -0.05 else "#5A6B80")
        sz = "15px" if big else "13px"
        wt = "700" if big else "500"
        return (
            f'<div style="display:flex;justify-content:space-between;'
            f'align-items:baseline;padding:5px 0;border-bottom:1px solid #E3EAF2">'
            f'<span style="font-size:{sz};color:#41546B">{lab}</span>'
            f'<span style="font-size:{sz};font-weight:{wt};color:#14213D">'
            f'{val * 100:.0f}%<span style="color:{col};font-size:11.5px;'
            f'margin-left:6px">{dv * 100:+.0f}</span></span></div>')

    html = ['<div style="background:#F7FAFC;border:1px solid #D8E1EA;'
            'border-radius:10px;padding:11px 13px">',
            '<div style="font-size:12px;letter-spacing:.4px;color:#1F4E79;'
            'text-transform:uppercase;font-weight:700;margin-bottom:6px">'
            'Score</div>',
            row("Fitness", co.fitness, co.fitness - cr.fitness, big=True)]
    for key, lab in plan_metrics.METRIC_LABELS:
        html.append(row(lab, co.scores[key],
                        co.scores[key] - cr.scores[key]))
    html.append('<div style="font-size:11px;color:#5A6B80;margin-top:7px">'
                'green/red = change vs the AI-generated plan</div></div>')
    st.markdown("".join(html), unsafe_allow_html=True)


def render_side_legend(fp):
    """Room-colour key for the sidebar. Set in readable type with generous rows
    so it fills the column properly rather than sitting as a cramped block with
    dead space beneath it."""
    seen, html = set(), []
    for r in fp.rooms:
        if r.name in seen:
            continue
        seen.add(r.name)
        col = _ROOM_COLORS.get(r.name, "#607D8B")
        html.append(
            '<div style="display:flex;align-items:center;gap:11px;'
            'padding:8px 2px;border-bottom:1px solid #E3EAF2;'
            'font-size:15px;color:#14213D">'
            f'<span style="width:17px;height:17px;border-radius:4px;'
            f'background:{col};flex:0 0 17px;'
            f'border:1px solid rgba(0,0,0,.15)"></span>'
            f'<span>{pretty_room(r.name)}</span></div>')
    st.markdown(
        '<div style="font-size:13px;letter-spacing:.6px;text-transform:uppercase;'
        'color:#1F4E79;font-weight:700;margin:2px 0 6px">Rooms</div>'
        + "".join(html), unsafe_allow_html=True)


def plan_thumbnail(fp, road_side):
    """A small cached PNG of one plan for the gallery. Cached by the plan's
    geometry so clicking a tile (which reruns the whole page) does not
    re-render all twenty every time."""
    sig = (road_side, tuple((r.name, round(r.x, 1), round(r.y, 1),
                             round(r.w, 1), round(r.h, 1)) for r in fp.rooms))
    cache = st.session_state.setdefault("_thumb_cache", {})
    key = hash(sig)
    if key in cache:
        return cache[key]
    import matplotlib.pyplot as _plt
    from core.render_plan import draw_plan
    fig, ax = _plt.subplots(figsize=(2.7, 3.4))
    # A gallery tile is a PREVIEW: room names only, at roughly half the normal
    # text size. Full-size labels on a tile this small came out bigger than the
    # rooms they sat in, and the dimensions are unreadable at this scale anyway
    # β€” the plan opens at full size on click.
    draw_plan(ax, fp, fp.plot_w, fp.plot_h, road_side, "",
              show_dims=False, text_scale=0.55)
    fig.tight_layout(pad=0.15)
    png = fig_to_bytes(fig).getvalue()
    _plt.close(fig)
    cache[key] = png
    return png


def enforce_bhk_rooms(plan_type: str, required_rooms, optional_rooms):
    required = list(dict.fromkeys(required_rooms))
    optional = list(dict.fromkeys(optional_rooms))

    def require(room):
        if room not in required:
            required.append(room)
        if room in optional:
            optional.remove(room)

    def remove(room):
        if room in required:
            required.remove(room)
        if room in optional:
            optional.remove(room)

    bedroom_counts = {"1BHK": 0, "2BHK": 1, "3BHK": 2, "4BHK": 3}
    for room in ("bedroom_01", "bedroom_02", "bedroom_03"):
        remove(room)
    for room in ("bedroom_01", "bedroom_02", "bedroom_03")[:bedroom_counts[plan_type]]:
        require(room)

    require("common_bathroom")
    if plan_type == "1BHK":
        remove("attached_bathroom")
        remove("attached_bathroom_02")
    elif plan_type == "2BHK":
        remove("attached_bathroom_02")
    elif plan_type == "3BHK":
        require("attached_bathroom")
        remove("attached_bathroom_02")
    else:
        require("attached_bathroom")
        require("attached_bathroom_02")
    return required, optional


def metric_row(raw_fp, opt_fp, road_side="S", selected_vastu=None):
    """One row of headline numbers β€” ALL from the finalised scoring system, so
    every panel on the page agrees (no more one Vastu here, another there)."""
    cr = plan_metrics.evaluate(raw_fp, road_side, selected_vastu)
    co = plan_metrics.evaluate(opt_fp, road_side, selected_vastu)

    def cell(col, label, key, is_fit=False):
        rv = cr.fitness if is_fit else cr.scores[key]
        ov = co.fitness if is_fit else co.scores[key]
        col.metric(label, f"{ov * 100:.1f}%", f"{(ov - rv) * 100:+.1f}%")

    cols = st.columns(6)
    cols[0].metric("Layout Proposer Fitness", f"{cr.fitness * 100:.1f}%")
    cell(cols[1], "Domain Expert Fitness", None, is_fit=True)
    cell(cols[2], "Vastu", "vastu")
    cell(cols[3], "Adjacency", "adjacency")
    cell(cols[4], "Constraints", "constraints")
    cell(cols[5], "Space Utilization", "space_utilization")


def room_presence_line(fp):
    counts = {}
    for room in fp.rooms:
        counts[room.name] = counts.get(room.name, 0) + 1
    parts = [
        f"Master: {counts.get('master_bedroom', 0)}",
        f"Bedroom: {counts.get('bedroom_01', 0) + counts.get('bedroom_02', 0) + counts.get('bedroom_03', 0)}",
        f"Study: {counts.get('study', 0)}",
        f"Dining: {counts.get('dining_room', 0)}",
        f"Utility: {counts.get('utility_area', 0)}",
    ]
    return " | ".join(parts)


def score_table(fp):
    score = fp.scores
    return pd.DataFrame(
        {
            "Metric": ["Fitness", "Vastu", "Adjacency", "Cost",
                       "Space Usage", "Area Compliance", "Layout Compactness"],
            "Score": [
                f"{score['Fitness']:.3f}",
                f"{score['VS'] * 100:.0f}%",
                f"{score['AQ'] * 100:.0f}%",
                f"{score['CS'] * 100:.0f}%",
                f"{score['SU'] * 100:.0f}%",
                f"{score['AC'] * 100:.0f}%",
                f"{score['LC'] * 100:.0f}%",
            ],
        }
    )


def score_formula_table(fp):
    score = fp.scores
    failed = score.get("hard_failed", 0)
    return pd.DataFrame(
        {
            "UI metric": [
                "Fitness",
                "Vastu",
                "Adjacency",
                "Cost",
                "Space Usage",
                "Area Compliance",
                "Layout Compactness",
            ],
            "Calculation used": [
                "30% VS + 25% AQ + 15% CS + 15% SU + 10% AC + 5% LC - hard-constraint penalty",
                "matched Vastu rule weight / total applicable Vastu rule weight x 100",
                "earned adjacency weight / required adjacency weight, minus forbidden/avoid penalties x 100",
                "1.0 when estimated cost/sqft <= 1.05 x base rate; 0.0 when >= 1.40 x base rate; linear between x 100",
                "occupied buildable-area grid cells / total inner setback area x 100",
                "average room-size compliance against min/max guide table x 100",
                "0.4 x bounding-box compactness + 0.6 x room fill inside bounding box x 100",
            ],
            "Current value": [
                f"{score['Fitness']:.3f} ({failed} hard checks failed)",
                f"{score['VS'] * 100:.0f}%",
                f"{score['AQ'] * 100:.0f}%",
                f"{score['CS'] * 100:.0f}%",
                f"{score['SU'] * 100:.0f}%",
                f"{score['AC'] * 100:.0f}%",
                f"{score['LC'] * 100:.0f}%",
            ],
        }
    )


def _pct(v):
    return f"{v * 100:.1f}%"


def fig_connectivity_graph(nodes, edges, blocked_edges=()):
    """The plan's access graph. Each room is a small dot at its centroid with
    its name beside it (never inside β€” the text is unreadable in a dot). A SOLID
    line is a legal doorway you may walk through; a DOTTED line is a pair of
    rooms that physically touch but may not be used as a route (e.g. two
    bedrooms), which is what usually explains a stranded room."""
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots(figsize=(3.6, 3.1), dpi=110)
    for i, j in blocked_edges:
        ax.plot([nodes[i][1], nodes[j][1]], [nodes[i][2], nodes[j][2]],
                ":", color="#E53935", lw=1.0, alpha=0.75, zorder=1)
    for i, j in edges:
        ax.plot([nodes[i][1], nodes[j][1]], [nodes[i][2], nodes[j][2]],
                "-", color="#8899A6", lw=1.2, zorder=2)
    short = {"external_staircase": "Staircase", "internal_corridor": "Passage",
             "attached_bathroom": "Att. Bath", "attached_bathroom_02": "Att. Bath 2",
             "common_bathroom": "Common Bath", "master_bedroom": "Master",
             "utility_area": "Utility", "living_room": "Living",
             "dining_room": "Dining", "pooja_room": "Pooja",
             "bedroom_01": "Bed 1", "bedroom_02": "Bed 2", "bedroom_03": "Bed 3",
             "walk_in_closet": "Closet"}
    # Labels sit off the dot and are joined to it by a thin leader, so which
    # name belongs to which dot is never in doubt even when rooms sit close.
    spots = [(13, 9), (-13, 9), (13, -11), (-13, -11)]
    for k, (name, cx, cy, reach, is_entry, _hop) in enumerate(nodes):
        color = "#2E7D32" if is_entry else ("#1E88E5" if reach else "#E53935")
        ax.scatter([cx], [cy], s=46, color=color, edgecolor="white",
                   linewidth=1.0, zorder=4)
        dx, dy = spots[k % len(spots)]
        ax.annotate(short.get(name, pretty_room(name)), (cx, cy),
                    textcoords="offset points", xytext=(dx, dy),
                    ha="left" if dx > 0 else "right", va="center",
                    fontsize=6, color="#111111", zorder=5,
                    bbox=dict(fc="white", ec=color, lw=0.5,
                              boxstyle="round,pad=0.22", alpha=0.95),
                    arrowprops=dict(arrowstyle="-", color=color, lw=0.7,
                                    shrinkA=0, shrinkB=2))
    ax.set_aspect("equal")
    ax.axis("off")
    ax.margins(0.18)
    ax.set_title("Access graph β€” green entry Β· blue reachable Β· red isolated\n"
                 "solid = usable doorway Β· dotted = touching but not a route",
                 fontsize=6)
    fig.tight_layout()
    return fig


def render_edit_comparison(orig_fp, edited_fp, road_side, selected_vastu=None):
    """Score the plan the user edited in the room editor with the SAME finalised
    system and compare it, metric by metric, to the original optimised plan.
    (Walls and doors are visual only and do not change the score; moving,
    resizing or deleting rooms does.)"""
    before = plan_metrics.evaluate(orig_fp, road_side, selected_vastu)
    after = plan_metrics.evaluate(edited_fp, road_side, selected_vastu)
    delta = (after.fitness - before.fitness) * 100
    verdict = ("improved" if delta > 0.05
               else "lowered" if delta < -0.05 else "kept")
    st.markdown('<div class="section-header">Your Edited Plan β€” Finalised Score '
                f'({verdict} the fitness by {delta:+.1f})</div>',
                unsafe_allow_html=True)

    # Scores only β€” the weighting break-up follows underneath.
    rows = [{"Metric": label,
             "Domain Expert Engine": _pct(before.scores[key]),
             "Your Edit": _pct(after.scores[key]),
             "Ξ”": f"{(after.scores[key] - before.scores[key]) * 100:+.1f}"}
            for key, label in plan_metrics.METRIC_LABELS]
    rows.append({"Metric": "FLOOR PLAN FITNESS",
                 "Domain Expert Engine": _pct(before.fitness),
                 "Your Edit": _pct(after.fitness),
                 "Ξ”": f"{delta:+.1f}"})
    st.dataframe(pd.DataFrame(rows), hide_index=True, width="stretch")

    st.caption(
        f"Your edits **{verdict}** the fitness by **{delta:+.1f} points**. "
        "Walls and doors are visual only β€” moving, resizing or deleting rooms "
        "is what changes the score. The full per-metric working is below.")

    # The full per-metric break-up, recomputed on the EDITED plan: which Vastu
    # tier each room now reaches, which adjacency pairs survived, which
    # constraints still hold, plus the weighted fold under the Fitness tab.
    #
    # OPEN BY DEFAULT, unlike the generated plan's copy above. A flat
    # weight/score/contribution table used to sit here, but it was the
    # Evaluation Metrics table again with different numbers AND a duplicate of
    # this panel's own Fitness tab β€” so the page showed the same summary twice
    # while the per-metric working stayed folded behind a collapsed row that
    # nobody opened. The duplicate is gone and the working is what opens.
    render_evaluation(
        orig_fp, edited_fp, road_side, selected_vastu,
        left_label="Domain Expert Engine",
        right_label="Your Edit",
        expander_label="Break-up β€” the exact calculation on your edited plan",
        show_summary=False,
        expanded=True)


_WALL_OUTER, _WALL_INNER = 0.75, 0.40    # ft β€” same as the editor's walls


def _carpet_dims(r, rooms):
    """Carpet (inside-wall) dimensions: subtract half an inner wall (0.2') on
    each shared side and a full outer wall (0.75') on each exterior side β€”
    identical to the editor's carpet display."""
    tol, minov = 0.6, 1.0

    def neigh(side):
        for o in rooms:
            if o is r:
                continue
            yov = min(o.y + o.h, r.y + r.h) - max(o.y, r.y) >= minov
            xov = min(o.x + o.w, r.x + r.w) - max(o.x, r.x) >= minov
            if side == "L" and abs(o.x + o.w - r.x) < tol and yov:
                return True
            if side == "R" and abs(r.x + r.w - o.x) < tol and yov:
                return True
            if side == "B" and abs(o.y + o.h - r.y) < tol and xov:
                return True
            if side == "T" and abs(r.y + r.h - o.y) < tol and xov:
                return True
        return False

    allow = lambda side: (_WALL_INNER / 2 if neigh(side) else _WALL_OUTER)
    return (max(0.0, r.w - allow("L") - allow("R")),
            max(0.0, r.h - allow("B") - allow("T")))


def _carpet_map(fp):
    """{room name: carpet sqft} for one plan."""
    out, tot = {}, 0.0
    for r in fp.rooms:
        cw, ch = _carpet_dims(r, fp.rooms)
        a = cw * ch
        out[r.name] = out.get(r.name, 0.0) + a
        tot += a
    return out, tot


def render_carpet_area(fp, before_fp=None):
    """Each room's carpet area (usable area inside the walls). When `before_fp`
    is given the table gains BEFORE and AFTER columns so an edit can be read
    room by room. DISPLAY ONLY β€” never used in scoring."""
    after, ta = _carpet_map(fp)
    if before_fp is None:
        rows = [{"Room": pretty_room(n), "Carpet Area (sqft)": f"{a:.1f}"}
                for n, a in after.items()]
        rows.append({"Room": "TOTAL", "Carpet Area (sqft)": f"{ta:.1f}"})
        st.dataframe(pd.DataFrame(rows), hide_index=True, width="stretch")
        return
    before, tb = _carpet_map(before_fp)
    rows = []
    for n in list(before) + [k for k in after if k not in before]:
        b_, a_ = before.get(n), after.get(n)
        rows.append({
            "Room": pretty_room(n),
            "Before (sqft)": f"{b_:.1f}" if b_ is not None else "β€”",
            "After (sqft)": f"{a_:.1f}" if a_ is not None else "removed",
            "Change": (f"{a_ - b_:+.1f}" if b_ is not None and a_ is not None
                       else ("new" if b_ is None else "removed")),
        })
    rows.append({"Room": "TOTAL", "Before (sqft)": f"{tb:.1f}",
                 "After (sqft)": f"{ta:.1f}", "Change": f"{ta - tb:+.1f}"})
    st.dataframe(pd.DataFrame(rows), hide_index=True, width="stretch")
    st.caption(
        "Carpet area is the usable floor inside the walls β€” each side loses half "
        "an inner wall (0.2') where shared and a full outer wall (0.75') where "
        "it faces outside. Display only; scoring uses built-up areas.")


def render_evaluation(raw_fp, opt_fp, road_side, selected_vastu=None,
                      left_label="Layout Proposer",
                      right_label="Domain Expert Engine",
                      expander_label=None,
                      show_summary=True,
                      expanded=False):
    """The finalised scoring system: the nine-metric table (with the official
    weights) plus a click-to-expand EXACT calculation break-up per metric.

    The break-up is always computed on `opt_fp`, so the same function serves
    the generated plan AND the user's edited plan β€” call it a second time with
    (original, edited) and the per-room Vastu tiers, adjacency pairs,
    constraint results and size tables all reflect the edit. `show_summary`
    suppresses the top table where the caller has already drawn its own.
    Nothing inside is a keyed widget, so calling it twice is safe.
    """
    craw = plan_metrics.evaluate(raw_fp, road_side, selected_vastu)
    copt = plan_metrics.evaluate(opt_fp, road_side, selected_vastu)
    W = plan_metrics.DEFAULT_WEIGHTS

    # Fitness table: metric Β· weight Β· score Β· contribution to the fitness.
    if show_summary:
        rows = []
        for key, label in plan_metrics.METRIC_LABELS:
            w = W.get(key, 0.0)
            rows.append({
                "Metric": label,
                "Weight": f"{w:.2f}",
                "Score": _pct(copt.scores[key]),
                "Contribution": f"{copt.scores[key] * w * 100:.2f}",
            })
        rows.append({"Metric": "FLOOR PLAN FITNESS", "Weight": "1.00",
                     "Score": _pct(copt.fitness),
                     "Contribution": f"{copt.fitness * 100:.2f}"})
        st.dataframe(pd.DataFrame(rows), hide_index=True, width="stretch")
        st.caption(
            "Contribution = Score Γ— Weight, and the contributions sum to the "
            "fitness. All nine metrics now carry weight and the weights sum to "
            f"1.00. Expand any metric for its exact calculation on the "
            f"{right_label} plan.")

    with st.expander(expander_label or
                     "Break-up β€” the exact calculation behind every metric",
                     expanded=expanded):
        _tabs = st.tabs([f"{left_label} vs {right_label}", "Vastu", "Adjacency",
                         "Constraints", "Room Size", "Room Width",
                         "Aspect Ratio", "Zoning", "Connectivity",
                         "Space Util", "Fitness"])
    with _tabs[0]:
        cmp_rows = [{"Metric": label,
                     left_label: _pct(craw.scores[key]),
                     right_label: _pct(copt.scores[key]),
                     "Ξ”": f"{(copt.scores[key] - craw.scores[key]) * 100:+.1f}"}
                    for key, label in plan_metrics.METRIC_LABELS]
        cmp_rows.append({"Metric": "FLOOR PLAN FITNESS",
                         left_label: _pct(craw.fitness),
                         right_label: _pct(copt.fitness),
                         "Ξ”": f"{(copt.fitness - craw.fitness) * 100:+.1f}"})
        st.dataframe(pd.DataFrame(cmp_rows), hide_index=True, width="stretch")

    d = copt.details
    s = copt.scores

    _ZONE_FULL = {"NE": "North-East", "N": "North", "E": "East",
                  "SE": "South-East", "S": "South", "SW": "South-West",
                  "W": "West", "NW": "North-West", "Centre": "Centre"}

    # "none" = the room has no Vastu rule at all. Shown as a dash, because a
    # column full of the word "None" reads like a bug rather than a fact.
    _TIER_TXT = {"high": "High", "med": "Med", "low": "Low",
                 "ok": "Acceptable", "avoid": "Avoid", "none": "β€”"}
    _TIER_CNT = {"high": "+1.0", "med": "+0.5", "low": "+0.2",
                 "ok": "+0.1", "avoid": "βˆ’1.0", "none": "0"}

    with _tabs[1]:
        st.markdown(f"**Vastu Compliance β€” {_pct(s['vastu'])}**")
        vd = d["vastu"]
        st.markdown(
            "Each ruled room's occupied zone lands in a tier β€” "
            "**High +1 Β· Med +0.5 Β· Low +0.2 Β· Acceptable +0.1 Β· Avoid βˆ’1**. "
            "Two readings are shown below: the **plain compliance %** (rooms in "
            "any allowed zone Γ· total) and the **weighted %** (total counts Γ· "
            "the max if every room were High).")
        vt, total_credit = [], 0.0
        for r, z, t, c in vd["rows"]:
            total_credit += c
            ideal = plan_metrics.FINAL_VASTU.get(r, {}).get("high", ("β€”",))[0]
            # a room outside the rule set has no zone/tier β€” show a dash
            # rather than letting a bare None reach the table
            _dash = lambda v: "β€”" if v in (None, "") else v
            vt.append({
                "Room": pretty_room(r),
                "Ideal Zone": _dash(_ZONE_FULL.get(ideal, ideal)),
                "Current Zone": _dash(_ZONE_FULL.get(z, z)),
                "Tier": _dash(_TIER_TXT.get(t, t)),
                "Counts": _dash(_TIER_CNT.get(t, str(c) if c is not None else None))})
        vt.append({"Room": "TOTAL", "Ideal Zone": "", "Current Zone": "",
                   "Tier": "", "Counts": f"{total_credit:+g}"})
        st.dataframe(pd.DataFrame(vt), hide_index=True, width="stretch")
        n = vd["total"]
        weighted = max(0.0, min(1.0, total_credit / n)) if n else 1.0
        st.markdown(
            f"**Plain compliance = {vd['satisfied']} in an allowed zone Γ· "
            f"{n} ruled rooms = {_pct(s['vastu'])}**  \n"
            f"**Weighted Vastu (novelty) = total {total_credit:+g} Γ· {n} max "
            f"= {_pct(weighted)}**")

    with _tabs[2]:
        st.markdown(f"**Adjacency Achieved β€” {_pct(s['adjacency'])}**")
        ad = d["adjacency"]
        _atier = {1.0: "High", 0.5: "Med", 0.2: "Low"}
        st.markdown(
            "Each finalised room pair earns its tier value when the two rooms "
            "**share a wall** β€” **High +1 Β· Med +0.5 Β· Low +0.2**. Every "
            "**Avoid** pair that touches subtracts 1. "
            "**Total possible is the MAX SCORE**, not the pair count β€” a High "
            "pair is worth 1.0 but a Low pair only 0.2, so the pairs sum to "
            "less than their number. Score = (total counts βˆ’ avoid penalties) "
            "Γ· total possible.")
        # only the pairs that are actually present in the plan are judged
        arows = [{"Room Pairs": n, "Tier": _atier.get(w, str(w)),
                  "Status": "Shares wall" if ok else "Doesn't share wall",
                  "Counts": f"+{w:g}" if ok else "0"}
                 for n, w, ap, ok in ad["rows"] if ap]
        njudged = sum(1 for _n, _w, ap, _ok in ad["rows"] if ap)
        arows.append({"Room Pairs": "TOTAL", "Tier": "", "Status": "",
                      "Counts": f"+{ad['earned']:g}"})
        st.dataframe(pd.DataFrame(arows), hide_index=True, width="stretch")
        if any(ap for _n, ap, _h in ad["avoid_rows"]):
            st.markdown("**Avoid pairs (βˆ’1 each if the two touch):**")
            st.dataframe(pd.DataFrame(
                [{"Room Pairs": n,
                  "Status": "Touching" if hit else "Apart",
                  "Counts": "βˆ’1" if hit else "0"}
                 for n, ap, hit in ad["avoid_rows"] if ap]), hide_index=True,
                width="stretch")
        st.markdown(
            f"**Final = (counts {ad['earned']:g} βˆ’ avoid "
            f"{ad['penalties']:.0f}) Γ· {ad['possible']:g} max score "
            f"= {_pct(s['adjacency'])}**  \n"
            f"*{njudged} pairs judged Β· max score {ad['possible']:g} = their "
            f"tier values summed (High 1.0 Β· Med 0.5 Β· Low 0.2), not the pair "
            f"count.*")

    with _tabs[3]:
        st.markdown(f"**Constraint Validation Engine β€” {_pct(s['constraints'])}**")
        cd = d["constraints"]
        st.markdown(
            f"**{cd['hard_total']} hard constraints (+1 each)** plus two soft "
            "credits: +0.5 Γ— the Vastu fraction and +0.5 Γ— the Adjacency "
            f"fraction. Score = (passed + soft) Γ· {cd['total_possible']:.0f}.")
        crows = [{"Description": plan_metrics.CONSTRAINT_DESCRIPTIONS.get(k, k),
                  "Status": "Pass" if v else "Fail"}
                 for k, v in cd["hard"]]
        crows.append({"Description": "TOTAL passed",
                      "Status": f"{cd['passed']} / {cd['hard_total']}"})
        st.dataframe(pd.DataFrame(crows), hide_index=True, width="stretch")
        st.markdown(
            f"hard passed **{cd['passed']}/{cd['hard_total']}** Β· soft vastu "
            f"**+{cd['soft_vastu']}** Β· soft adjacency "
            f"**+{cd['soft_adjacency']}**\n\n"
            f"**Final = ({cd['passed']} + {cd['soft_vastu']} + "
            f"{cd['soft_adjacency']}) Γ· {cd['total_possible']:.0f} = "
            f"{_pct(s['constraints'])}**")

    with _tabs[4]:
        st.markdown(f"**Room Size Accuracy β€” {_pct(s['size_accuracy'])}**")
        sd = d["size_accuracy"]
        st.markdown(
            "**Required Area** = the room's share of the buildable area from "
            "the Proportions table (the size it SHOULD be). **Predicted Area** "
            "= its actual drawn size in this plan (width Γ— depth). "
            "**Deviation** = Predicted βˆ’ Required (signed: **+** over-sized, "
            "**βˆ’** under-sized). This is the standard **MAPE** "
            "(mean absolute percentage error): "
            "**Error % = |Deviation| Γ· Required Γ— 100**, and "
            "**Accuracy = 100 βˆ’ mean(Error %)**.")
        # metrics gives (name, plan_area, proportions_area, error%). Required =
        # the proportions area; Predicted = the plan area; Deviation = a βˆ’ p.
        st.dataframe(pd.DataFrame(
            [{"Room": pretty_room(n), "Required Area (sqft)": p,
              "Predicted Area (sqft)": a, "Deviation (sqft)": f"{a - p:+.1f}",
              "Error %": e}
             for n, a, p, e in sd["rooms"]]),
            hide_index=True, width="stretch")
        st.markdown(f"**Final = 100 βˆ’ mean error {sd['mean_error_pct']}% "
                    f"= {_pct(s['size_accuracy'])}**")

    with _tabs[5]:
        st.markdown(f"**Room Width Compliance β€” {_pct(s['room_width'])}**")
        rw = d["room_width"]
        st.markdown(
            "Each room's NARROW side must stay inside the Proportions width "
            "table (living 9-12 ft Β· bedroom 8-12 Β· master 10-16 Β· "
            "kitchen 7-10 Β· dining 5-8 Β· washroom 4-7 Β· utility 4-6 Β· "
            "pooja 3-5). Score = rooms within bounds Γ· rooms judged.")
        st.dataframe(pd.DataFrame(
            [{"Room": pretty_room(n), "Width as per plan (ft)": f"{sh}",
              "Min Req Width (ft)": f"{lo}", "Max Allowed (ft)": f"{hi}",
              "Count": "Satisfied" if ok == "yes" else "Not satisfied"}
             for n, sh, lo, hi, ok in rw["rows"]]),
            hide_index=True, width="stretch")
        st.markdown(f"**Final = {rw['ok']} satisfied Γ· {rw['judged']} judged "
                    f"= {_pct(s['room_width'])}**")

    with _tabs[6]:
        st.markdown(f"**Room Aspect Ratio β€” {_pct(s['aspect_ratio'])}**")
        ad2 = d["aspect_ratio"]
        st.markdown("Per room: clamp((2.5 βˆ’ aspect) Γ· 1.5) β€” 1:1 (a perfect "
                    "square) is ideal and scores 100%, β‰₯2.5:1 scores zero. "
                    "Metric = the mean (passages and balconies exempt).")
        arows = [{"Room": pretty_room(n), "Aspect": a, "Score": _pct(sc)}
                 for n, a, sc in ad2["rows"]]
        st.dataframe(pd.DataFrame(arows), hide_index=True, width="stretch")
        if arows:
            st.markdown(
                f"**Final = mean of {len(arows)} room scores = "
                f"{_pct(s['aspect_ratio'])}**")

    with _tabs[7]:
        st.markdown(f"**Functional Zoning β€” {_pct(s['zoning'])}**")
        zd = d["zoning"]
        c1, c2 = zd.get("cuts", (0.40, 0.55))
        st.markdown(
            "Distance = staircase centroid β†’ room centroid, **normalised** by "
            "the farthest staircase-to-corner distance (**0** at the entry, "
            "**1** at the deepest corner) so it is plot-size independent. "
            f"Bands: **Common ≀ {c1} Β· Transitional ≀ {c2} Β· Private > {c2}**. "
            "Ideal: Common areas near the entry, Private deepest. A room is "
            "**Satisfied** when it lands in its ideal band or an adjacent one. "
            "Score = satisfied Γ· total rooms.")
        if "rows" in zd:
            st.dataframe(pd.DataFrame(
                [{"Room": pretty_room(n), "Ideal Zone": ib.title(),
                  "Distance from Entry (ft)": dist, "Normalised (0–1)": nm,
                  "Current Zone": ab.title(),
                  "Count": "Satisfied" if ok else "Not satisfied"}
                 for n, ib, dist, nm, ab, ok in zd["rows"]]),
                hide_index=True, width="stretch")
            st.markdown(f"**Final = {zd['satisfied']} satisfied Γ· "
                        f"{zd['total']} rooms = {_pct(s['zoning'])}**  \n"
                        f"*The staircase is not in the count β€” it is the entry "
                        f"every distance is measured FROM, so its own distance "
                        f"from itself is meaningless. Every other room in the "
                        f"plan is judged.*")

    with _tabs[8]:
        st.markdown(f"**Connectivity β€” {_pct(s['connectivity'])}**")
        cn = d["connectivity"]
        st.markdown(
            "Access is **directional**: a route may only be walked in the "
            "direction a room is legitimately entered from. So the passage "
            "gives access to a bedroom, but a bedroom does **not** give access "
            "to the passage β€” you cannot reach the passage (and everything "
            "hanging off it) by crossing somebody's bedroom. Each room's "
            "permitted entry rooms:")
        st.dataframe(pd.DataFrame([
            {"Room": "Living Β· Passage", "May be entered from":
             "Staircase (entry), Living, Dining, Passage"},
            {"Room": "Dining", "May be entered from":
             "Staircase (entry), Living, Dining, Passage, Kitchen"},
            {"Room": "Kitchen Β· Bedrooms Β· Common bath Β· Study",
             "May be entered from": "Living, Dining, Passage"},
            {"Room": "Utility", "May be entered from":
             "Living, Dining, Passage, Kitchen"},
            {"Room": "Pooja", "May be entered from":
             "Living, Dining, Passage, Kitchen"},
            {"Room": "Balcony", "May be entered from":
             "Living, Dining, Passage, any Bedroom"},
            {"Room": "Attached bath", "May be entered from":
             "Its own bedroom only"},
        ]), hide_index=True, width="stretch")
        st.markdown(
            "Rooms are then reached by walking those directed doorways out from "
            "the entry (staircase). Score = reachable Γ· total rooms.")
        if cn.get("nodes"):
            fig_cg = fig_connectivity_graph(cn["nodes"], cn["edges"],
                                            cn.get("blocked_edges", ()))
            gcol, _gpad = st.columns([1, 1.6])  # keep the graph small
            gcol.pyplot(fig_cg)
            import matplotlib.pyplot as _plt
            _plt.close(fig_cg)
            iso = cn["unreachable"]
            st.markdown(
                "**βœ… All rooms are reachable from the entry.**" if not iso else
                "**⚠ Not fully connected β€” isolated: " +
                ", ".join(pretty_room(x) for x in iso) + "**")
        unreach = set(cn["unreachable"])
        st.dataframe(pd.DataFrame(
            [{"Room": pretty_room(r.name),
              "Reachable from entry": "No" if r.name in unreach else "Yes"}
             for r in opt_fp.rooms]), hide_index=True, width="stretch")
        st.markdown(f"**Final = {cn['reachable']} reachable Γ· {cn['total']} "
                    f"rooms = {_pct(s['connectivity'])}**")

    with _tabs[9]:
        st.markdown(f"**Space Utilization β€” {_pct(s['space_utilization'])}**")
        su = d["space_utilization"]
        st.markdown(
            f"Fraction of the buildable (setback) area covered by rooms β€” "
            f"overlaps counted once, a gapless tiling scores 100%.\n\n"
            f"**Final = {su['covered_sqft']} covered Γ· {su['buildable_sqft']} "
            f"buildable sqft = {_pct(s['space_utilization'])}**")

    with _tabs[10]:
        st.markdown(f"**Floor Plan Fitness β€” {_pct(copt.fitness)} (weighted fold)**")
        fd = d["fitness"]
        st.dataframe(pd.DataFrame(
            [{"Metric": k, "Score": _pct(sc), "Weight": f"{w:.2f}",
              "Contribution": f"{c * 100:.2f}"}
             for k, sc, w, c in fd["contributions"]]),
            hide_index=True, width="stretch")
        st.markdown(f"**SUM Γ· {fd['weight_sum']} = {_pct(copt.fitness)}**")


def floorplan_to_dxf(fp, road_side="S", openings=None, walls=None):
    """Hand-written ASCII DXF using only R12-safe entities.

    Room outlines used to be written as LWPOLYLINE, but LWPOLYLINE is an R14+
    entity and the file declared no version, so AutoCAD read it as R12 and
    silently dropped every outline β€” the export opened showing the labels only.
    Everything is now emitted as LINE + TEXT, which every DXF version supports,
    and the header states $ACADVER explicitly."""
    def esc(text):
        return str(text).replace("\n", " ").replace("\r", " ")

    def _ft_in(v):
        """Feet as the feet-inches string a drawing is normally annotated in."""
        ft = int(v)
        inch = int(round((v - ft) * 12))
        if inch == 12:
            ft, inch = ft + 1, 0
        return f"{ft}'-{inch}\"" if inch else f"{ft}'"

    lines = [
        "0", "SECTION", "2", "HEADER",
        "9", "$ACADVER", "1", "AC1009",
        "9", "$INSBASE", "10", "0.0", "20", "0.0", "30", "0.0",
        # extents include the title block below and the north arrow to the right
        "9", "$EXTMIN", "10", "-2.0", "20", "-15.0", "30", "0.0",
        "9", "$EXTMAX", "10", f"{fp.plot_w + 10.0:.3f}",
        "20", f"{fp.plot_h + 2.0:.3f}", "30", "0.0",
        "0", "ENDSEC",
        "0", "SECTION", "2", "TABLES",
        "0", "TABLE", "2", "LAYER", "70", "8",
        "0", "LAYER", "2", "PLOT", "70", "0", "62", "7", "6", "CONTINUOUS",
        "0", "LAYER", "2", "SETBACK", "70", "0", "62", "1", "6", "DASHED",
        "0", "LAYER", "2", "ROOMS", "70", "0", "62", "5", "6", "CONTINUOUS",
        "0", "LAYER", "2", "WALLS", "70", "0", "62", "8", "6", "CONTINUOUS",
        "0", "LAYER", "2", "DOORS", "70", "0", "62", "3", "6", "CONTINUOUS",
        "0", "LAYER", "2", "WINDOWS", "70", "0", "62", "4", "6", "CONTINUOUS",
        "0", "LAYER", "2", "TEXT", "70", "0", "62", "7", "6", "CONTINUOUS",
        "0", "LAYER", "2", "TITLE", "70", "0", "62", "7", "6", "CONTINUOUS",
        "0", "ENDTAB", "0", "ENDSEC",
        "0", "SECTION", "2", "ENTITIES",
    ]

    def line(layer, x1, y1, x2, y2):
        lines.extend([
            "0", "LINE", "8", layer,
            "10", f"{x1:.3f}", "20", f"{y1:.3f}", "30", "0.0",
            "11", f"{x2:.3f}", "21", f"{y2:.3f}", "31", "0.0",
        ])

    def rect(layer, x, y, w, h):
        line(layer, x, y, x + w, y)
        line(layer, x + w, y, x + w, y + h)
        line(layer, x + w, y + h, x, y + h)
        line(layer, x, y + h, x, y)

    def text(layer, x, y, height, value):
        # 72/73 = centred both ways, so 11/21 is the alignment point
        lines.extend([
            "0", "TEXT", "8", layer,
            "10", f"{x:.3f}", "20", f"{y:.3f}", "30", "0.0",
            "40", f"{height:.3f}", "1", esc(value),
            "72", "1", "73", "2",
            "11", f"{x:.3f}", "21", f"{y:.3f}", "31", "0.0",
        ])

    def text_left(layer, x, y, height, value):
        """Left-aligned text (72=0/73=0 uses the 10/20 point as the baseline)."""
        lines.extend([
            "0", "TEXT", "8", layer,
            "10", f"{x:.3f}", "20", f"{y:.3f}", "30", "0.0",
            "40", f"{height:.3f}", "1", esc(value),
            "72", "0", "73", "0",
            "11", f"{x:.3f}", "21", f"{y:.3f}", "31", "0.0",
        ])

    def arc(layer, cx, cy, r, a1, a2):
        lines.extend([
            "0", "ARC", "8", layer,
            "10", f"{cx:.3f}", "20", f"{cy:.3f}", "30", "0.0",
            "40", f"{r:.3f}", "50", f"{a1:.1f}", "51", f"{a2:.1f}",
        ])

    rect("PLOT", 0, 0, fp.plot_w, fp.plot_h)
    sb_road, sb_other = 6.56, 3.28
    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
    rect("SETBACK", left, bottom, fp.plot_w - left - right, fp.plot_h - bottom - top)
    # Room labels are sized to FIT INSIDE their room. A DXF character is about
    # 0.6 x the text height wide, so a 14-character name at the old 2 ft height
    # was ~17 ft wide β€” wider than the room, which is why labels came out huge.
    CHAR_W = 0.62          # width of one character, as a fraction of height
    MIN_H = 0.30           # below this a label is unreadable, so it is dropped

    def fitted_height(s, room_w, room_h, cap=0.65):
        """Largest text height that keeps `s` inside the room."""
        if not s:
            return 0.0
        return min(cap,
                   (room_w * 0.86) / (len(s) * CHAR_W),
                   room_h * 0.16)

    for room in fp.rooms:
        rect("ROOMS", room.x, room.y, room.w, room.h)
        name = pretty_room(room.name).upper()      # architectural convention
        dims = f"{_ft_in(room.w)} x {_ft_in(room.h)}"
        area = f"{room.w * room.h:.0f} SQ.FT."
        # one height for the whole block so the lines read evenly
        h = min(fitted_height(name, room.w, room.h),
                fitted_height(dims, room.w, room.h))
        if h < MIN_H:
            # too tight for the full block β€” try the name alone, else skip
            h = fitted_height(name, room.w, room.h)
            if h >= MIN_H:
                text("TEXT", room.cx, room.cy, h, name)
            continue
        show_area = room.h > h * 7 and fitted_height(area, room.w, room.h) >= MIN_H
        if show_area:
            text("TEXT", room.cx, room.cy + h * 1.5, h, name)
            text("TEXT", room.cx, room.cy, h * 0.85, dims)
            text("TEXT", room.cx, room.cy - h * 1.4, h * 0.75, area)
        else:
            text("TEXT", room.cx, room.cy + h * 0.8, h, name)
            text("TEXT", room.cx, room.cy - h * 0.8, h * 0.85, dims)

    # ── WALLS: the second face of every wall, so it reads as a thickness ──
    if walls:
        t_out = float(walls.get("outer", _WALL_OUTER))
        t_in = float(walls.get("inner", _WALL_INNER))
        tol, minov = 0.6, 1.0
        rs = fp.rooms
        if rs:
            x0 = min(r.x for r in rs); y0 = min(r.y for r in rs)
            x1 = max(r.x + r.w for r in rs); y1 = max(r.y + r.h for r in rs)
            rect("WALLS", x0, y0, x1 - x0, y1 - y0)
            rect("WALLS", x0 + t_out, y0 + t_out,
                 (x1 - x0) - 2 * t_out, (y1 - y0) - 2 * t_out)
        for i in range(len(rs)):
            for j in range(i + 1, len(rs)):
                a, b = rs[i], rs[j]
                if abs(a.x + a.w - b.x) < tol or abs(b.x + b.w - a.x) < tol:
                    lo, hi = max(a.y, b.y), min(a.y + a.h, b.y + b.h)
                    if hi - lo >= minov:
                        xb = a.x + a.w if abs(a.x + a.w - b.x) < tol else b.x + b.w
                        line("WALLS", xb - t_in / 2, lo, xb - t_in / 2, hi)
                        line("WALLS", xb + t_in / 2, lo, xb + t_in / 2, hi)
                if abs(a.y + a.h - b.y) < tol or abs(b.y + b.h - a.y) < tol:
                    lo, hi = max(a.x, b.x), min(a.x + a.w, b.x + b.w)
                    if hi - lo >= minov:
                        yb = a.y + a.h if abs(a.y + a.h - b.y) < tol else b.y + b.h
                        line("WALLS", lo, yb - t_in / 2, hi, yb - t_in / 2)
                        line("WALLS", lo, yb + t_in / 2, hi, yb + t_in / 2)

    # ── DOORS and WINDOWS at the positions set in the editor ──
    by_name = {r.name: r for r in fp.rooms}
    for op in (openings or []):
        r = by_name.get(op.get("room"))
        if r is None:
            continue
        side, ow = op.get("side"), float(op.get("w", 3.0))
        vert = side in ("L", "R")
        span = r.h if vert else r.w
        ow = max(0.8, min(ow, span))
        t = max(ow / 2, min(float(op.get("t", span / 2)), span - ow / 2))
        at = (r.x if side == "L" else r.x + r.w if side == "R"
              else r.y if side == "B" else r.y + r.h)
        base = r.y if vert else r.x
        lo, hi = base + t - ow / 2, base + t + ow / 2
        if op.get("kind") == "window":
            # two parallel lines across the opening = a window in plan
            if vert:
                line("WINDOWS", at - 0.1, lo, at - 0.1, hi)
                line("WINDOWS", at + 0.1, lo, at + 0.1, hi)
            else:
                line("WINDOWS", lo, at - 0.1, hi, at - 0.1)
                line("WINDOWS", lo, at + 0.1, hi, at + 0.1)
        else:
            # leaf + quarter-circle swing, opening into the room
            if vert:
                inward = 1.0 if (r.x + r.w / 2) > at else -1.0
                line("DOORS", at, lo, at + inward * ow, lo)
                arc("DOORS", at, lo, ow, 0.0, 90.0) if inward > 0 else \
                    arc("DOORS", at, lo, ow, 90.0, 180.0)
            else:
                inward = 1.0 if (r.y + r.h / 2) > at else -1.0
                line("DOORS", lo, at, lo, at + inward * ow)
                arc("DOORS", lo, at, ow, 0.0, 90.0) if inward > 0 else \
                    arc("DOORS", lo, at, ow, 270.0, 360.0)

    # ── North arrow, to the right of the plot so it never sits over a room ──
    nx, ny = fp.plot_w + 6.0, fp.plot_h - 10.0
    line("TITLE", nx, ny, nx, ny + 7.0)
    line("TITLE", nx, ny + 7.0, nx - 1.1, ny + 4.8)
    line("TITLE", nx, ny + 7.0, nx + 1.1, ny + 4.8)
    text("TITLE", nx, ny + 8.8, 1.1, "N")

    # ── Title block under the plot ──
    built = sum(r.w * r.h for r in fp.rooms)
    tb_y1, tb_h = -2.0, 11.0
    tb_y0 = tb_y1 - tb_h
    rect("TITLE", 0.0, tb_y0, fp.plot_w, tb_h)
    line("TITLE", 0.0, tb_y1 - 3.4, fp.plot_w, tb_y1 - 3.4)   # header rule
    text_left("TITLE", 0.9, tb_y1 - 2.5, 1.25, "VASTU FLOOR PLAN")
    rows = [
        ("PLOT SIZE", f"{_ft_in(fp.plot_w)} x {_ft_in(fp.plot_h)}"),
        ("ROAD FACING", {"S": "SOUTH", "N": "NORTH",
                         "E": "EAST", "W": "WEST"}.get(road_side, road_side)),
        ("BUILT-UP AREA", f"{built:.0f} SQ.FT."),
        ("ROOMS", str(len(fp.rooms))),
    ]
    col_w = fp.plot_w / max(len(rows), 1)
    for i, (k, v) in enumerate(rows):
        x = 0.9 + i * col_w
        text_left("TITLE", x, tb_y1 - 5.4, 0.62, k)
        text_left("TITLE", x, tb_y1 - 7.4, 0.85, v)
    text_left("TITLE", 0.9, tb_y0 + 1.0, 0.5,
              "ALL DIMENSIONS IN FEET-INCHES.  LAYERS: PLOT / SETBACK / ROOMS / "
              "WALLS / DOORS / WINDOWS / TEXT / TITLE")

    lines.extend(["0", "ENDSEC", "0", "EOF"])
    return "\n".join(lines).encode("ascii", errors="ignore")


def clone_floorplan(fp):
    rooms = [Room(r.name, r.x, r.y, r.w, r.h) for r in fp.rooms]
    cloned = FloorPlan(rooms, fp.plot_w, fp.plot_h)
    cloned.scores = dict(getattr(fp, "scores", {}))
    cloned.template_name = getattr(fp, "template_name", "manual_adjusted")
    return cloned


def score_adjusted_plan(fp, selected_vastu, w_vs, w_aq, w_cs, w_su, w_ac, w_lc):
    weights = (w_aq, w_vs, w_su, w_ac, w_cs, w_lc)
    _score_one(fp, selected_vastu, weights)
    return fp



st.markdown(
    """
<div class="main-header">
    <h1>Architectural Floor Plan Generation System</h1>
    <p>Hybrid AI-Assisted Decision Support for Residential Layout Planning</p>
</div>
""",
    unsafe_allow_html=True,
)


with st.sidebar:
    st.markdown("## Configuration")
    st.markdown("---")

    st.markdown("### Plot")
    c1, c2 = st.columns(2)
    with c1:
        plot_w = st.number_input("Width (ft)", min_value=20, max_value=100, value=40, step=5)
    with c2:
        plot_h = st.number_input("Depth (ft)", min_value=20, max_value=100, value=60, step=5)

    road_side = st.selectbox(
        "Road-facing side",
        options=["S", "N", "E", "W"],
        index=0,
        format_func={"S": "South", "N": "North", "E": "East", "W": "West"}.get,
    )

    plan_type = st.radio(
        "Plan type",
        options=["1BHK", "2BHK", "3BHK", "4BHK"],
        index=0,
        horizontal=True,
    )
    # switching plan type clears stale plans of the other type
    if st.session_state.get("last_plan_type") not in (None, plan_type):
        st.session_state.pop("last_top_plans", None)
    st.session_state["last_plan_type"] = plan_type

    st.markdown("")
    generate_btn = st.button("Generate Floor Plans", width="stretch",
                             type="primary")

    # ── Fixed defaults (no longer shown as controls) ─────────────────────────
    # Rooms are decided by the plan type; the shown plans are re-ranked by the
    # finalised nine-metric fitness, so the generation weights are just defaults.
    core_required = {
        "external_staircase": True, "living_room": True, "kitchen": True,
        "dining_room": True, "utility_area": True, "common_bathroom": True,
        "master_bedroom": True,
        "attached_bathroom": plan_type in {"2BHK", "3BHK", "4BHK"},
    }
    required_rooms = [r for r, on in core_required.items() if on]
    opt_defaults = {
        "bedroom_01": plan_type in {"2BHK", "3BHK", "4BHK"},
        "bedroom_02": plan_type in {"3BHK", "4BHK"},
        "bedroom_03": plan_type == "4BHK",
        "balcony": True, "pooja_room": True,
    }
    optional_rooms = [r for r, on in opt_defaults.items() if on]
    required_rooms, optional_rooms = enforce_bhk_rooms(
        plan_type, required_rooms, optional_rooms)
    room_names = required_rooms + optional_rooms
    selected_vastu = [rule[0] for rule in VASTU_RULES]
    w_vs, w_aq, w_cs, w_su, w_ac, w_lc = 0.30, 0.25, 0.15, 0.15, 0.10, 0.05


if generate_btn:
    progress_bar = st.progress(0, text="Initialising generation pipeline...")
    status = st.empty()

    with st.spinner(""):
        status.markdown("**Stage I β€” Cognitive Intelligence** Β· Layout Proposer predicts the conceptual layout")
        progress_bar.progress(20, text="Layout Proposer: Graph VAE predicting candidate topologies...")
        time.sleep(0.2)

        status.markdown("**Step 2/4** - AI engine designs the layouts")
        progress_bar.progress(45, text="AI engine: designing layouts...")
        plan_count = int(os.getenv("PLAN_COUNT", "20"))
        # The GPT-first BHK pipeline is the PRIMARY path: it designs all the
        # plans with the GPT engine and only uses its own PDF templates when
        # no API key is available. generate_population (ml/rule backends) is
        # kept strictly as an emergency fallback.
        _bhk_generator = {
            "2BHK": pdf_templates_2bhk.generate_bhk2_pdf_population,
            "3BHK": pdf_templates_3bhk.generate_bhk3_pdf_population,
            "4BHK": pdf_templates_4bhk.generate_bhk4_pdf_population,
        }.get(plan_type, pdf_templates.generate_bhk1_pdf_population)
        bhk_selected_optional = list(optional_rooms)
        if plan_type == "2BHK" and "attached_bathroom" in required_rooms:
            bhk_selected_optional.append("attached_bathroom")
        try:
            plan_pairs = _bhk_generator(
                plot_w=plot_w, plot_h=plot_h,
                selected_optional=bhk_selected_optional, road_side=road_side,
                n=plan_count)
        except Exception as exc:
            print(f"[app] {plan_type} pipeline failed: {exc}")
            plan_pairs = []
        if not plan_pairs:
            st.warning("BHK pipeline returned no plans; using emergency backend generator.")
            plan_pairs = generate_population(
                room_names,
                plot_w,
                plot_h,
                n=plan_count,
                required_rooms=required_rooms,
                optional_rooms=optional_rooms,
                road_side=road_side,
            )
        time.sleep(0.2)

        status.markdown("**Stage II β€” Design Synthesis** Β· Domain Expert Engine constructs and validates the layouts")
        progress_bar.progress(75, text="Domain Expert Engine: conditioned geometry construction...")
        ranked = rank_plans(
            plan_pairs,
            selected_vastu,
            w_vs=w_vs,
            w_aq=w_aq,
            w_cs=w_cs,
            w_su=w_su,
            w_ac=w_ac,
            w_lc=w_lc,
            road_side=road_side,
            regenerate_peak=False,
        )
        top_plans = ranked[:plan_count]
        # RANK BY THE FINALISED FITNESS so Plan 1 is genuinely the best plan
        # under the same scoring system every panel displays (rank_plans uses
        # the legacy objective, which would disagree with the shown numbers).
        top_plans.sort(
            key=lambda p: -plan_metrics.evaluate(
                p.get("peak", p["optimised"]), road_side,
                selected_vastu).fitness)
        st.session_state["last_top_plans"] = top_plans
        st.session_state["last_road_side"] = road_side

        status.markdown("**Stage III β€” Decision Support** Β· Multi-Criteria Evaluation Engine scores and ranks")
        progress_bar.progress(100, text="Complete")
        time.sleep(0.2)

    progress_bar.empty()
    status.empty()

else:
    top_plans = st.session_state.get("last_top_plans")
    if top_plans:
        road_side = st.session_state.get("last_road_side", road_side)


if top_plans:

    best_opt = top_plans[0].get("peak", top_plans[0]["optimised"])
    _engine_name = str(getattr(best_opt, "template_name", "") or "")
    if "_ai_" not in _engine_name and "_bb_" not in _engine_name:
        st.warning("These plans came from the legacy emergency backend. "
                   "Check the setup and click Generate again.")

    # ── Average of ALL nine metrics across every generated plan ──────────────
    _cards = [plan_metrics.evaluate(p.get("peak", p["optimised"]), road_side,
                                    selected_vastu) for p in top_plans]
    _n = len(_cards) or 1
    _avg_fit = sum(c.fitness for c in _cards) / _n
    _avg = {k: sum(c.scores[k] for c in _cards) / _n
            for k, _lab in plan_metrics.METRIC_LABELS}
    st.markdown(f'<div class="section-header">All {_n} Plans β€” Average Scores'
                '</div>', unsafe_allow_html=True)
    tiles = [("Fitness", _avg_fit)] + [
        (lab, _avg[k]) for k, lab in plan_metrics.METRIC_LABELS]
    per_row = 6
    for start in range(0, len(tiles), per_row):
        cols = st.columns(per_row)
        for c, (lab, val) in enumerate(tiles[start:start + per_row]):
            cols[c].metric(lab, f"{val * 100:.0f}%")
    st.caption("Each score meaned over all generated plans. Click a plan below "
               "for its own full break-up.")

    # Room-colour legend goes in the sidebar's empty space, so it sits on the
    # LEFT alongside the whole gallery rather than beside one plan.
    with st.sidebar:
        st.markdown("---")
        render_side_legend(top_plans[0].get("peak", top_plans[0]["optimised"]))

    # ── Plan gallery: all plans at once, click a tile to open it ──────────────
    st.markdown('<div class="section-header">Choose a Plan '
                f'({len(top_plans)} generated Β· click any to open)</div>',
                unsafe_allow_html=True)
    selected_idx = min(st.session_state.get("selected_plan_idx", 0),
                       len(top_plans) - 1)
    GALLERY_COLS = 5
    for row_start in range(0, len(top_plans), GALLERY_COLS):
        cols = st.columns(GALLERY_COLS)
        for c, idx in enumerate(
                range(row_start, min(row_start + GALLERY_COLS, len(top_plans)))):
            with cols[c]:
                fp_i = top_plans[idx].get("peak", top_plans[idx]["optimised"])
                sel = (idx == selected_idx)
                st.markdown(f'<div class="plan-tile '
                            f'{"plan-tile-sel" if sel else ""}">',
                            unsafe_allow_html=True)
                st.image(plan_thumbnail(fp_i, road_side),
                         width="stretch")
                st.markdown('</div>', unsafe_allow_html=True)
                fit = _cards[idx].fitness * 100
                if st.button(f"{'βœ“ ' if sel else ''}Plan {idx + 1} Β· {fit:.0f}%",
                             key=f"pick_{idx}", width="stretch",
                             type="primary" if sel else "secondary"):
                    st.session_state["selected_plan_idx"] = idx
                    st.rerun()

    # Ranked comparison of every plan, directly under the gallery it describes.
    st.markdown('<div class="section-header">Ranked Comparison β€” All Plans'
                '</div>', unsafe_allow_html=True)
    # _cards[idx] is the finalised evaluation of top_plans[idx]'s optimised
    # plan, already computed for the average panel β€” reuse it here.
    rows = []
    for idx, (pair_i, co) in enumerate(zip(top_plans, _cards)):
        cr = plan_metrics.evaluate(pair_i["raw"], road_side, selected_vastu)
        rows.append({
            "Plan": f"Plan {idx + 1}",
            "Layout Proposer": f"{cr.fitness * 100:.1f}%",
            "Domain Expert Engine": f"{co.fitness * 100:.1f}%",
            "Gain": f"{(co.fitness - cr.fitness) * 100:+.1f}%",
            "Vastu": f"{co.scores['vastu'] * 100:.0f}%",
            "Adjacency": f"{co.scores['adjacency'] * 100:.0f}%",
            "Constraints": f"{co.scores['constraints'] * 100:.0f}%",
            "Aspect": f"{co.scores['aspect_ratio'] * 100:.0f}%",
            "Room Size": f"{co.scores['size_accuracy'] * 100:.0f}%",
            "Space Util": f"{co.scores['space_utilization'] * 100:.0f}%",
        })
    st.dataframe(pd.DataFrame(rows), hide_index=True, width="stretch")

    st.markdown(f'<div class="section-header">Plan {selected_idx + 1} β€” '
                'Layout Proposer vs Domain Expert Engine</div>', unsafe_allow_html=True)
    pair = top_plans[selected_idx]
    raw_fp = pair["raw"]
    opt_fp = pair.get("peak", pair["optimised"])
    comparison_fig = fig_comparison(
        raw_fp, opt_fp,
        rank=selected_idx + 1,
        road_side=road_side,
        left_title="Layout Proposer Generated",
        right_title="Expert Engine Generated",
    )
    comparison_png = fig_to_bytes(comparison_fig).getvalue()

    # Scores + legend as a vertical column on the LEFT, the plans on the RIGHT.
    side, main = st.columns([1, 3.6])
    with side:
        render_side_scores(raw_fp, opt_fp, road_side, selected_vastu)
    with main:
        st.image(comparison_png, width="stretch")

    st.markdown('<div class="section-header">Multi-Criteria Evaluation Engine'
                '</div>', unsafe_allow_html=True)
    render_evaluation(raw_fp, opt_fp, road_side, selected_vastu)

    st.markdown('<div class="section-header">User Interactive Editor Module'
                '</div>', unsafe_allow_html=True)

    editor_result = floor_plan_editor(
        rooms=opt_fp.rooms,
        plot_w=opt_fp.plot_w,
        plot_h=opt_fp.plot_h,
        road_side=road_side,
        key=f"editor_{selected_idx}",
    )

    # The editor returns the edited room list. Keep the ORIGINAL optimised plan
    # intact (so we can compare) and stash the edit in session state so it
    # survives Streamlit reruns; then score it against the original below.
    edited_key = f"edited_fp_{selected_idx}"
    if editor_result:
        st.session_state[edited_key] = editor_result

    edited_result = st.session_state.get(edited_key)
    if edited_result:
        # the editor sends {rooms, openings, walls}; older payloads were a bare
        # room list, so accept both
        if isinstance(edited_result, dict):
            ed_rooms = edited_result.get("rooms", [])
            ed_openings = edited_result.get("openings", [])
            ed_walls = edited_result.get("walls", {})
        else:
            ed_rooms, ed_openings, ed_walls = edited_result, [], {}
        edited_fp = FloorPlan(
            [Room(r["name"], r["x"], r["y"], r["w"], r["h"])
             for r in ed_rooms],
            opt_fp.plot_w, opt_fp.plot_h)
        st.session_state[f"edited_fp_obj_{selected_idx}"] = (
            edited_fp, ed_openings, ed_walls)

        # Domain Expert Engine plan and YOUR edited plan, side by side.
        st.markdown('<div class="section-header">Original vs Your Edited Plan'
                    '</div>', unsafe_allow_html=True)
        import matplotlib.pyplot as _plt_ed
        o_fig = fig_floorplan(opt_fp, opt_fp.plot_w, opt_fp.plot_h, road_side,
                              "Domain Expert Engine (original)")
        o_png = fig_to_bytes(o_fig).getvalue()
        _plt_ed.close(o_fig)
        ed_fig = fig_floorplan(edited_fp, edited_fp.plot_w, edited_fp.plot_h,
                               road_side, "Your Edited Plan")
        ed_png = fig_to_bytes(ed_fig).getvalue()
        _plt_ed.close(ed_fig)
        # Kept to two thirds of the row so the pair reads at a comfortable size
        # rather than filling the page β€” these are a comparison, not the
        # working drawing.
        pv1, pv2, _pv_pad = st.columns([1, 1, 1])
        pv1.image(o_png, width="stretch")
        pv2.image(ed_png, width="stretch")

        render_edit_comparison(opt_fp, edited_fp, road_side, selected_vastu)

        st.markdown('<div class="section-header">Carpet Area β€” Your Edited Plan'
                    '</div>', unsafe_allow_html=True)
        render_carpet_area(edited_fp, before_fp=opt_fp)

    # Carpet area of the plan as generated β€” only when nothing has been edited
    # (the edited plan shows its own carpet table up in the editor section).
    _edit = st.session_state.get(f"edited_fp_obj_{selected_idx}")
    if not _edit:
        st.markdown('<div class="section-header">Carpet Area</div>',
                    unsafe_allow_html=True)
        render_carpet_area(opt_fp)

    # ── Everything downloadable, at the very end ─────────────────────────────
    st.markdown('<div class="section-header">Downloads</div>',
                unsafe_allow_html=True)
    dxf_fp, dxf_openings, dxf_walls = (_edit if _edit else (opt_fp, [], {}))
    dcols = st.columns(4 if _edit else 2)
    dcols[0].download_button(
        "Plan PNG",
        data=comparison_png,
        file_name=f"{plan_type.lower()}_plan_{selected_idx + 1}.png",
        mime="image/png", key=f"png_download_{selected_idx}", width="stretch")
    dcols[1].download_button(
        "Plan DXF (AutoCAD)",
        data=floorplan_to_dxf(opt_fp, road_side),
        file_name=f"{plan_type.lower()}_plan_{selected_idx + 1}.dxf",
        mime="application/dxf", key=f"dxf_download_{selected_idx}",
        width="stretch")
    if _edit:
        dcols[2].download_button(
            "Edited plan PNG",
            data=ed_png,
            file_name=f"{plan_type.lower()}_plan_{selected_idx + 1}_edited.png",
            mime="image/png", key=f"png_edit_{selected_idx}", width="stretch")
        dcols[3].download_button(
            "Edited plan DXF",
            data=floorplan_to_dxf(dxf_fp, road_side, dxf_openings, dxf_walls),
            file_name=f"{plan_type.lower()}_plan_{selected_idx + 1}_edited.dxf",
            mime="application/dxf", key=f"dxf_edit_{selected_idx}",
            width="stretch")
    st.caption(
        "DXF layers: PLOT Β· SETBACK Β· ROOMS Β· WALLS Β· DOORS Β· WINDOWS Β· TEXT Β· "
        "TITLE. The edited DXF carries your rooms, walls, doors and windows. "
        "DWG is AutoCAD's proprietary format β€” open the DXF and **Save As β†’ "
        ".dwg** if a DWG is needed.")

else:
    st.markdown(
        """
        <div style="text-align:center; padding: 3rem 2rem; color: #8B949E;">
            <h3 style="color:#1F4E79;">Configure the Design Requirements</h3>
            <p>Specify the design requirements to generate and compare multiple layout alternatives.</p>
        </div>
        """,
        unsafe_allow_html=True,
    )

    st.markdown('<div class="section-header">System Workflow</div>', unsafe_allow_html=True)
    c1, c2, c3, c4 = st.columns(4)
    cards = [
        (c1, "Stage I β€” Cognitive Intelligence",
         "Learns user requirements and predicts the conceptual layout. "
         "<i>Layout Proposer β€” Graph VAE + Geometry Constructor.</i>"),
        (c2, "Stage II β€” Design Synthesis",
         "Generates and validates multiple candidate layouts. "
         "<i>Domain Expert Engine with Conditioned Geometry Constructor, "
         "checked by the Constraint Validation Engine.</i>"),
        (c3, "Stage III β€” Decision Support",
         "Evaluates, ranks and β€” after editing β€” re-evaluates the layouts to "
         "help choose the best alternative. "
         "<i>Multi-Criteria Evaluation Engine.</i>"),
        (c4, "Stage IV β€” Documentation",
         "The selected design is detailed with walls, doors and windows, then "
         "exported to CAD and image formats. "
         "<i>User Interactive Editor Module.</i>"),
    ]
    for col, title, desc in cards:
        col.markdown(
            f"""
            <div class="metric-card" style="text-align:left; min-height:145px;">
                <div style="font-size:1rem; margin-bottom:0.4rem;"><b style="color:#4FC3F7;">{title}</b></div>
                <div style="font-size:0.82rem; color:#8B949E; line-height:1.4;">{desc}</div>
            </div>
            """,
            unsafe_allow_html=True,
        )