File size: 58,470 Bytes
1c17b67
149b55d
c8370ac
 
1c17b67
149b55d
 
9a13d73
149b55d
 
54af1a9
9daa4e6
149bbed
1c17b67
 
f10100d
 
 
 
 
 
82467f9
d8b8170
 
 
 
 
b59c2e9
 
 
 
 
 
e603457
ff61605
c8370ac
cf8ed7d
 
 
149b55d
 
 
 
 
 
 
 
c8370ac
149b55d
 
 
 
 
 
 
 
 
c8370ac
149b55d
 
a337e1e
149b55d
 
 
c8370ac
7adad6c
 
 
 
 
 
 
 
 
 
 
 
 
c8370ac
 
e603457
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c17b67
 
 
 
c8370ac
 
 
149b55d
c8370ac
 
 
 
 
 
 
54af1a9
 
 
 
 
 
 
 
c8370ac
 
149bbed
c8370ac
a337e1e
 
149bbed
a337e1e
149b55d
 
 
 
 
c8370ac
a337e1e
149b55d
 
c8370ac
a337e1e
149b55d
 
 
 
c8370ac
a337e1e
149b55d
 
 
 
 
 
c8370ac
82467f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149b55d
82467f9
149b55d
c8370ac
149b55d
 
 
 
 
c8370ac
7adad6c
1c17b67
 
 
7adad6c
 
 
 
1c17b67
 
 
 
7adad6c
 
 
 
 
1c17b67
98ba82f
 
 
7adad6c
 
 
 
 
 
 
 
 
 
 
 
 
 
c8370ac
1c17b67
 
 
a337e1e
 
 
 
 
c8370ac
a337e1e
149b55d
c8370ac
7adad6c
 
 
 
 
 
 
b59c2e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e603457
b59c2e9
 
 
 
 
 
e603457
 
 
 
 
 
b59c2e9
 
 
 
 
 
 
 
f3b85c6
 
9a13d73
b59c2e9
 
e603457
 
b59c2e9
 
 
 
 
 
 
e603457
9a13d73
 
 
 
 
 
 
 
 
 
 
 
f3b85c6
e603457
 
 
 
9a13d73
 
 
 
 
 
f3b85c6
e603457
9a13d73
 
 
f3b85c6
 
9a13d73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5182a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d49a735
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff61605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c17b67
a337e1e
f3b85c6
 
 
 
 
a337e1e
f3b85c6
 
a337e1e
f3b85c6
a337e1e
 
 
 
f3b85c6
 
 
 
 
 
a337e1e
 
f3b85c6
a337e1e
 
 
f3b85c6
 
 
a337e1e
 
c8370ac
a337e1e
1c17b67
a337e1e
149b55d
 
 
1c17b67
 
ff61605
149b55d
f3b85c6
1c17b67
f3b85c6
a337e1e
cf8ed7d
 
1c17b67
a337e1e
 
f3b85c6
a337e1e
82467f9
 
 
 
f3b85c6
a337e1e
1c17b67
f3b85c6
1c17b67
 
a337e1e
 
f3b85c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5182a9
 
f3b85c6
 
 
 
 
 
 
 
 
 
d8b8170
 
 
f3b85c6
 
bd71026
f3b85c6
9a13d73
f3b85c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f10100d
 
 
 
 
f3b85c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e603457
 
 
 
 
 
 
f3b85c6
 
 
 
 
 
 
 
 
 
 
 
 
bd71026
b59c2e9
f3b85c6
 
 
 
 
 
b59c2e9
f3b85c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e603457
 
f3b85c6
 
 
 
 
 
 
 
d49a735
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff61605
 
 
 
 
 
d49a735
 
 
 
 
 
 
 
 
 
 
 
 
ff61605
d49a735
 
 
 
ff61605
 
 
 
 
 
 
d49a735
ff61605
d49a735
f3b85c6
 
 
 
 
 
 
 
 
a337e1e
 
149b55d
 
 
 
1c17b67
 
 
 
 
c8370ac
 
149bbed
c8370ac
149b55d
1c17b67
7adad6c
1c17b67
7adad6c
1c17b67
c8370ac
 
149bbed
c8370ac
149b55d
 
 
 
 
 
 
 
149bbed
149b55d
 
a337e1e
a587cf8
 
 
a337e1e
 
 
a587cf8
 
 
 
 
 
 
 
 
 
 
 
 
 
a337e1e
a587cf8
 
149b55d
 
 
a337e1e
149b55d
 
 
 
149bbed
149b55d
 
 
 
a337e1e
149b55d
 
 
 
149bbed
149b55d
 
 
 
82467f9
 
 
 
 
 
 
 
149b55d
 
 
 
149bbed
149b55d
 
d5182a9
 
 
 
 
 
 
 
 
 
 
 
149b55d
 
 
 
 
 
 
149bbed
149b55d
 
c8370ac
 
 
54af1a9
 
c8370ac
d8b8170
 
 
e603457
 
 
d8b8170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e603457
 
 
 
 
 
d8b8170
 
 
e603457
d8b8170
 
 
 
 
 
e603457
 
 
d8b8170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e603457
 
 
 
 
 
d8b8170
 
 
e603457
d8b8170
 
 
149b55d
 
7adad6c
1c17b67
149b55d
bd71026
b59c2e9
 
 
 
 
 
f10100d
e603457
b59c2e9
 
 
 
 
 
 
 
9a13d73
 
b59c2e9
f10100d
d8031b4
 
b59c2e9
 
 
 
 
 
 
 
 
f10100d
 
 
e603457
 
 
 
 
 
f10100d
 
 
 
 
 
 
 
 
 
 
 
 
e603457
f10100d
 
 
 
 
 
 
 
 
 
 
 
e603457
f10100d
 
 
 
 
 
 
 
 
 
 
 
 
e603457
f10100d
 
b59c2e9
 
 
 
f3b85c6
b59c2e9
 
 
e603457
 
 
 
 
 
f10100d
e603457
 
 
 
 
 
 
 
 
 
b59c2e9
 
 
 
 
 
f3b85c6
 
 
b59c2e9
e603457
 
 
 
 
 
 
9a13d73
 
b59c2e9
 
 
 
 
 
 
 
 
 
 
 
 
3b8afb0
b59c2e9
 
 
 
 
 
 
 
 
3b8afb0
 
 
 
f3b85c6
b59c2e9
 
3b8afb0
 
bd71026
d49a735
 
 
 
 
 
 
ff61605
 
 
 
 
d49a735
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff61605
 
 
 
 
 
 
 
 
d49a735
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff61605
 
 
 
 
 
 
 
 
d49a735
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff61605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d49a735
 
 
 
 
 
ff61605
d49a735
ff61605
 
 
 
 
d49a735
bd71026
b59c2e9
 
 
 
 
 
 
f10100d
e603457
b59c2e9
 
 
 
 
 
 
 
9a13d73
 
b59c2e9
 
9a13d73
bd71026
149b55d
3b8afb0
 
b59c2e9
 
 
 
 
 
 
 
 
 
 
 
3b8afb0
 
 
d49a735
 
 
 
 
 
 
 
 
ff61605
 
 
 
 
d49a735
 
 
 
 
 
 
 
ff61605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d49a735
 
d8b8170
 
 
 
 
e603457
 
 
d8b8170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e603457
 
 
d8b8170
 
 
 
 
 
 
 
 
 
 
 
1c17b67
 
 
 
7adad6c
 
 
 
 
 
 
 
1c17b67
 
 
 
 
149b55d
7adad6c
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
# app.py
import os
import tempfile
import pathlib
import hashlib
import gradio as gr
import numpy as np
import matplotlib.pyplot as plt

from quread.engine import QuantumStateVector
from quread.exporters import to_openqasm2, to_qiskit, to_cirq, to_csv, csv_to_skill
from quread.llm_explain_openai import explain_with_gpt4o
from quread.circuit_diagram import draw_circuit_svg
from quread.cost_guard import allow_request
from quread.export_pdf import md_to_pdf
from quread.heatmap import (
    make_metric_heatmap,
    make_metric_heatmap_plotly,
    plotly_available,
    HeatmapConfig,
)
from quread.noise_model import sample_noisy_counts
from quread.eda_translator import (
    build_eda_mapping,
    to_synopsys_tcl,
    to_cadence_skill_reliability,
)
from quread.metrics import (
    compute_metrics_from_csv,
    to_metrics_csv,
    MetricWeights,
    MetricThresholds,
)
from quread.layout_mapper import parse_layout_csv_text
from quread.trends import compute_metric_trends, compute_drift_alerts, alerts_to_csv

# --- Qubit cap (configurable) ---
DEFAULT_MAX_QUBITS = 16  # safe default for CPU Spaces; change if you want
MAX_QUBITS = int(os.getenv("QUREAD_MAX_QUBITS", DEFAULT_MAX_QUBITS))

# ---------- Helpers ----------
def _new_sim(n_qubits: int):
    qc = QuantumStateVector(int(n_qubits))
    last_counts = None
    selected_gate = "H"
    return qc, last_counts, selected_gate


def _probs_top(qc, n_qubits: int, k: int = 6):
    probs = (np.abs(qc.state) ** 2)
    top = sorted(
        [(format(i, f"0{n_qubits}b"), float(p)) for i, p in enumerate(probs)],
        key=lambda x: x[1],
        reverse=True
    )[:k]
    return top


def _counts_str(counts):
    if not counts:
        return ""
    return "\n".join([f"{k}: {v}" for k, v in counts.items()])


def _write_tmp(filename: str, content: str) -> str:
    base = pathlib.Path(filename).name
    stem = pathlib.Path(base).stem or "quread"
    suffix = pathlib.Path(base).suffix or ".txt"
    with tempfile.NamedTemporaryFile(
        mode="w",
        encoding="utf-8",
        prefix=f"{stem}_",
        suffix=suffix,
        dir=tempfile.gettempdir(),
        delete=False,
    ) as f:
        f.write(content)
        return f.name


def _read_uploaded_text(uploaded_file) -> str:
    if uploaded_file is None:
        return ""

    if isinstance(uploaded_file, bytes):
        return uploaded_file.decode("utf-8", errors="replace")
    if isinstance(uploaded_file, str):
        path = pathlib.Path(uploaded_file)
        if path.exists():
            return path.read_text(encoding="utf-8", errors="replace")
        return ""

    if isinstance(uploaded_file, dict):
        raw = uploaded_file.get("data")
        if isinstance(raw, bytes):
            return raw.decode("utf-8", errors="replace")
        maybe_path = uploaded_file.get("name") or uploaded_file.get("path")
        if maybe_path:
            path = pathlib.Path(str(maybe_path))
            if path.exists():
                return path.read_text(encoding="utf-8", errors="replace")
        return ""

    maybe_path = getattr(uploaded_file, "name", None)
    if maybe_path:
        path = pathlib.Path(str(maybe_path))
        if path.exists():
            return path.read_text(encoding="utf-8", errors="replace")

    raw = getattr(uploaded_file, "data", None)
    if isinstance(raw, bytes):
        return raw.decode("utf-8", errors="replace")
    return ""


def _resolve_layout_coords(layout_file, n_qubits, rows, cols):
    layout_text = _read_uploaded_text(layout_file)
    return parse_layout_csv_text(
        layout_text,
        int(n_qubits),
        rows=int(rows),
        cols=int(cols),
    )


def _circuit_hash(history):
    return hashlib.sha256(str(history).encode()).hexdigest()


def dl_qasm(qc, n_qubits):
    return _write_tmp("circuit.qasm", to_openqasm2(qc.history, n_qubits=int(n_qubits)))


def dl_qiskit(qc, n_qubits):
    return _write_tmp("circuit_qiskit.py", to_qiskit(qc.history, n_qubits=int(n_qubits)))


def dl_cirq(qc, n_qubits):
    return _write_tmp("circuit_cirq.py", to_cirq(qc.history, n_qubits=int(n_qubits)))

def dl_csv(qc):
    return _write_tmp("circuit.csv", to_csv(qc.history))


def dl_skill(qc, n_qubits):
    csv_text = to_csv(qc.history)
    skill_text = csv_to_skill(csv_text, n_qubits=int(n_qubits))
    return _write_tmp("circuit.il", skill_text)

def update_views(qc, last_counts, n_qubits):
    svg = draw_circuit_svg(qc.history, n_qubits=int(n_qubits))
    ket = qc.ket_notation(max_terms=16)
    probs_top = _probs_top(qc, int(n_qubits), k=6)
    counts_text = _counts_str(last_counts)
    return svg, ket, counts_text, probs_top


def init_or_reset(n_qubits):
    qc, last_counts, selected_gate = _new_sim(n_qubits)
    return qc, last_counts, selected_gate, "✅ Reset done."


def set_gate(gate):
    return gate, f"✅ Selected gate: {gate}"


def apply_selected_gate(qc, last_counts, selected_gate, target):
    qc.apply_single(selected_gate, target=int(target))
    last_counts = None
    return qc, last_counts, f"✅ Applied {selected_gate} on q{target}."


def apply_cnot(qc, last_counts, control, target):
    if int(control) == int(target):
        return qc, last_counts, "❌ Control and target must be different."
    qc.apply_cnot(control=int(control), target=int(target))
    last_counts = None
    return qc, last_counts, f"✅ Applied CNOT (q{control} -> q{target})."


def sample_shots(
    qc,
    shots,
    noise_preview_enabled,
    readout_scale,
    depolarizing_prob,
    calibration_text,
):
    if bool(noise_preview_enabled):
        last_counts = sample_noisy_counts(
            state=qc.state,
            n_qubits=qc.n_qubits,
            shots=int(shots),
            calibration_json=str(calibration_text or ""),
            readout_scale=float(readout_scale),
            depolarizing_prob=float(depolarizing_prob),
        )
        return last_counts, "✅ Sampled noisy hardware-preview shots."

    last_counts = qc.sample(shots=int(shots))
    return last_counts, "✅ Sampled ideal shots."


def measure_collapse(qc, shots):
    res = qc.measure_collapse()
    last_counts = qc.sample(shots=int(shots))
    return last_counts, f"✅ Collapsed to |{res}⟩ and sampled shots."


def explain_llm(qc, n_qubits, shots, last_hash, previous_explanation):
    # circuit-change gating
    curr_hash = _circuit_hash(qc.history)
    if curr_hash == last_hash:
        if previous_explanation:
            shown = f"ℹ️ Circuit unchanged. Reusing previous explanation.\n\n{previous_explanation}"
            return shown, last_hash, previous_explanation
        return "ℹ️ Circuit unchanged. No previous explanation available.", last_hash, previous_explanation

    # cost guard
    EST_TOKENS = 900
    if not allow_request(EST_TOKENS):
        if previous_explanation:
            shown = "🚫 Explanation disabled (daily token limit reached). Showing previous explanation.\n\n"
            shown += previous_explanation
            return shown, last_hash, previous_explanation
        return "🚫 Explanation disabled (daily token limit reached).", last_hash, previous_explanation

    state_ket = qc.ket_notation(max_terms=6)
    probs_top = _probs_top(qc, int(n_qubits), k=6)

    try:
        explanation = explain_with_gpt4o(
            n_qubits=int(n_qubits),
            history=qc.history,
            state_ket=state_ket,
            probs_top=probs_top,
            shots=int(shots),
        )
    except Exception as exc:
        safe_msg = f"❌ Explanation request failed: {exc}"
        if previous_explanation:
            shown = f"{safe_msg}\n\nShowing previous explanation:\n\n{previous_explanation}"
            return shown, last_hash, previous_explanation
        return safe_msg, last_hash, previous_explanation

    return explanation, curr_hash, explanation


def _refresh_choices(n):
    opts = list(range(int(n)))
    return (
        gr.Dropdown(choices=opts, value=0),
        gr.Dropdown(choices=opts, value=0),
        gr.Dropdown(choices=opts, value=min(1, int(n) - 1)),
    )


def _on_qubit_count_change(n):
    qc, last_counts, selected_gate = _new_sim(n)
    t, c, ct = _refresh_choices(n)
    msg = f"✅ Reinitialized simulator with {int(n)} qubits."
    return qc, last_counts, selected_gate, t, c, ct, msg


def _metric_controls_to_models(
    activity_w,
    gate_error_w,
    readout_error_w,
    decoherence_w,
    fidelity_w,
    warning_thr,
    critical_thr,
):
    weights = MetricWeights(
        activity=float(activity_w),
        gate_error=float(gate_error_w),
        readout_error=float(readout_error_w),
        decoherence=float(decoherence_w),
        fidelity=float(fidelity_w),
    )
    thresholds = MetricThresholds(
        warning=float(warning_thr),
        critical=float(critical_thr),
    )
    return weights, thresholds


def _hotspot_rows(metrics, n_qubits, top_k, qubit_coords=None):
    rows = []
    n = int(n_qubits)
    for q in range(n):
        risk = float(metrics["composite_risk"][q])
        level = int(metrics["hotspot_level"][q])
        status = "critical" if level == 2 else ("warning" if level == 1 else "ok")
        layout_row = ""
        layout_col = ""
        if qubit_coords and q in qubit_coords:
            rr, cc = qubit_coords[q]
            layout_row = int(rr)
            layout_col = int(cc)
        rows.append(
            [
                q,
                status,
                round(risk, 6),
                round(float(metrics["activity_count"][q]), 3),
                round(float(metrics["gate_error"][q]), 6),
                round(float(metrics["readout_error"][q]), 6),
                round(float(metrics["state_fidelity"][q]), 6),
                round(float(metrics["process_fidelity"][q]), 6),
                round(float(metrics["coherence_health"][q]), 6),
                round(float(metrics["decoherence_risk"][q]), 6),
                round(float(metrics["fidelity"][q]), 6),
                layout_row,
                layout_col,
            ]
        )
    rows.sort(key=lambda x: x[2], reverse=True)
    k = max(1, min(int(top_k), len(rows)))
    return rows[:k]


def _hotspot_detail_markdown(metrics, meta, n_qubits, focus_qubit, qubit_coords=None):
    n = int(n_qubits)
    if n < 1:
        return "No qubits available."
    q = int(max(0, min(int(focus_qubit), n - 1)))

    risk = float(metrics["composite_risk"][q])
    level = int(metrics["hotspot_level"][q])
    status = "critical" if level == 2 else ("warning" if level == 1 else "ok")

    thresholds = meta.get("thresholds")
    thr_warning = float(getattr(thresholds, "warning", 0.45))
    thr_critical = float(getattr(thresholds, "critical", 0.70))
    fidelity_backend = str(meta.get("fidelity_backend", "unknown"))
    coord_line = ""
    if qubit_coords and q in qubit_coords:
        rr, cc = qubit_coords[q]
        coord_line = f"- Layout coordinate: row={int(rr)}, col={int(cc)}\n"

    return (
        f"### Hotspot Detail: q{q}\n"
        f"- Status: **{status}**\n"
        f"- Composite risk: **{risk:.6f}**\n"
        f"- Thresholds: warning={thr_warning:.2f}, critical={thr_critical:.2f}\n"
        f"- Fidelity backend: `{fidelity_backend}`\n"
        f"{coord_line}"
        f"- Activity count: {float(metrics['activity_count'][q]):.3f}\n"
        f"- Gate error: {float(metrics['gate_error'][q]):.6f}\n"
        f"- Readout error: {float(metrics['readout_error'][q]):.6f}\n"
        f"- State fidelity: {float(metrics['state_fidelity'][q]):.6f}\n"
        f"- Process fidelity: {float(metrics['process_fidelity'][q]):.6f}\n"
        f"- Coherence health: {float(metrics['coherence_health'][q]):.6f}\n"
        f"- Decoherence risk: {float(metrics['decoherence_risk'][q]):.6f}\n"
        f"- Fidelity: {float(metrics['fidelity'][q]):.6f}"
    )


def _hotspot_detail_plot(metrics, meta, n_qubits, focus_qubit):
    n = int(n_qubits)
    if n < 1:
        fig, ax = plt.subplots(figsize=(6, 3))
        ax.set_title("No qubits available")
        ax.axis("off")
        fig.tight_layout()
        return fig

    q = int(max(0, min(int(focus_qubit), n - 1)))
    weights = meta.get("weights")
    w_activity = float(getattr(weights, "activity", 0.25))
    w_gate = float(getattr(weights, "gate_error", 0.20))
    w_readout = float(getattr(weights, "readout_error", 0.15))
    w_decoh = float(getattr(weights, "decoherence", 0.25))
    w_fidelity = float(getattr(weights, "fidelity", 0.15))

    fidelity_risk = 1.0 - float(metrics["fidelity"][q])
    components = {
        "activity": float(metrics["activity_norm"][q]),
        "gate_error": float(metrics["gate_error"][q]),
        "readout_error": float(metrics["readout_error"][q]),
        "decoherence_risk": float(metrics["decoherence_risk"][q]),
        "fidelity_risk": fidelity_risk,
    }
    weighted = {
        "activity": w_activity * components["activity"],
        "gate_error": w_gate * components["gate_error"],
        "readout_error": w_readout * components["readout_error"],
        "decoherence_risk": w_decoh * components["decoherence_risk"],
        "fidelity_risk": w_fidelity * components["fidelity_risk"],
    }

    labels = list(weighted.keys())
    values = [weighted[k] for k in labels]

    fig, ax = plt.subplots(figsize=(7, 3.5))
    ax.bar(labels, values, color=["#4f46e5", "#dc2626", "#f97316", "#2563eb", "#16a34a"])
    ax.set_ylim(0.0, 1.0)
    ax.set_ylabel("Weighted contribution")
    ax.set_title(f"Composite risk contributions for q{q}")
    ax.tick_params(axis="x", rotation=15)
    for idx, v in enumerate(values):
        ax.text(idx, v + 0.02, f"{v:.3f}", ha="center", va="bottom", fontsize=8)
    fig.tight_layout()
    return fig


def _ideal_vs_noisy_plot(
    qc,
    shots,
    calibration_text,
    readout_scale,
    depolarizing_prob,
):
    n = int(qc.n_qubits)
    s = int(shots)

    ideal_counts = qc.sample(shots=s)
    noisy_counts = sample_noisy_counts(
        state=qc.state,
        n_qubits=n,
        shots=s,
        calibration_json=str(calibration_text or ""),
        readout_scale=float(readout_scale),
        depolarizing_prob=float(depolarizing_prob),
    )

    keys = sorted(set(ideal_counts.keys()) | set(noisy_counts.keys()))
    if not keys:
        keys = [format(0, f"0{n}b")]

    ideal = np.array([ideal_counts.get(k, 0) for k in keys], dtype=float)
    noisy = np.array([noisy_counts.get(k, 0) for k in keys], dtype=float)
    ideal_p = ideal / max(1.0, float(np.sum(ideal)))
    noisy_p = noisy / max(1.0, float(np.sum(noisy)))

    x = np.arange(len(keys))
    w = 0.4
    fig, ax = plt.subplots(figsize=(max(7.0, len(keys) * 0.65), 3.8))
    ax.bar(x - w / 2, ideal_p, width=w, label="Ideal", color="#4f46e5")
    ax.bar(x + w / 2, noisy_p, width=w, label="Noisy", color="#dc2626")
    ax.set_xticks(x)
    ax.set_xticklabels(keys, rotation=45, ha="right")
    ax.set_ylim(0.0, 1.0)
    ax.set_ylabel("Probability")
    ax.set_title("Ideal vs Noisy measurement distribution")
    ax.legend(loc="upper right")
    fig.tight_layout()
    return fig


def _metric_label(metric_key: str) -> str:
    labels = {
        "composite_risk": "Composite risk",
        "gate_error": "Gate error",
        "readout_error": "Readout error",
        "decoherence_risk": "Decoherence risk",
        "fidelity": "Fidelity",
        "state_fidelity": "State fidelity",
        "process_fidelity": "Process fidelity",
        "coherence_health": "Coherence health",
    }
    return labels.get(metric_key, metric_key.replace("_", " ").title())


def _plot_metric_trends(series, labels, ranking_rows, metric_key, top_k):
    if series.size == 0:
        fig, ax = plt.subplots(figsize=(7, 3))
        ax.set_title("No trend data")
        ax.axis("off")
        fig.tight_layout()
        return fig

    k = max(1, min(int(top_k), len(ranking_rows)))
    selected_qubits = [int(ranking_rows[i]["qubit"]) for i in range(k)]
    x = np.arange(series.shape[0])
    fig, ax = plt.subplots(figsize=(8, 4))
    for q in selected_qubits:
        ax.plot(x, series[:, q], marker="o", linewidth=2, label=f"q{q}")

    xticks = labels
    if len(xticks) > 12:
        step = max(1, len(xticks) // 10)
        keep = [idx for idx in range(len(xticks)) if idx % step == 0 or idx == len(xticks) - 1]
        ax.set_xticks(keep)
        ax.set_xticklabels([xticks[i] for i in keep], rotation=35, ha="right")
    else:
        ax.set_xticks(x)
        ax.set_xticklabels(xticks, rotation=35, ha="right")

    ax.set_ylim(0.0, 1.0)
    ax.set_ylabel(_metric_label(metric_key))
    ax.set_xlabel("Snapshot")
    ax.set_title(f"Temporal drift: top {k} qubits by latest {_metric_label(metric_key).lower()}")
    ax.grid(alpha=0.2, linestyle="--")
    ax.legend(ncols=2, fontsize=8)
    fig.tight_layout()
    return fig


def _drift_alert_summary(alert_rows):
    total = len(alert_rows)
    critical = sum(1 for r in alert_rows if str(r.get("level")) == "critical")
    warning = sum(1 for r in alert_rows if str(r.get("level")) == "warning")
    ok = max(0, total - critical - warning)
    if critical > 0:
        badge = "critical drift detected"
    elif warning > 0:
        badge = "warning drift detected"
    else:
        badge = "stable"
    return f"Auto-flag summary: critical={critical}, warning={warning}, ok={ok} ({badge})."


def _mitigation_hint_for_metric(metric_key, level):
    severity = str(level or "ok")
    if metric_key == "gate_error":
        return "Prioritize gate pulse recalibration and schedule RB/IRB validation."
    if metric_key == "readout_error":
        return "Run readout discriminator retuning and measurement calibration refresh."
    if metric_key == "decoherence_risk":
        return "Reduce circuit depth on flagged qubits and revisit idle decoupling timing."
    if metric_key in {"fidelity", "state_fidelity", "process_fidelity"}:
        return "Re-characterize fidelity with tomography/benchmarking and re-tune control stack."
    if metric_key == "coherence_health":
        return "Investigate T1/T2 drift, thermal environment, and schedule recalibration windows."
    if severity == "critical":
        return "Lock flagged qubits out of high-depth paths and escalate full calibration."
    if severity == "warning":
        return "Increase monitoring cadence and rebalance workloads away from flagged qubits."
    return "No immediate action required; continue scheduled monitoring."


def _drift_recommendations_markdown(alert_rows, metric_key, max_items=6):
    if not alert_rows:
        return "No recommendations available yet. Run drift analysis first."

    actionable = [r for r in alert_rows if str(r.get("level")) in {"critical", "warning"}]
    if not actionable:
        return "### Recommended Actions\n- No active drift alerts. Maintain regular calibration cadence."

    lines = ["### Recommended Actions"]
    k = max(1, min(int(max_items), len(actionable)))
    for row in actionable[:k]:
        q = int(row.get("qubit", -1))
        level = str(row.get("level", "warning"))
        hint = _mitigation_hint_for_metric(str(metric_key), level)
        triggers = row.get("triggers") or []
        reason = ", ".join(str(t) for t in triggers[:2]) if triggers else "trend threshold crossing"
        lines.append(f"- q{q} ({level}): {hint} Trigger: {reason}.")
    return "\n".join(lines)


# ---------- Styling ----------
CSS = """
#title h1 { font-size: 38px !important; margin-bottom: 4px; letter-spacing: -0.02em; }
#subtitle { color: #64748b; margin-top: 0px; }
.app-shell {
  gap: 14px;
}
.sidebar {
  background: linear-gradient(160deg, #f8fafc 0%, #eef2ff 100%);
  border: 1px solid #dbeafe;
  border-radius: 14px;
  padding: 16px 14px;
  height: calc(100vh - 34px);
  position: sticky;
  top: 16px;
}
.main-panel {
  background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%);
  border: 1px solid #e2e8f0;
  border-radius: 14px;
  padding: 14px;
}
.card {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 14px;
  padding: 14px;
}
.section-title { font-size: 21px; font-weight: 700; margin: 4px 0 10px; color: #0f172a; }
.small-note { color: #64748b; font-size: 12px; }
.analytics-action-row { gap: 8px; }
"""

theme = gr.themes.Soft(radius_size="lg", text_size="md")


with gr.Blocks(theme=theme, css=CSS, title="Quread.ai — State Vector Studio") as demo:
    qc_state = gr.State()
    last_counts_state = gr.State()
    selected_gate_state = gr.State()
    explanation_md = gr.State("")
    last_explained_hash = gr.State("")
    drift_alert_rows_state = gr.State([])

    with gr.Row(elem_classes=["app-shell"]):
        # Sidebar
        with gr.Column(scale=2, elem_classes=["sidebar"]):
            gr.Markdown("### Simulator Settings")
            n_qubits = gr.Slider(1, MAX_QUBITS, value=2, step=1, label="Number of qubits")
            gr.Markdown(f"<div class='small-note'>Max qubits: <b>{MAX_QUBITS}</b> (set env var <code>QUREAD_MAX_QUBITS</code> to change)</div>")
            shots = gr.Slider(128, 8192, value=1024, step=128, label="Shots")

            gr.Markdown("---")
            gr.Markdown("### Quick Actions")
            reset_btn = gr.Button("Reset Simulator", variant="secondary")
            with gr.Accordion("Hardware Noise Preview", open=False):
                noise_preview_enabled = gr.Checkbox(label="Enable noise-aware sampling", value=False)
                noise_readout_scale = gr.Slider(0.0, 3.0, value=1.0, step=0.05, label="Readout error scale")
                noise_depolarizing = gr.Slider(0.0, 0.5, value=0.0, step=0.01, label="Depolarizing probability")
            gr.Markdown("<div class='small-note'>Analytics controls are in the <b>Hardware Analytics</b> tab.</div>")

        # Main
        with gr.Column(scale=10, elem_classes=["main-panel"]):
            gr.Markdown("<div id='title'><h1>Quread.ai — State Vector Studio</h1></div>")
            gr.Markdown("<div id='subtitle'>Build circuits, visualize, export, and get teaching-ready explanations.</div>")
            status = gr.Markdown("")

            with gr.Tabs():
                with gr.Tab("Circuit Studio"):
                    with gr.Row():
                        with gr.Column(scale=7):
                            with gr.Group(elem_classes=["card"]):
                                gr.Markdown("<div class='section-title'>Gate Palette</div>")
                                with gr.Row():
                                    gate_H = gr.Button("H")
                                    gate_T = gr.Button("T")
                                    gate_Tdg = gr.Button("T†")
                                    gate_X = gr.Button("X")
                                with gr.Row():
                                    gate_Y = gr.Button("Y")
                                    gate_Z = gr.Button("Z")
                                    gate_sx = gr.Button("√X")
                                    gate_sz = gr.Button("√Z")
                                with gr.Row():
                                    gate_rx_pi = gr.Button("Rx(π)")
                                    gate_rx_pi2 = gr.Button("Rx(π/2)")
                                    gate_ry_pi = gr.Button("Ry(π)")
                                    gate_ry_pi2 = gr.Button("Ry(π/2)")
                                with gr.Row():
                                    gate_rz_pi = gr.Button("Rz(π)")
                                    gate_rz_pi2 = gr.Button("Rz(π/2)")
                                    gate_I = gr.Button("I")
                                    gate_Idg = gr.Button("I†")  # will map to I
                                with gr.Row():
                                    gate_S = gr.Button("S")
                                    gate_Sdg = gr.Button("S†")

                                target = gr.Dropdown(choices=[0, 1], value=0, label="Target qubit")

                                with gr.Row():
                                    apply_gate_btn = gr.Button("Apply Selected Gate", variant="primary")
                                    sample_btn = gr.Button("Sample shots")
                                    measure_btn = gr.Button("Measure + Collapse")

                                gr.Markdown("**CNOT**")
                                with gr.Row():
                                    control = gr.Dropdown(choices=[0, 1], value=0, label="Control")
                                    cnot_target = gr.Dropdown(choices=[0, 1], value=1, label="Target")
                                    apply_cnot_btn = gr.Button("Apply CNOT")

                            with gr.Group(elem_classes=["card"]):
                                gr.Markdown("<div class='section-title'>Circuit Diagram</div>")
                                circuit_html = gr.HTML()

                        with gr.Column(scale=5):
                            with gr.Group(elem_classes=["card"]):
                                gr.Markdown("<div class='section-title'>Statevector</div>")
                                ket_out = gr.Code(label="", language="python")
                                gr.Markdown("<div class='section-title'>Top probabilities</div>")
                                probs_out = gr.Dataframe(headers=["bitstring", "prob"], interactive=False)

                            with gr.Group(elem_classes=["card"]):
                                gr.Markdown("<div class='section-title'>Measurement distribution</div>")
                                counts_out = gr.Textbox(lines=10)
                                compare_dist_btn = gr.Button("Compare Ideal vs Noisy", variant="secondary")
                                dist_compare_plot = gr.Plot()

                            with gr.Group(elem_classes=["card"]):
                                gr.Markdown("<div class='section-title'>Export</div>")
                                with gr.Row():
                                    qasm_dl = gr.DownloadButton("OpenQASM 2.0")
                                    qiskit_dl = gr.DownloadButton("Qiskit")
                                with gr.Row():
                                    cirq_dl = gr.DownloadButton("Cirq")
                                    csv_dl = gr.DownloadButton("CSV")
                                skill_dl = gr.DownloadButton("Skill script")
                                with gr.Row():
                                    synopsys_tcl_dl = gr.DownloadButton("Synopsys TCL (risk)")
                                    cadence_skill_dl = gr.DownloadButton("Cadence SKILL (risk)")

                with gr.Tab("Hardware Analytics"):
                    with gr.Group(elem_classes=["card"]):
                        gr.Markdown("<div class='section-title'>Heatmap & Hotspots</div>")
                        with gr.Row():
                            with gr.Column(scale=4):
                                heat_metric = gr.Dropdown(
                                    choices=[
                                        "activity_count",
                                        "activity_norm",
                                        "gate_error",
                                        "readout_error",
                                        "coherence_health",
                                        "decoherence_risk",
                                        "fidelity",
                                        "state_fidelity",
                                        "process_fidelity",
                                        "composite_risk",
                                    ],
                                    value="activity_count",
                                    label="Metric",
                                )
                                heat_render_mode = gr.Dropdown(
                                    choices=["interactive", "static"],
                                    value="interactive",
                                    label="Render mode",
                                )
                                chip_rows = gr.Slider(2, 64, value=8, step=1, label="Chip rows")
                                chip_cols = gr.Slider(2, 64, value=8, step=1, label="Chip cols")
                                metric_threshold = gr.Slider(
                                    0.0,
                                    1.0,
                                    value=0.05,
                                    step=0.01,
                                    label="Threshold filter (0 = off)",
                                )
                                with gr.Row(elem_classes=["analytics-action-row"]):
                                    heat_btn = gr.Button("Generate heatmap", variant="primary")
                                    metrics_csv_dl = gr.DownloadButton("Download metrics CSV")
                            with gr.Column(scale=8):
                                with gr.Accordion("Calibration Input", open=False):
                                    calibration_json = gr.Textbox(
                                        lines=6,
                                        label="Calibration JSON (optional)",
                                        placeholder='{"qubits":{"0":{"gate_error":0.012,"readout_error":0.02,"t1_us":82,"t2_us":61,"fidelity":0.991}}}',
                                    )
                                with gr.Accordion("Physical Layout Mapper", open=False):
                                    layout_csv_file = gr.File(
                                        label="Layout CSV (optional): qubit,row,col",
                                        file_types=[".csv"],
                                        type="filepath",
                                    )
                                    gr.Markdown("<div class='small-note'>Accepted aliases: qubit_id/q/id and row(r/y), col(c/x).</div>")
                                with gr.Accordion("Advanced Weights & Thresholds", open=False):
                                    gr.Markdown("<div class='small-note'>Composite risk weights are normalized automatically.</div>")
                                    with gr.Row():
                                        w_activity = gr.Slider(0.0, 1.0, value=0.25, step=0.01, label="Weight: activity")
                                        w_gate = gr.Slider(0.0, 1.0, value=0.20, step=0.01, label="Weight: gate error")
                                        w_readout = gr.Slider(0.0, 1.0, value=0.15, step=0.01, label="Weight: readout error")
                                    with gr.Row():
                                        w_decoherence = gr.Slider(0.0, 1.0, value=0.25, step=0.01, label="Weight: decoherence")
                                        w_fidelity = gr.Slider(0.0, 1.0, value=0.15, step=0.01, label="Weight: fidelity risk")
                                    with gr.Row():
                                        thr_warning = gr.Slider(0.0, 1.0, value=0.45, step=0.01, label="Threshold: warning")
                                        thr_critical = gr.Slider(0.0, 1.0, value=0.70, step=0.01, label="Threshold: critical")
                                        hotspot_top_k = gr.Slider(1, 64, value=16, step=1, label="Hotspot rows")
                        heat_plot = gr.Plot()
                        hotspot_status = gr.Markdown()
                        hotspot_focus_q = gr.Slider(
                            0,
                            max(0, MAX_QUBITS - 1),
                            value=0,
                            step=1,
                            label="Hotspot detail qubit",
                        )
                        with gr.Row():
                            with gr.Column(scale=7):
                                hotspot_table = gr.Dataframe(
                                    headers=[
                                        "qubit",
                                        "status",
                                        "composite_risk",
                                        "activity_count",
                                        "gate_error",
                                        "readout_error",
                                        "state_fidelity",
                                        "process_fidelity",
                                        "coherence_health",
                                        "decoherence_risk",
                                        "fidelity",
                                        "layout_row",
                                        "layout_col",
                                    ],
                                    interactive=False,
                                    label="Hotspot ranking (highest composite risk first)",
                                )
                            with gr.Column(scale=5):
                                hotspot_detail_md = gr.Markdown()
                                hotspot_detail_plot = gr.Plot()

                    with gr.Group(elem_classes=["card"]):
                        gr.Markdown("<div class='section-title'>Temporal Drift (Calibration Snapshots)</div>")
                        with gr.Row():
                            trend_metric = gr.Dropdown(
                                choices=[
                                    "composite_risk",
                                    "gate_error",
                                    "readout_error",
                                    "decoherence_risk",
                                    "fidelity",
                                    "state_fidelity",
                                    "process_fidelity",
                                    "coherence_health",
                                ],
                                value="composite_risk",
                                label="Trend metric",
                            )
                            trend_top_k = gr.Slider(1, 32, value=8, step=1, label="Trend lines (top qubits)")
                            trend_btn = gr.Button("Analyze drift", variant="secondary")
                        with gr.Row():
                            drift_delta_warning = gr.Slider(0.0, 1.0, value=0.08, step=0.01, label="Drift delta warning")
                            drift_delta_critical = gr.Slider(0.0, 1.0, value=0.18, step=0.01, label="Drift delta critical")
                            drift_slope_warning = gr.Slider(0.0, 0.5, value=0.02, step=0.005, label="Drift slope warning")
                            drift_slope_critical = gr.Slider(0.0, 0.5, value=0.05, step=0.005, label="Drift slope critical")
                            drift_alert_top_k = gr.Slider(1, 64, value=16, step=1, label="Auto-flag rows")
                        with gr.Accordion("Snapshot Input", open=False):
                            trend_snapshots_file = gr.File(
                                label="Snapshots file (.json/.jsonl/.txt)",
                                file_types=[".json", ".jsonl", ".txt"],
                                type="filepath",
                            )
                            trend_snapshots_text = gr.Textbox(
                                lines=8,
                                label="Snapshots JSON/JSONL (optional)",
                                placeholder='[{"timestamp":"2026-02-12","qubits":{"0":{"gate_error":0.012,"readout_error":0.02,"t1_us":82,"t2_us":61,"fidelity":0.991}}}]',
                            )
                            gr.Markdown("<div class='small-note'>If both are provided, file input is used.</div>")
                        trend_status = gr.Markdown("Upload snapshots and click Analyze drift.")
                        drift_alert_csv_dl = gr.DownloadButton("Download auto-flag CSV")
                        trend_plot = gr.Plot()
                        trend_table = gr.Dataframe(
                            headers=["qubit", "latest", "baseline", "delta"],
                            interactive=False,
                            label="Latest ranking (highest metric risk first)",
                        )
                        drift_alert_status = gr.Markdown("Auto-flag summary: awaiting trend analysis.")
                        drift_alert_table = gr.Dataframe(
                            headers=["qubit", "alert", "latest_risk", "risk_delta", "risk_slope", "triggers"],
                            interactive=False,
                            label="Auto-flag panel",
                        )
                        drift_reco_md = gr.Markdown("Recommendations appear after drift analysis.")

                with gr.Tab("Explain"):
                    with gr.Group(elem_classes=["card"]):
                        gr.Markdown("<div class='section-title'>Explain (GPT-4o)</div>")
                        gr.Markdown("<div class='small-note'>Uses GPT-4o with cost guards. Tip: sample shots first.</div>")
                        explain_btn = gr.Button("Explain", variant="primary")
                        llm_out = gr.Markdown()
                        with gr.Row():
                            dl_md = gr.DownloadButton("Download Explanation (Markdown)")
                            dl_pdf = gr.DownloadButton("Download Explanation (PDF)")

    # init
    def _init_all(n):
        qc, last_counts, selected_gate = _new_sim(n)
        return qc, last_counts, selected_gate

    demo.load(
        fn=_init_all,
        inputs=[n_qubits],
        outputs=[qc_state, last_counts_state, selected_gate_state],
    ).then(
        fn=update_views,
        inputs=[qc_state, last_counts_state, n_qubits],
        outputs=[circuit_html, ket_out, counts_out, probs_out],
    )

    n_qubits.change(
        fn=_on_qubit_count_change,
        inputs=[n_qubits],
        outputs=[qc_state, last_counts_state, selected_gate_state, target, control, cnot_target, status],
    ).then(
        fn=update_views,
        inputs=[qc_state, last_counts_state, n_qubits],
        outputs=[circuit_html, ket_out, counts_out, probs_out],
    )

    reset_btn.click(
        fn=init_or_reset,
        inputs=[n_qubits],
        outputs=[qc_state, last_counts_state, selected_gate_state, status],
    ).then(
        fn=update_views,
        inputs=[qc_state, last_counts_state, n_qubits],
        outputs=[circuit_html, ket_out, counts_out, probs_out],
    )

    gate_H.click(fn=lambda: set_gate("H"), outputs=[selected_gate_state, status])
    gate_T.click(fn=lambda: set_gate("T"), outputs=[selected_gate_state, status])
    gate_Tdg.click(fn=lambda: set_gate("T†"), outputs=[selected_gate_state, status])
    
    gate_X.click(fn=lambda: set_gate("X"), outputs=[selected_gate_state, status])
    gate_Y.click(fn=lambda: set_gate("Y"), outputs=[selected_gate_state, status])
    gate_Z.click(fn=lambda: set_gate("Z"), outputs=[selected_gate_state, status])
    
    gate_sx.click(fn=lambda: set_gate("√X"), outputs=[selected_gate_state, status])
    gate_sz.click(fn=lambda: set_gate("√Z"), outputs=[selected_gate_state, status])
    
    gate_rx_pi.click(fn=lambda: set_gate("RX(π)"), outputs=[selected_gate_state, status])
    gate_rx_pi2.click(fn=lambda: set_gate("RX(π/2)"), outputs=[selected_gate_state, status])
    gate_ry_pi.click(fn=lambda: set_gate("RY(π)"), outputs=[selected_gate_state, status])
    gate_ry_pi2.click(fn=lambda: set_gate("RY(π/2)"), outputs=[selected_gate_state, status])
    gate_rz_pi.click(fn=lambda: set_gate("RZ(π)"), outputs=[selected_gate_state, status])
    gate_rz_pi2.click(fn=lambda: set_gate("RZ(π/2)"), outputs=[selected_gate_state, status])
    
    gate_I.click(fn=lambda: set_gate("I"), outputs=[selected_gate_state, status])
    gate_Idg.click(fn=lambda: set_gate("I"), outputs=[selected_gate_state, status])  # treat I† as I
    
    gate_S.click(fn=lambda: set_gate("S"), outputs=[selected_gate_state, status])
    gate_Sdg.click(fn=lambda: set_gate("S†"), outputs=[selected_gate_state, status])


    apply_gate_btn.click(
        fn=apply_selected_gate,
        inputs=[qc_state, last_counts_state, selected_gate_state, target],
        outputs=[qc_state, last_counts_state, status],
    ).then(
        fn=update_views,
        inputs=[qc_state, last_counts_state, n_qubits],
        outputs=[circuit_html, ket_out, counts_out, probs_out],
    )

    apply_cnot_btn.click(
        fn=apply_cnot,
        inputs=[qc_state, last_counts_state, control, cnot_target],
        outputs=[qc_state, last_counts_state, status],
    ).then(
        fn=update_views,
        inputs=[qc_state, last_counts_state, n_qubits],
        outputs=[circuit_html, ket_out, counts_out, probs_out],
    )

    sample_btn.click(
        fn=sample_shots,
        inputs=[
            qc_state,
            shots,
            noise_preview_enabled,
            noise_readout_scale,
            noise_depolarizing,
            calibration_json,
        ],
        outputs=[last_counts_state, status],
    ).then(
        fn=update_views,
        inputs=[qc_state, last_counts_state, n_qubits],
        outputs=[circuit_html, ket_out, counts_out, probs_out],
    )

    compare_dist_btn.click(
        fn=_ideal_vs_noisy_plot,
        inputs=[
            qc_state,
            shots,
            calibration_json,
            noise_readout_scale,
            noise_depolarizing,
        ],
        outputs=[dist_compare_plot],
    )

    measure_btn.click(
        fn=measure_collapse,
        inputs=[qc_state, shots],
        outputs=[last_counts_state, status],
    ).then(
        fn=update_views,
        inputs=[qc_state, last_counts_state, n_qubits],
        outputs=[circuit_html, ket_out, counts_out, probs_out],
    )

    qasm_dl.click(fn=dl_qasm, inputs=[qc_state, n_qubits], outputs=[qasm_dl])
    qiskit_dl.click(fn=dl_qiskit, inputs=[qc_state, n_qubits], outputs=[qiskit_dl])
    cirq_dl.click(fn=dl_cirq, inputs=[qc_state, n_qubits], outputs=[cirq_dl])
    csv_dl.click(fn=dl_csv, inputs=[qc_state], outputs=[csv_dl])
    skill_dl.click(fn=dl_skill, inputs=[qc_state, n_qubits], outputs=[skill_dl])

    def _dl_synopsys_tcl(
        qc,
        n_qubits,
        rows,
        cols,
        layout_file,
        calibration_text,
        activity_w,
        gate_error_w,
        readout_error_w,
        decoherence_w,
        fidelity_w,
        warning_thr,
        critical_thr,
    ):
        csv_text = to_csv(qc.history)
        weights, thresholds = _metric_controls_to_models(
            activity_w,
            gate_error_w,
            readout_error_w,
            decoherence_w,
            fidelity_w,
            warning_thr,
            critical_thr,
        )
        metrics, _meta = compute_metrics_from_csv(
            csv_text,
            int(n_qubits),
            calibration_json=str(calibration_text or ""),
            state_vector=np.asarray(qc.state, dtype=complex),
            weights=weights,
            thresholds=thresholds,
        )
        qubit_coords, _layout_meta = _resolve_layout_coords(
            layout_file,
            int(n_qubits),
            int(rows),
            int(cols),
        )
        mapping = build_eda_mapping(
            metrics,
            cfg=None,
            qubit_coords=qubit_coords,
        )
        return _write_tmp("quread_risk_synopsys.tcl", to_synopsys_tcl(mapping))

    def _dl_cadence_skill(
        qc,
        n_qubits,
        rows,
        cols,
        layout_file,
        calibration_text,
        activity_w,
        gate_error_w,
        readout_error_w,
        decoherence_w,
        fidelity_w,
        warning_thr,
        critical_thr,
    ):
        csv_text = to_csv(qc.history)
        weights, thresholds = _metric_controls_to_models(
            activity_w,
            gate_error_w,
            readout_error_w,
            decoherence_w,
            fidelity_w,
            warning_thr,
            critical_thr,
        )
        metrics, _meta = compute_metrics_from_csv(
            csv_text,
            int(n_qubits),
            calibration_json=str(calibration_text or ""),
            state_vector=np.asarray(qc.state, dtype=complex),
            weights=weights,
            thresholds=thresholds,
        )
        qubit_coords, _layout_meta = _resolve_layout_coords(
            layout_file,
            int(n_qubits),
            int(rows),
            int(cols),
        )
        mapping = build_eda_mapping(
            metrics,
            cfg=None,
            qubit_coords=qubit_coords,
        )
        return _write_tmp("quread_risk_cadence.il", to_cadence_skill_reliability(mapping))

    explain_btn.click(
        fn=explain_llm,
        inputs=[qc_state, n_qubits, shots, last_explained_hash, explanation_md],
        outputs=[llm_out, last_explained_hash, explanation_md],
    )
    
    def _heat_and_hotspots_from_current(
        qc,
        n_qubits,
        rows,
        cols,
        metric,
        render_mode,
        layout_file,
        calibration_text,
        activity_w,
        gate_error_w,
        readout_error_w,
        decoherence_w,
        fidelity_w,
        warning_thr,
        critical_thr,
        metric_thr,
        focus_qubit,
        top_k,
        ):
        csv_text = to_csv(qc.history)  # must exist from Task 2A
        cfg = HeatmapConfig(rows=int(rows), cols=int(cols))
        weights, thresholds = _metric_controls_to_models(
            activity_w,
            gate_error_w,
            readout_error_w,
            decoherence_w,
            fidelity_w,
            warning_thr,
            critical_thr,
        )
        threshold_value = None if float(metric_thr) <= 0 else float(metric_thr)
        render_choice = str(render_mode or "interactive").strip().lower()
        notes = []
        qubit_coords, layout_meta = _resolve_layout_coords(
            layout_file,
            int(n_qubits),
            int(rows),
            int(cols),
        )

        if render_choice == "interactive":
            if plotly_available():
                fig = make_metric_heatmap_plotly(
                    csv_text=csv_text,
                    n_qubits=int(n_qubits),
                    metric=str(metric),
                    cfg=cfg,
                    calibration_json=str(calibration_text or ""),
                    state_vector=np.asarray(qc.state, dtype=complex),
                    weights=weights,
                    thresholds=thresholds,
                    highlight_threshold=threshold_value,
                    qubit_coords=qubit_coords,
                )
            else:
                fig = make_metric_heatmap(
                    csv_text=csv_text,
                    n_qubits=int(n_qubits),
                    metric=str(metric),
                    cfg=cfg,
                    calibration_json=str(calibration_text or ""),
                    state_vector=np.asarray(qc.state, dtype=complex),
                    weights=weights,
                    thresholds=thresholds,
                    highlight_threshold=threshold_value,
                    qubit_coords=qubit_coords,
                )
                notes.append("Plotly unavailable in this runtime; using static heatmap.")
        else:
            fig = make_metric_heatmap(
                csv_text=csv_text,
                n_qubits=int(n_qubits),
                metric=str(metric),
                cfg=cfg,
                calibration_json=str(calibration_text or ""),
                state_vector=np.asarray(qc.state, dtype=complex),
                weights=weights,
                thresholds=thresholds,
                highlight_threshold=threshold_value,
                qubit_coords=qubit_coords,
            )

        metrics, meta = compute_metrics_from_csv(
            csv_text,
            int(n_qubits),
            calibration_json=str(calibration_text or ""),
            state_vector=np.asarray(qc.state, dtype=complex),
            weights=weights,
            thresholds=thresholds,
        )
        hotspot_rows = _hotspot_rows(
            metrics,
            int(n_qubits),
            int(top_k),
            qubit_coords=qubit_coords,
        )
        note = notes
        if layout_meta.get("source") == "uploaded":
            note.append(
                "Layout map uploaded: "
                f"mapped={int(layout_meta.get('mapped', 0))}, "
                f"fallback={int(layout_meta.get('fallback', 0))}, "
                f"skipped={int(layout_meta.get('skipped', 0))}, "
                f"duplicates={int(layout_meta.get('duplicates', 0))}"
            )
        else:
            note.append("Layout map: using default row-major mapping.")
        skipped = int(meta.get("skipped_rows", 0))
        if skipped:
            note.append(f"Skipped malformed CSV rows: {skipped}")
        calibration_note = str(meta.get("calibration_note", "") or "").strip()
        if calibration_note:
            note.append(calibration_note)
        fidelity_backend = str(meta.get("fidelity_backend", "") or "").strip()
        if fidelity_backend:
            note.append(f"Fidelity backend: {fidelity_backend}")
        summary = " | ".join(note) if note else "Hotspot ranking updated."
        detail_md = _hotspot_detail_markdown(
            metrics,
            meta,
            int(n_qubits),
            int(focus_qubit),
            qubit_coords=qubit_coords,
        )
        detail_fig = _hotspot_detail_plot(metrics, meta, int(n_qubits), int(focus_qubit))
        return fig, summary, hotspot_rows, detail_md, detail_fig

    def _dl_metrics_csv(
        qc,
        n_qubits,
        calibration_text,
        activity_w,
        gate_error_w,
        readout_error_w,
        decoherence_w,
        fidelity_w,
        warning_thr,
        critical_thr,
    ):
        csv_text = to_csv(qc.history)
        weights, thresholds = _metric_controls_to_models(
            activity_w,
            gate_error_w,
            readout_error_w,
            decoherence_w,
            fidelity_w,
            warning_thr,
            critical_thr,
        )
        metrics, _meta = compute_metrics_from_csv(
            csv_text,
            int(n_qubits),
            calibration_json=str(calibration_text or ""),
            state_vector=np.asarray(qc.state, dtype=complex),
            weights=weights,
            thresholds=thresholds,
        )
        return _write_tmp("qubit_metrics.csv", to_metrics_csv(metrics))

    def _trend_from_snapshots(
        qc,
        n_qubits,
        snapshots_file,
        snapshots_text,
        trend_metric_value,
        trend_top_qubits,
        drift_delta_warn,
        drift_delta_crit,
        drift_slope_warn,
        drift_slope_crit,
        drift_alert_rows_max,
        activity_w,
        gate_error_w,
        readout_error_w,
        decoherence_w,
        fidelity_w,
        warning_thr,
        critical_thr,
    ):
        text = _read_uploaded_text(snapshots_file).strip()
        if not text:
            text = str(snapshots_text or "").strip()

        if not text:
            fig, ax = plt.subplots(figsize=(7, 3))
            ax.set_title("Temporal drift")
            ax.text(0.5, 0.5, "Provide calibration snapshots (JSON/JSONL).", ha="center", va="center")
            ax.axis("off")
            fig.tight_layout()
            return (
                fig,
                "No snapshots provided.",
                [],
                "Auto-flag summary: no data.",
                [],
                [],
                "No recommendations available yet. Run drift analysis first.",
            )

        csv_text = to_csv(qc.history)
        weights, thresholds = _metric_controls_to_models(
            activity_w,
            gate_error_w,
            readout_error_w,
            decoherence_w,
            fidelity_w,
            warning_thr,
            critical_thr,
        )

        try:
            series, labels, ranking, meta = compute_metric_trends(
                csv_text,
                int(n_qubits),
                text,
                metric=str(trend_metric_value),
                state_vector=np.asarray(qc.state, dtype=complex),
                weights=weights,
                thresholds=thresholds,
            )
        except Exception as exc:
            fig, ax = plt.subplots(figsize=(7, 3))
            ax.set_title("Temporal drift")
            ax.text(0.5, 0.5, f"Unable to parse snapshots: {exc}", ha="center", va="center")
            ax.axis("off")
            fig.tight_layout()
            return (
                fig,
                f"Drift analysis failed: {exc}",
                [],
                f"Auto-flag summary unavailable: {exc}",
                [],
                [],
                f"Recommendation generation unavailable: {exc}",
            )

        fig = _plot_metric_trends(
            series,
            labels,
            ranking,
            str(meta.get("metric", trend_metric_value)),
            int(trend_top_qubits),
        )
        table_rows = []
        for row in ranking:
            table_rows.append(
                [
                    int(row["qubit"]),
                    round(float(row["latest"]), 6),
                    round(float(row["baseline"]), 6),
                    round(float(row["delta"]), 6),
                ]
            )
        alerts = compute_drift_alerts(
            ranking,
            warning_threshold=float(warning_thr),
            critical_threshold=float(critical_thr),
            delta_warning=float(drift_delta_warn),
            delta_critical=float(drift_delta_crit),
            slope_warning=float(drift_slope_warn),
            slope_critical=float(drift_slope_crit),
        )
        max_rows = max(1, min(int(drift_alert_rows_max), len(alerts)))
        alert_table_rows = []
        for row in alerts[:max_rows]:
            alert_table_rows.append(
                [
                    int(row["qubit"]),
                    str(row["level"]),
                    round(float(row["latest_risk"]), 6),
                    round(float(row["risk_delta"]), 6),
                    round(float(row["risk_slope"]), 6),
                    "; ".join(row["triggers"]) if row["triggers"] else "-",
                ]
            )
        alert_status = _drift_alert_summary(alerts)
        recommendation_md = _drift_recommendations_markdown(
            alerts,
            str(meta.get("metric", trend_metric_value)),
            max_items=6,
        )
        status = (
            f"Snapshots parsed: {int(meta.get('parsed', 0))}"
            f" | Skipped: {int(meta.get('skipped', 0))}"
            f" | Format: {meta.get('format', 'unknown')}"
            f" | Points: {int(meta.get('points', 0))}"
            f" | Metric: {meta.get('metric', trend_metric_value)}"
            f" | Risk mode: {meta.get('risk_mode', 'unknown')}"
        )
        return fig, status, table_rows, alert_status, alert_table_rows, alerts, recommendation_md

    def _dl_drift_alert_csv(alert_rows):
        rows = alert_rows or []
        return _write_tmp("drift_alerts.csv", alerts_to_csv(rows))

    heat_btn.click(
        fn=_heat_and_hotspots_from_current,
        inputs=[
            qc_state,
            n_qubits,
            chip_rows,
            chip_cols,
            heat_metric,
            heat_render_mode,
            layout_csv_file,
            calibration_json,
            w_activity,
            w_gate,
            w_readout,
            w_decoherence,
            w_fidelity,
            thr_warning,
            thr_critical,
            metric_threshold,
            hotspot_focus_q,
            hotspot_top_k,
        ],
        outputs=[heat_plot, hotspot_status, hotspot_table, hotspot_detail_md, hotspot_detail_plot],
    )

    metrics_csv_dl.click(
        fn=_dl_metrics_csv,
        inputs=[
            qc_state,
            n_qubits,
            calibration_json,
            w_activity,
            w_gate,
            w_readout,
            w_decoherence,
            w_fidelity,
            thr_warning,
            thr_critical,
        ],
        outputs=[metrics_csv_dl],
    )

    trend_btn.click(
        fn=_trend_from_snapshots,
        inputs=[
            qc_state,
            n_qubits,
            trend_snapshots_file,
            trend_snapshots_text,
            trend_metric,
            trend_top_k,
            drift_delta_warning,
            drift_delta_critical,
            drift_slope_warning,
            drift_slope_critical,
            drift_alert_top_k,
            w_activity,
            w_gate,
            w_readout,
            w_decoherence,
            w_fidelity,
            thr_warning,
            thr_critical,
        ],
        outputs=[
            trend_plot,
            trend_status,
            trend_table,
            drift_alert_status,
            drift_alert_table,
            drift_alert_rows_state,
            drift_reco_md,
        ],
    )

    drift_alert_csv_dl.click(
        fn=_dl_drift_alert_csv,
        inputs=[drift_alert_rows_state],
        outputs=[drift_alert_csv_dl],
    )

    synopsys_tcl_dl.click(
        fn=_dl_synopsys_tcl,
        inputs=[
            qc_state,
            n_qubits,
            chip_rows,
            chip_cols,
            layout_csv_file,
            calibration_json,
            w_activity,
            w_gate,
            w_readout,
            w_decoherence,
            w_fidelity,
            thr_warning,
            thr_critical,
        ],
        outputs=[synopsys_tcl_dl],
    )

    cadence_skill_dl.click(
        fn=_dl_cadence_skill,
        inputs=[
            qc_state,
            n_qubits,
            chip_rows,
            chip_cols,
            layout_csv_file,
            calibration_json,
            w_activity,
            w_gate,
            w_readout,
            w_decoherence,
            w_fidelity,
            thr_warning,
            thr_critical,
        ],
        outputs=[cadence_skill_dl],
    )

    def dl_explain_md(md_text):
        return _write_tmp("explanation.md", md_text)

    def dl_explain_pdf(md_text):
        fd, path = tempfile.mkstemp(
            prefix="explanation_",
            suffix=".pdf",
            dir=tempfile.gettempdir(),
        )
        os.close(fd)
        md_to_pdf(md_text, path)
        return path

    dl_md.click(fn=dl_explain_md, inputs=[explanation_md], outputs=[dl_md])
    dl_pdf.click(fn=dl_explain_pdf, inputs=[explanation_md], outputs=[dl_pdf])


if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)