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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
# ===== file: skills/workflow_skill_creator/references/cli_script_template.py =====
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""CLI script template for skills that wrap external APIs.

Copy and adapt this pattern when generating a multi-command CLI script for a
new skill. This follows the same structure as clinvar_api.py and screen_api.py.

Key design decisions:
- Uses argparse with subcommands (one per workflow step).
- All subcommands write output to a JSON file via --output.
- Uses stdlib only (urllib, json, argparse) — no requests, no third-party deps.
- Built-in rate limiting with dedicated RateLimitError and retry logic.
"""

import argparse
import json
import sys
import time
from urllib import error as urllib_error
from urllib import parse as urllib_parse
from urllib import request as urllib_request


class RateLimitError(Exception):
  """Raised when the API rate limit is exceeded."""


class MyAPIClient:
  """Client for the Example API with built-in rate limiting.

  Replace with your actual API. Adapt this class as follows:
  1. Set BASE_URL to your API's base URL.
  2. Set REQUESTS_PER_SECOND to the documented rate limit.
  3. Implement domain-specific query methods.
  """

  BASE_URL = 'https://api.example.com/v1'
  REQUESTS_PER_SECOND = 5

  def __init__(self):
    self.delay = 1.0 / self.REQUESTS_PER_SECOND
    self.last_request_time = 0.0

  def _wait_for_rate_limit(self):
    """Blocks until enough time has passed since the last request."""
    elapsed = time.monotonic() - self.last_request_time
    if elapsed < self.delay:
      time.sleep(self.delay - elapsed)

  def _request(self, path, params=None, retries=3):
    """Makes an HTTP GET request with rate limiting and retry logic.

    Args:
      path: URL path relative to BASE_URL (e.g., '/search').
      params: Optional dict of query parameters.
      retries: Number of retry attempts for transient server errors.

    Returns:
      Parsed JSON response as a Python dict/list.

    Raises:
      RateLimitError: If the server responds with HTTP 429.
      RuntimeError: If the request fails after all retries.
    """
    url = f'{self.BASE_URL}{path}'
    if params:
      url = f'{url}?{urllib_parse.urlencode(params)}'

    for attempt in range(retries):
      self._wait_for_rate_limit()
      try:
        req = urllib_request.Request(url)
        req.add_header('Accept', 'application/json')
        with urllib_request.urlopen(req, timeout=30) as response:
          self.last_request_time = time.monotonic()
          return json.loads(response.read().decode('utf-8'))
      except urllib_error.HTTPError as e:
        self.last_request_time = time.monotonic()
        if e.code == 429:
          # Rate limited — exponential backoff before retry
          wait = 2**attempt
          print(
              f'Rate limited (429), retrying in {wait}s '
              f'(attempt {attempt + 1}/{retries})...',
              file=sys.stderr,
          )
          if attempt == retries - 1:
            raise RateLimitError(
                f'HTTP 429 Too Many Requests from {self.BASE_URL}. '
                f'The API rate limit ({self.REQUESTS_PER_SECOND} req/s) has '
                f'been exceeded after {retries} retries.'
            ) from e
          time.sleep(wait)
          continue
        if e.code >= 500:
          # Transient server error — exponential backoff
          wait = 2**attempt
          print(
              f'Server error {e.code}, retrying in {wait}s '
              f'(attempt {attempt + 1}/{retries})...',
              file=sys.stderr,
          )
          if attempt == retries - 1:
            raise RuntimeError(
                f'Server error {e.code} from {url} after {retries} retries.'
            ) from e
          time.sleep(wait)
          continue
        # Non-retriable client error — read the response body for details
        try:
          body = e.read().decode('utf-8', errors='replace')[:1000]
        except OSError:
          body = e.reason
        raise RuntimeError(f'HTTP {e.code} from {url}: {body}') from e
      except urllib_error.URLError as e:
        if attempt == retries - 1:
          raise RuntimeError(
              f'Failed to connect to {url} after {retries} attempts: {e}'
          ) from e
        time.sleep(2**attempt)

  def search(self, query, limit=100):
    """Example search method. Replace with your API's search endpoint."""
    return self._request('/search', params={'q': query, 'limit': limit})

  def get_details(self, item_id):
    """Example detail method. Replace with your API's detail endpoint."""
    return self._request(f'/items/{item_id}')


def write_output(data, output_file):
  """Writes data to a JSON file.

  Args:
    data: The data to serialize (dict or list).
    output_file: Path to the output file.
  """
  try:
    with open(output_file, 'w', encoding='utf-8') as f:
      json.dump(data, f, indent=2)
    print(f'Success! Data written to: {output_file}')
  except (OSError, TypeError) as e:
    print(f'Error writing to file {output_file}: {e}', file=sys.stderr)
    sys.exit(1)


def main():
  parser = argparse.ArgumentParser(description='Example API Wrapper Script')
  subparsers = parser.add_subparsers(dest='command', required=True)

  # --- Subcommand: search ---
  p_search = subparsers.add_parser(
      'search',
      help='Search for items by query',
  )
  p_search.add_argument(
      '--query',
      required=True,
      help='Search query string',
  )
  p_search.add_argument(
      '--limit',
      type=int,
      required=True,
      help='Maximum number of results to return',
  )
  p_search.add_argument(
      '--output',
      required=True,
      help='Output JSON file path',
  )

  # --- Subcommand: details ---
  p_details = subparsers.add_parser(
      'details',
      help='Get detailed information for a specific item',
  )
  p_details.add_argument(
      '--id',
      required=True,
      dest='item_id',
      help='Item ID to retrieve',
  )
  p_details.add_argument(
      '--output',
      required=True,
      help='Output JSON file path',
  )

  args = parser.parse_args()
  client = MyAPIClient()

  if args.command == 'search':
    data = client.search(args.query, limit=args.limit)
  elif args.command == 'details':
    data = client.get_details(args.item_id)
  else:
    print(f'Unknown command: {args.command}', file=sys.stderr)
    sys.exit(1)

  write_output(data, args.output)


if __name__ == '__main__':
  main()

# ===== file: skills/alphafold_database_fetch_and_analyze/scripts/analyze_pae.py =====
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Analyzes Predicted Aligned Error (PAE) and detects domain boundaries."""

# /// script
# requires-python = ">=3.10"
# dependencies = []
# ///

import argparse
import itertools
import json
import os


def find_sub_domains(pae_matrix, distance_cutoff=7.0, min_domain_size=40):
  """Identifies structurally independent sub-domains based on the PAE matrix."""
  n_res = len(pae_matrix)
  domains = []
  current_domain = []

  for i in range(n_res):
    if not current_domain:
      current_domain.append(i)
      continue

    window_size = min(20, len(current_domain))
    recent_res = current_domain[-window_size:]

    pae_sum = sum(pae_matrix[r][i] + pae_matrix[i][r] for r in recent_res)
    avg_pae = pae_sum / (2.0 * window_size)

    if avg_pae < distance_cutoff:
      current_domain.append(i)
    else:
      if len(current_domain) >= min_domain_size:
        domains.append(current_domain)
      current_domain = [i]

  if len(current_domain) >= min_domain_size:
    domains.append(current_domain)

  domain_boundaries = []
  for comp in domains:
    start = comp[0] + 1
    end = comp[-1] + 1
    domain_boundaries.append([start, end])

  return domain_boundaries


def merge_global_domains(boundaries, pae_matrix, merge_cutoff=15.0):
  """Merges sub-domains if the average PAE between them is below cutoff."""
  if not boundaries:
    return []

  if len(boundaries) == 1:
    merged = boundaries
  else:
    merged = [boundaries[0]]

    for i in range(1, len(boundaries)):
      prev_end = merged[-1][1] - 1
      curr_start = boundaries[i][0] - 1

      lookback = max(merged[-1][0] - 1, prev_end - 30)
      lookfwd = min(boundaries[i][1] - 1, curr_start + 30)

      pae_sum = 0
      n_pairs = 0
      for r1 in range(lookback, prev_end + 1):
        for r2 in range(curr_start, lookfwd + 1):
          pae_sum += pae_matrix[r1][r2] + pae_matrix[r2][r1]
          n_pairs += 2

      if n_pairs > 0 and (pae_sum / n_pairs) < merge_cutoff:
        merged[-1][1] = boundaries[i][1]
      else:
        merged.append(boundaries[i])

  filtered_merged = [dom for dom in merged if (dom[1] - dom[0] + 1) > 50]

  return filtered_merged


def analyze_pae(pae_file):
  """Parses a PAE JSON file and calculates structural domain metrics."""
  print(
      "\n[*] Analyzing Predicted Aligned Error (PAE) from"
      f" {os.path.basename(pae_file)}..."
  )
  try:
    with open(pae_file, "r") as f:
      data = json.load(f)[0]

    if "predicted_aligned_error" in data:
      pae = data["predicted_aligned_error"]
    elif "distance" in data:
      pae = data["distance"]
    else:
      print(
          "     [!] Could not locate PAE matrix in JSON keys:"
          f" {list(data.keys())}"
      )
      return

    flat_pae = list(itertools.chain.from_iterable(pae))
    if not flat_pae:
      print("     [!] PAE matrix is empty.")
      return

    mean_pae = sum(flat_pae) / len(flat_pae)
    max_pae = max(flat_pae)
    min_pae = min(flat_pae)
    confident_pairs = sum(1 for p in flat_pae if p < 5.0) / len(flat_pae) * 100

    print(f"  -> PAE Matrix Shape: {len(pae)}x{len(pae[0])}")
    print(f"  -> Mean Error: {mean_pae:.2f} Å")
    print(
        f"  -> Max Error: {max_pae:.2f} Å (suggests max possible distance"
        " between domains)"
    )
    print(f"  -> Min Error: {min_pae:.2f} Å")
    print(
        "  -> Fraction of confident residue pairs (<5Å PAE):"
        f" {confident_pairs:.1f}%"
    )

    sub_domains = find_sub_domains(pae, distance_cutoff=7.0, min_domain_size=40)
    global_domains = merge_global_domains(sub_domains, pae, merge_cutoff=15.0)

    print("\n[*] Domain Boundary Analysis:")
    if not global_domains:
      print("  -> No distinct rigidly-folded domains detected (>50 AAs).")
    else:
      print(
          "  -> Number of distinct Global Domains detected:"
          f" {len(global_domains)}"
      )
      for i, (start, end) in enumerate(global_domains, 1):
        print(
            f"     Domain {i}: residues {start} - {end} (Length:"
            f" {end - start + 1} AAs)"
        )

    print("\n[*] PAE Structural Conclusion:")
    if len(global_domains) == 1:
      conclusion = (
          "The protein consists of a single well-folded, rigid composite"
          " domain."
      )
    elif len(global_domains) > 1:
      conclusion = (
          f"The protein has {len(global_domains)} independently positioned"
          " global domains separated by truly flexible joints."
      )
    else:
      conclusion = (
          "The protein is likely entirely disordered or lacks rigid"
          " tertiary structure."
      )
    print(f"  -> {conclusion}")

    return {
        "pae_file": os.path.basename(pae_file),
        "matrix_shape": f"{len(pae)}x{len(pae[0])}",
        "mean_pae": round(mean_pae, 2),
        "max_pae": round(max_pae, 2),
        "min_pae": round(min_pae, 2),
        "confident_pairs_pct": round(confident_pairs, 1),
        "domains": [
            {"start": s, "end": e, "length": e - s + 1}
            for s, e in global_domains
        ],
        "conclusion": conclusion,
    }

  except (IOError, json.JSONDecodeError) as e:
    print(f"     [!] Failed to analyze PAE file: {e}")
    return None


if __name__ == "__main__":
  parser = argparse.ArgumentParser(
      description=(
          "Analyze PAE matrix and detect domain boundaries from an AlphaFold"
          " PAE JSON file"
      )
  )
  parser.add_argument(
      "pae_file",
      help=(
          "Path to the PAE JSON file (e.g.,"
          " AF-P04637-F1-predicted_aligned_error_v6.json)"
      ),
  )

  args = parser.parse_args()

  analyze_pae(args.pae_file)

# ===== file: skills/alphafold_database_fetch_and_analyze/scripts/analyze_plddt.py =====
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Analyzes pLDDT confidence metrics from a saved AFDB metadata JSON file."""

# /// script
# requires-python = ">=3.10"
# dependencies = []
# ///

import argparse
import json
import sys

CONFIDENT_THRESHOLD = 0.7
MODERATE_THRESHOLD = 0.4
NOTABLE_DISORDER_THRESHOLD = 0.15
MIXED_DISORDER_THRESHOLD = 0.3
MOSTLY_DISORDERED_THRESHOLD = 0.5


def analyze_plddt(metadata_file):
  """Loads an AFDB metadata JSON and analyzes pLDDT metrics."""
  try:
    with open(metadata_file, "r") as f:
      entry = json.load(f)
  except (IOError, json.JSONDecodeError) as e:
    print(f"[!] Error reading metadata file: {e}")
    sys.exit(1)

  return _analyze_entry(entry)


def _analyze_entry(entry):
  """Parses and analyzes pLDDT confidence metrics from the API payload."""
  accession = entry.get("uniprotAccession", "Unknown")
  print(f"\n[*] AlphaFold pLDDT Metrics for Accession: {accession}")
  global_plddt = entry.get("globalMetricValue", 0.0)
  frac_vlow = entry.get("fractionPlddtVeryLow", 0.0)
  frac_low = entry.get("fractionPlddtLow", 0.0)
  frac_conf = entry.get("fractionPlddtConfident", 0.0)
  frac_vhigh = entry.get("fractionPlddtVeryHigh", 0.0)

  print("-" * 65)
  print(f"  -> Overall Global pLDDT   : {global_plddt:.2f}")
  print(f"  -> Fraction Very Low (<50): {frac_vlow:.3f} ({frac_vlow*100:.1f}%)")
  print(f"  -> Fraction Low (50-70)   : {frac_low:.3f} ({frac_low*100:.1f}%)")
  print(f"  -> Fraction Confident     : {frac_conf:.3f} ({frac_conf*100:.1f}%)")
  print(
      f"  -> Fraction Very High     : {frac_vhigh:.3f} ({frac_vhigh*100:.1f}%)"
  )
  print("-" * 65)

  conf_total = frac_conf + frac_vhigh

  print("[*] pLDDT Conclusion:")
  if conf_total >= CONFIDENT_THRESHOLD:
    if frac_vlow > NOTABLE_DISORDER_THRESHOLD:
      conclusion = (
          "Protein is mostly confidently predicted, but contains notable"
          " disordered regions."
      )
    else:
      conclusion = (
          "Protein is confidently predicted and likely fully"
          " ordered/structured."
      )
  elif conf_total >= MODERATE_THRESHOLD:
    if frac_vlow >= MIXED_DISORDER_THRESHOLD:
      conclusion = (
          "Protein has a mixture of confidently predicted structured"
          " domains and significant intrinsically disordered regions."
      )
    else:
      conclusion = (
          "Protein has moderate prediction confidence. Certain regions"
          " might be flexible or poorly predicted."
      )
  else:
    if frac_vlow >= MOSTLY_DISORDERED_THRESHOLD:
      conclusion = (
          "Protein is mostly poorly predicted, likely being highly"
          " intrinsically disordered."
      )
    else:
      conclusion = "Protein prediction is of low confidence overall."
  print(f"  -> {conclusion}")
  print()

  return {
      "uniprot_id": accession,
      "global_plddt": global_plddt,
      "fractions": {
          "very_low": frac_vlow,
          "low": frac_low,
          "confident": frac_conf,
          "very_high": frac_vhigh,
      },
      "conclusion": conclusion,
  }


if __name__ == "__main__":
  parser = argparse.ArgumentParser(
      description="Analyze pLDDT confidence metrics from an AFDB metadata file"
  )
  parser.add_argument(
      "metadata_file",
      help="Path to the metadata JSON file (e.g., AF-P04637-F1-metadata.json)",
  )

  args = parser.parse_args()

  analyze_plddt(args.metadata_file)

# ===== file: skills/alphafold_database_fetch_and_analyze/scripts/fetch_structure.py =====
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Fetches AlphaFold structure files (mmCIF + PAE) for a UniProt ID."""

# /// script
# requires-python = ">=3.10"
# dependencies = [
#   "polite-http",
# ]
# ///

import argparse
import json
import os
import sys
from polite_http import http_client

CLIENT = http_client.HttpClient("https://alphafold.ebi.ac.uk", qps=1.0)


def fetch_structure(uniprot_id, output_dir):
  """Downloads the mmCIF file and PAE JSON for a given UniProt ID from AFDB."""
  uniprot_id = uniprot_id.strip().upper()
  api_url = f"https://alphafold.ebi.ac.uk/api/prediction/{uniprot_id}"
  is_fragment = False

  os.makedirs(output_dir, exist_ok=True)
  print(f"[*] Requesting AlphaFold data for UniProt ID: {uniprot_id}")

  try:
    data = CLIENT.fetch_json(api_url)
  except http_client.HttpError as e:
    if e.status_code == 404:
      print(
          f"\n[!] Error: UniProt ID '{uniprot_id}' was not found in"
          " the AlphaFold Database."
      )
      print(
          "    Please double-check the ID for typos, or verify it"
          " has an AFDB entry."
      )
    else:
      print(f"[!] HTTP error fetching API data: {e}")
    sys.exit(1)

  if not data:
    print(f"[!] No AlphaFold data returned for {uniprot_id}")
    sys.exit(1)

  # The API may return multiple entries (e.g. isoforms) for a single
  # UniProt ID. Prefer the canonical entry whose accession matches exactly.
  entry = None
  for e in data:
    if e.get("uniprotAccession") == uniprot_id:
      entry = e
      break
  # If no canonical entry exists (common for very large proteins like
  # Dystrophin), fall back to the longest available isoform so the user
  # gets the most complete structure.
  if entry is None:
    entry = max(data, key=lambda e: e.get("sequenceEnd", 0))
    entry_acc = entry.get("uniprotAccession", "unknown")
    entry_len = entry.get("sequenceEnd", 0)
    print(
        "[!] WARNING: No canonical AFDB entry found for"
        f" '{uniprot_id}'. Using longest available isoform"
        f" '{entry_acc}' ({entry_len} amino acids) instead."
        " The full-length protein may not be available in AFDB."
    )

  max_seq_len = max((e.get("sequenceEnd", 0) for e in data), default=0)
  if max_seq_len > 2700:
    print(
        f"[!] WARNING: Protein {uniprot_id} is massive"
        f" ({max_seq_len} amino acids). Only the first entry has"
        " been downloaded. The full protein may span many more"
        " fragments in AFDB."
    )
    is_fragment = True

  entry_acc = entry.get("uniprotAccession", uniprot_id)
  metadata_filename = f"AF-{entry_acc}-F1-metadata.json"
  metadata_path = os.path.join(output_dir, metadata_filename)
  with open(metadata_path, "w") as f:
    json.dump(entry, f, indent=2)
  print(f"  -> Saved API metadata to: {metadata_path}")

  cif_url = entry.get("cifUrl")
  pae_url = entry.get("paeDocUrl")

  urls_to_fetch = []
  if cif_url:
    urls_to_fetch.append(cif_url)
  if pae_url:
    urls_to_fetch.append(pae_url)

  success_count = 0

  for url in urls_to_fetch:
    filename = url.split("/")[-1]
    file_path = os.path.join(output_dir, filename)

    print(f"  -> Fetching {filename}...")

    try:
      file_bytes = CLIENT.fetch_bytes(url)
      with open(file_path, "wb") as f:
        f.write(file_bytes)

      print(f"     [+] Saved to: {file_path}")
      success_count += 1

    except http_client.HttpError as e:
      if e.status_code == 404:
        print(f"     [!] Error 404: {filename} not found.")
      else:
        print(f"     [!] Download error: {e}")

  if success_count == 0:
    print(
        f"\n[!] Failed to download any data for {uniprot_id}. Please check"
        " the ID."
    )
    sys.exit(1)
  else:
    print(
        f"\n[*] Successfully downloaded {success_count}/{len(urls_to_fetch)}"
        " files."
    )

  return {
      "uniprot_id": uniprot_id,
      "output_dir": output_dir,
      "is_fragment": is_fragment,
      "files_downloaded": success_count,
      "metadata_file": metadata_path,
  }


if __name__ == "__main__":
  parser = argparse.ArgumentParser(
      description="Download AlphaFold structure files for a UniProt ID"
  )
  parser.add_argument(
      "uniprot_id", help="The UniProt ID (e.g., P04637 or A0A1B0GX81)"
  )
  parser.add_argument(
      "-o",
      "--output-dir",
      help="Output directory to save the files (required)",
      required=True,
  )

  args = parser.parse_args()

  fetch_structure(args.uniprot_id, args.output_dir)

# ===== file: skills/alphagenome_atlas_website_links/scripts/alphagenome_atlas_links.py =====
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""AlphaGenome Atlas Deep-Link & Track Predictions Generator CLI.

Constructs validated deep-links and multi-modality Ref vs. Alt track predictions
for the AlphaGenome Atlas web application
(https://deepmind.google.com/science/alphagenome/atlas).

Subcommands:
  - `variant`: Construct single-variant exploration URLs.
  - `locus`: Construct genomic interval / locus exploration URLs.
  - `table`: Format variant records into a Markdown table with embedded Atlas
  links.
  - `track-predictions`: Construct /atlas/track-predictions comparison chart
  URLs with paired RNA-seq + splicing.
"""

import argparse
from collections.abc import Mapping, Sequence
import dataclasses
import json
import os
import re
import sys
import urllib.parse

from alphagenome.atlas import atlas
from alphagenome.data import genome
import dotenv
import pandas as pd

BASE_ATLAS_URL = "https://deepmind.google.com/science/alphagenome/atlas"
_DEFAULT_INTERGENIC_FLANK_BP = 20_000


@dataclasses.dataclass(frozen=True, kw_only=True)
class VariantLinkConfig:
  """Configuration for a single-variant Atlas URL.

  Attributes:
    variant: Genetic variant identifier in `chr:pos:ref>alt` format.
    biosample: Optional biosample or cell line name filter.
    modalities: Modality layout sections to display in the Atlas UI.
    filter_modalities: Scorer modality filters applied to the query (`f=`).
    tfs: Transcription factor names for ChIP-TF track filtering.
    include_avi: Whether to include the top-level AVI score track.
    extra_pinned: Additional track IDs or tokens to pin into the layout.
  """

  variant: str
  biosample: str | None = None
  modalities: Sequence[str] = ("RNA_SEQ", "DNASE", "CHIP_TF")
  filter_modalities: Sequence[str] = ()
  tfs: Sequence[str] = ()
  include_avi: bool = True
  extra_pinned: Sequence[str] = ()


@dataclasses.dataclass(frozen=True, kw_only=True)
class LocusLinkConfig:
  """Configuration for a locus/interval Atlas URL.

  Attributes:
    interval: Genomic coordinate viewport in `chr:start-end` format.
    biosample: Optional biosample or cell line name filter.
    modalities: Modality layout sections to display in the Atlas UI.
    filter_modalities: Scorer modality filters applied to the query (`f=`).
    tfs: Transcription factor names for ChIP-TF track filtering.
    include_avi: Whether to include the top-level AVI score track.
  """

  interval: str
  biosample: str | None = None
  modalities: Sequence[str] = ("RNA_SEQ", "DNASE", "CHIP_TF")
  filter_modalities: Sequence[str] = ()
  tfs: Sequence[str] = ()
  include_avi: bool = True


@dataclasses.dataclass(frozen=True, kw_only=True)
class GenomicInterval:
  """A genomic coordinate interval.

  Attributes:
    chrom: Chromosome with 'chr' prefix.
    start: 1-based start position (inclusive).
    end: 1-based end position (inclusive).
  """

  chrom: str
  start: int
  end: int

  def __str__(self) -> str:
    return f"{self.chrom}:{self.start}-{self.end}"


@dataclasses.dataclass(frozen=True, kw_only=True)
class GeneInfo:
  """Metadata for a single gene overlapping a genomic region.

  Attributes:
    gene_name: HGNC gene symbol.
    gene_id: Ensembl gene ID (with version).
    strand: Strand ('+' or '-').
    is_mane: Whether this is a MANE Select transcript.
    is_coding: Whether this is protein-coding.
    start: Gene start position.
    end: Gene end position.
  """

  gene_name: str
  gene_id: str
  strand: str
  is_mane: bool
  is_coding: bool
  start: int
  end: int


@dataclasses.dataclass(frozen=True, kw_only=True)
class ScoreRecord:
  """A single track prediction score entry.

  Attributes:
    modality: Scorer modality (e.g. 'RNA_SEQ', 'DNASE').
    track: Resolved track name from the Atlas catalog.
    strand: Strand descriptor for display.
    gene: Gene identifier or 'None' for unstranded modalities.
    score_id: Full score token for the Atlas URL.
  """

  modality: str
  track: str
  strand: str
  gene: str
  score_id: str


def normalize_variant_str(variant_str: str) -> str:
  """Validates and formats variant into chr:pos:ref>alt."""
  v = variant_str.strip()
  if not v.startswith("chr"):
    v = f"chr{v}"
  if ">" not in v:
    raise ValueError(
        f"Variant '{variant_str}' must contain '>' (format: chr:pos:ref>alt)"
    )
  return v


def encode_variant_query(variant_str: str) -> str:
  """URL-encodes variant for Atlas query string (ref%3Ealt)."""
  norm = normalize_variant_str(variant_str)
  return norm.replace(">", "%3E")


def _clean_chrom(chrom_str: str | int) -> str:
  """Ensures chromosome string has chr prefix."""
  c = str(chrom_str).strip()
  return c if c.startswith("chr") else f"chr{c}"


def parse_variant_components(variant: str) -> genome.Variant:
  """Parses a variant string (e.g. chr1:12345:A>G) into a genome.Variant."""
  return genome.Variant.from_str(variant)


def parse_interval(interval: str) -> GenomicInterval:
  """Parses a chr:start-end string into a GenomicInterval."""
  m = re.fullmatch(r"(?:chr)?([0-9A-Za-z]+):([0-9,]+)-([0-9,]+)", interval)
  if not m:
    raise ValueError(
        f"Invalid interval format '{interval}'. Expected 'chr:start-end'."
    )
  return GenomicInterval(
      chrom=_clean_chrom(m.group(1)),
      start=int(m.group(2).replace(",", "")),
      end=int(m.group(3).replace(",", "")),
  )


def _select_mane_preferred(df_rows):
  """Returns the MANE_Select-tagged row if available, otherwise the first row."""
  mane = df_rows[df_rows["tag"].fillna("").str.contains("MANE_Select")]
  return mane.iloc[0] if not mane.empty else df_rows.iloc[0]


def _parse_modality_list(modalities: Sequence[str] | str) -> list[str]:
  """Normalizes modalities input to a list of uppercase modality strings."""
  if isinstance(modalities, str):
    return [m.strip().upper() for m in modalities.split(",") if m.strip()]
  return [m.strip().upper() for m in modalities if m.strip()]


def build_filter_string(
    *,
    biosample: str | None = None,
    modalities: Sequence[str] = (),
    tfs: Sequence[str] = (),
) -> str | None:
  """Builds Atlas filter string (f=) enforcing the mandatory Assay group rule."""
  filter_parts: list[str] = []

  if biosample:
    filter_parts.append(f"BIOSAMPLE_NAME:{biosample}")

  modality_map: Mapping[str, str] = {
      "RNA_SEQ": "RNA-seq",
      "DNASE": "DNase",
      "ATAC": "ATAC-seq",
      "CHIP_TF": "ChIP-TF",
      "CHIP_HISTONE": "ChIP-Histone",
      "CAGE": "CAGE",
      "PROCAP": "PRO-cap",
      "POLYADENYLATION": "Polyadenylation",
      "SPLICE_JUNCTIONS": "Splice junctions",
      "SPLICE_SITE_USAGE": "Splice site usage",
  }

  for mod in modalities:
    mod_upper = mod.upper()
    display_name = modality_map.get(mod_upper, mod)
    filter_parts.append(f"SCORER_MODALITY:{display_name}")

  for tf in tfs:
    filter_parts.append(f"ASSAY_TRANSCRIPTOR_FACTOR:{tf}")

  return ",".join(filter_parts) if filter_parts else None


def build_layout_items(
    *,
    include_avi: bool = True,
    modalities: Sequence[str] = (),
    pinned_tracks: Sequence[str] = (),
) -> str:
  """Builds Atlas layout items (lItems=)."""
  items: list[str] = []

  if include_avi:
    items.append("avi")

  for mod in modalities:
    mod_upper = mod.upper()
    items.append(f"section:{mod_upper}")

  for pinned in pinned_tracks:
    items.append(pinned)

  return ",".join(items) if items else "avi"


def _get_tf_modality_filter_str(
    *,
    biosample: str | None,
    filter_modalities: Sequence[str],
    tfs: Sequence[str],
) -> str | None:
  """Computes the filter string (f=) enforcing the mandatory Assay group rule.

  When TF filters are present, RNA_SEQ and DNASE modalities are auto-included to
  satisfy the Atlas Assay-group OR-logic requirement (see SKILL §2).

  Args:
    biosample: Optional biosample name.
    filter_modalities: Modality filters to apply.
    tfs: Transcription factor filters to apply.

  Returns:
    Formatted Atlas filter string, or None if no filters are active.
  """
  active_mods = list(filter_modalities)
  if tfs:
    for required in ("RNA_SEQ", "DNASE"):
      if required not in active_mods:
        active_mods.append(required)

  return build_filter_string(
      biosample=biosample,
      modalities=active_mods,
      tfs=tfs,
  )


def build_variant_url(config: VariantLinkConfig) -> str:
  """Builds full AlphaGenome Atlas URL for a single variant."""
  norm_var = normalize_variant_str(config.variant)
  l_items = build_layout_items(
      include_avi=config.include_avi,
      modalities=config.modalities,
      pinned_tracks=config.extra_pinned,
  )

  query: dict[str, str] = {
      "q": norm_var,
      "m": "variant",
      "lItems": l_items,
  }
  f_str = _get_tf_modality_filter_str(
      biosample=config.biosample,
      filter_modalities=config.filter_modalities,
      tfs=config.tfs,
  )
  if f_str:
    query["f"] = f_str

  return f"{BASE_ATLAS_URL}?" + urllib.parse.urlencode(
      query, quote_via=urllib.parse.quote, safe=":,-"
  )


def build_locus_url(config: LocusLinkConfig) -> str:
  """Builds full AlphaGenome Atlas URL for a genomic interval."""
  interval = config.interval.strip()
  if not interval.startswith("chr"):
    interval = f"chr{interval}"

  l_items = build_layout_items(
      include_avi=config.include_avi,
      modalities=config.modalities,
  )

  query: dict[str, str] = {
      "q": interval,
      "m": "locus",
      "lItems": l_items,
  }
  f_str = _get_tf_modality_filter_str(
      biosample=config.biosample,
      filter_modalities=config.filter_modalities,
      tfs=config.tfs,
  )
  if f_str:
    query["f"] = f_str

  return f"{BASE_ATLAS_URL}?" + urllib.parse.urlencode(
      query, quote_via=urllib.parse.quote, safe=":,-"
  )


def build_table_from_records(
    records: Sequence[Mapping[str, object]],
    *,
    biosample: str | None = None,
) -> str:
  """Formats variant records into a Markdown table with embedded Atlas links."""
  lines: list[str] = [
      (
          "| Rank | Variant | AVI Phred | Raw Score | Top Modality | Atlas"
          " Deep-Link |"
      ),
      "| :--- | :--- | :--- | :--- | :--- | :--- |",
  ]

  for idx, rec in enumerate(records, start=1):
    variant_str = str(rec.get("variant", ""))
    phred_val = rec.get("avi_phred", rec.get("phred", ""))
    raw_val = rec.get("avi_raw", rec.get("raw_score", ""))
    top_mod = rec.get("top_modality", rec.get("top_feature", "N/A"))

    phred_display = f"**{float(phred_val):.2f}**" if phred_val else "N/A"
    raw_display = f"{float(raw_val):.4f}" if raw_val else "N/A"

    if variant_str:
      url = build_variant_url(
          VariantLinkConfig(
              variant=variant_str,
              biosample=biosample,
          )
      )
      link_display = f"[View in Atlas]({url})"
    else:
      link_display = "N/A"

    lines.append(
        f"| {idx} | `{variant_str}` | {phred_display} | {raw_display} |"
        f" `{top_mod}` | {link_display} |"
    )

  return "\n".join(lines)


# ------------------------------------------------------------------------------
# Track Predictions & GENCODE Splice Junction Resolution (predict subcommand)
# ------------------------------------------------------------------------------


def _get_authenticated_atlas_client():
  """Loads .env and initializes authenticated AlphaGenome Atlas client."""
  dotenv.load_dotenv(os.path.expanduser("~/.env"))

  api_key = os.environ.get("ALPHAGENOME_API_KEY")
  if not api_key:
    print(
        "Error: ALPHAGENOME_API_KEY is not set.\n\nThe 'predict' subcommand"
        " connects to the AlphaGenome Atlas database to resolve\nexact"
        " experimental track metadata and splice junction coordinates.\n\nTo"
        " set up your API key:\n  1. Retrieve your key and add it to ~/.env:\n "
        '    echo "ALPHAGENOME_API_KEY=<your_key>" >> ~/.env\n  2. Refer to'
        " the 'credentials' skill for the safe credentials protocol,\n     or"
        " register for an API key at"
        " https://deepmind.google.com/science/alphagenome/.\n",
        file=sys.stderr,
    )
    sys.exit(1)

  return atlas.create(api_key=api_key)


GTF_URL = (
    "https://storage.googleapis.com/alphagenome/reference/gencode/"
    "hg38/gencode.v46.annotation.gtf.gz.feather"
)


def load_gtf_dataframe(custom_path: str | None = None):
  """Loads GENCODE v46 GTF annotations, downloading and caching if needed."""
  path = custom_path or os.environ.get("ALPHAGENOME_GTF_PATH")
  if path and os.path.exists(path):
    print(f"Loading GTF from {path}...")
    return pd.read_feather(path)

  cache_dir = os.path.expanduser("~/.cache/alphagenome")
  cache_path = os.path.join(cache_dir, "gencode.v46.annotation.gtf.gz.feather")
  if os.path.exists(cache_path):
    print(f"Loading GTF from cache {cache_path}...")
    return pd.read_feather(cache_path)

  target_url = path or GTF_URL
  print(f"Loading GTF from {target_url}...")
  try:
    df = pd.read_feather(target_url)
    try:
      os.makedirs(cache_dir, exist_ok=True)
      df.to_feather(cache_path)
    except Exception:
      pass
    return df
  except Exception as e:
    raise RuntimeError(
        f"Failed to load GENCODE v46 GTF annotations from {target_url}: {e}"
    ) from e


def _resolve_locus(
    *,
    gene: str | None,
    gene_id: str | None,
    interval: str | None,
    variant: genome.Variant | None,
    gtf_df,
) -> tuple[GenomicInterval, object | None]:
  """Resolves the genomic interval and target gene from inputs.

  Resolution priority: gene/gene_id > explicit interval > variant overlap.

  Args:
    gene: Gene symbol (e.g. 'BRCA1').
    gene_id: Ensembl gene ID.
    interval: Explicit interval string.
    variant: Parsed genome.Variant, or None.
    gtf_df: GENCODE v46 GTF DataFrame.

  Returns:
    Tuple of (GenomicInterval, target_gene_row or None).

  Raises:
    ValueError: If no input provides enough information to resolve a locus.
  """
  if gene or gene_id:
    return _resolve_locus_from_gene(
        gene=gene,
        gene_id=gene_id,
        interval=interval,
        gtf_df=gtf_df,
    )
  if interval:
    return parse_interval(interval), None
  if variant is not None:
    return _resolve_locus_from_variant(
        variant=variant,
        gtf_df=gtf_df,
    )
  raise ValueError("Must provide at least one of variant, gene, or interval.")


def _resolve_locus_from_gene(
    *,
    gene: str | None,
    gene_id: str | None,
    interval: str | None,
    gtf_df,
) -> tuple[GenomicInterval, object]:
  """Resolves locus from a gene symbol or Ensembl ID."""
  if gene_id:
    matches = gtf_df[gtf_df["gene_id"].str.startswith(gene_id.split(".")[0])]
  else:
    matches = gtf_df[gtf_df["gene_name"].str.upper() == gene.upper()]

  if matches.empty:
    raise ValueError(f"Gene '{gene or gene_id}' not found in GENCODE v46 GTF.")

  target_gene_row = _select_mane_preferred(matches)
  chrom = target_gene_row["Chromosome"]

  if interval:
    return parse_interval(interval), target_gene_row

  return (
      GenomicInterval(
          chrom=chrom,
          start=int(matches["Start"].min()),
          end=int(matches["End"].max()),
      ),
      target_gene_row,
  )


def _resolve_locus_from_variant(
    *,
    variant: genome.Variant,
    gtf_df,
) -> tuple[GenomicInterval, object | None]:
  """Resolves locus by overlapping variant position with gene annotations."""
  chrom = variant.chromosome
  var_pos = variant.position
  c_df = gtf_df[gtf_df["Chromosome"] == chrom]
  overlapping = c_df[(c_df["Start"] <= var_pos) & (c_df["End"] >= var_pos)]

  if not overlapping.empty:
    target_gene_row = _select_mane_preferred(overlapping)
    gene_all = c_df[c_df["gene_id"] == target_gene_row["gene_id"]]
    return (
        GenomicInterval(
            chrom=chrom,
            start=int(gene_all["Start"].min()),
            end=int(gene_all["End"].max()),
        ),
        target_gene_row,
    )

  return (
      GenomicInterval(
          chrom=chrom,
          start=max(1, var_pos - _DEFAULT_INTERGENIC_FLANK_BP),
          end=var_pos + _DEFAULT_INTERGENIC_FLANK_BP,
      ),
      None,
  )


def _collect_overlapping_genes(
    gtf_df,
    interval: GenomicInterval,
) -> tuple[list[GeneInfo], list[GeneInfo]]:
  """Finds genes overlapping an interval, split and ranked by strand."""
  c_df = gtf_df[gtf_df["Chromosome"] == interval.chrom]
  in_region = c_df[
      (c_df["Feature"] == "gene")
      & (c_df["Start"] <= interval.end)
      & (c_df["End"] >= interval.start)
  ]
  if in_region.empty:
    in_region = c_df[
        (c_df["Start"] <= interval.end) & (c_df["End"] >= interval.start)
    ]

  unique_genes = in_region.drop_duplicates(subset=["gene_id"])
  positive_genes: list[GeneInfo] = []
  negative_genes: list[GeneInfo] = []

  for _, g in unique_genes.iterrows():
    info = GeneInfo(
        gene_name=g.get("gene_name") or g["gene_id"],
        gene_id=g["gene_id"],
        strand=g["Strand"],
        is_mane="MANE_Select" in str(g.get("tag", "")),
        is_coding=g.get("gene_type") == "protein_coding",
        start=int(g["Start"]),
        end=int(g["End"]),
    )
    if info.strand == "+":
      positive_genes.append(info)
    elif info.strand == "-":
      negative_genes.append(info)

  rank_key = lambda x: (x.is_mane, x.is_coding, x.end - x.start)
  positive_genes.sort(key=rank_key, reverse=True)
  negative_genes.sort(key=rank_key, reverse=True)
  return positive_genes, negative_genes


def _pick_target_gene_id(
    target_gene_row,
    positive_genes: Sequence[GeneInfo],
    negative_genes: Sequence[GeneInfo],
) -> str | None:
  """Picks the best target gene ID from available sources."""
  if target_gene_row is not None:
    return target_gene_row["gene_id"]
  if positive_genes:
    return positive_genes[0].gene_id
  if negative_genes:
    return negative_genes[0].gene_id
  return None


def _junction_from_exon_index(gene_exons, idx: int) -> tuple[int, int]:
  """Returns junction boundaries for a variant within the exon at idx."""
  n = len(gene_exons)
  if 0 < idx < n - 1:
    return (
        int(gene_exons.iloc[idx - 1]["End"]),
        int(gene_exons.iloc[idx + 1]["Start"]),
    )
  if idx == 0:
    return int(gene_exons.iloc[0]["End"]), int(gene_exons.iloc[1]["Start"])
  return int(gene_exons.iloc[-2]["End"]), int(gene_exons.iloc[-1]["Start"])


def _find_junction_for_position(gene_exons, var_pos: int) -> tuple[int, int]:
  """Finds the splice junction flanking a variant position."""
  for i, (_, ex) in enumerate(gene_exons.iterrows()):
    if int(ex["Start"]) <= var_pos <= int(ex["End"]):
      return _junction_from_exon_index(gene_exons, i)

  for i in range(len(gene_exons) - 1):
    e1 = gene_exons.iloc[i]
    e2 = gene_exons.iloc[i + 1]
    if int(e1["End"]) < var_pos < int(e2["Start"]):
      return int(e1["End"]), int(e2["Start"])

  return int(gene_exons.iloc[0]["End"]), int(gene_exons.iloc[1]["Start"])


def _resolve_splice_junction(
    *,
    gtf_df,
    chrom: str,
    var_pos: int,
    target_gene_row,
    positive_genes: Sequence[GeneInfo],
    negative_genes: Sequence[GeneInfo],
) -> tuple[int | None, int | None]:
  """Resolves splice junction boundaries nearest to a variant position."""
  target_gid = _pick_target_gene_id(
      target_gene_row, positive_genes, negative_genes
  )
  if target_gid is None:
    return None, None

  c_df = gtf_df[gtf_df["Chromosome"] == chrom]
  target_tid = (
      target_gene_row.get("transcript_id")
      if target_gene_row is not None
      else None
  )

  if target_tid:
    gene_exons = c_df[
        (c_df["transcript_id"] == target_tid) & (c_df["Feature"] == "exon")
    ].sort_values("Start")
  else:
    gene_exons = (
        c_df[(c_df["gene_id"] == target_gid) & (c_df["Feature"] == "exon")]
        .sort_values("Start")
        .drop_duplicates(subset=["Start", "End"])
    )

  if len(gene_exons) < 2:
    return None, None

  return _find_junction_for_position(gene_exons, var_pos)


def _resolve_tracks_from_catalog(
    *,
    requested_modalities: Sequence[str],
    biosample: str,
    tf: str,
) -> dict[str, str]:
  """Resolves track names from the Atlas API scorer metadata catalog."""
  client = _get_authenticated_atlas_client()
  scorer_map = client.scorer_metadata()
  resolved: dict[str, str] = {}
  for scorer_name, s_meta in scorer_map.items():
    df_meta = s_meta.track_metadata
    if df_meta is None or df_meta.empty:
      continue
    if scorer_name.endswith("_ACTIVE"):
      continue
    if scorer_name not in requested_modalities:
      continue
    if scorer_name in resolved:
      continue
    for _, row in df_meta.iterrows():
      t_name = str(row.get("name", ""))
      b_name = str(row.get("biosample_name", ""))
      ont_id = str(row.get("ontology_curie", ""))
      if scorer_name == "CHIP_TF":
        tf_match = tf.upper() in t_name.upper()
        bio_match = (
            not biosample
            or biosample.lower() in b_name.lower()
            or biosample.lower() in t_name.lower()
        )
        if tf_match and (bio_match or "CHIP_TF" not in resolved):
          resolved["CHIP_TF"] = t_name
      else:
        if (
            biosample.lower() in b_name.lower()
            or biosample.lower() in t_name.lower()
            or biosample.lower() in ont_id.lower()
        ):
          resolved[scorer_name] = t_name
          break
  return resolved


def _build_score_tokens(
    *,
    target_variant: str,
    requested_modalities: Sequence[str],
    resolved_tracks: Mapping[str, str],
    target_gene_row,
    positive_genes: Sequence[GeneInfo],
    negative_genes: Sequence[GeneInfo],
    interval: GenomicInterval,
    junction_start: int | None,
    junction_end: int | None,
) -> tuple[list[str], list[ScoreRecord]]:
  """Builds score tokens and records for track prediction URLs."""
  tokens: list[str] = []
  records: list[ScoreRecord] = []
  gene_id = (
      _pick_target_gene_id(target_gene_row, positive_genes, negative_genes)
      or "0"
  )

  for mod in requested_modalities:
    track_name = resolved_tracks.get(mod)
    if not track_name:
      continue

    if mod == "SPLICE_JUNCTIONS":
      start = junction_start if junction_start is not None else interval.start
      end = junction_end if junction_end is not None else interval.end
      token = (
          f"{target_variant}:SPLICE_JUNCTIONS:{track_name}"
          f":Unstranded:{gene_id}:{start}:{end}"
      )
      tokens.append(token)
      records.append(
          ScoreRecord(
              modality="SPLICE_JUNCTIONS",
              track=track_name,
              strand="Gene (Junction)",
              gene=gene_id,
              score_id=token,
          )
      )

    elif mod == "RNA_SEQ":
      if positive_genes:
        g = positive_genes[0]
        token = (
            f"{target_variant}:RNA_SEQ:{track_name}:Unstranded:{g.gene_id}:0:0"
        )
        tokens.append(token)
        records.append(
            ScoreRecord(
                modality="RNA_SEQ (+ strand)",
                track=track_name,
                strand="+ (Forward)",
                gene=f"{g.gene_name} ({g.gene_id})",
                score_id=token,
            )
        )
      if negative_genes:
        g = negative_genes[0]
        token = (
            f"{target_variant}:RNA_SEQ:{track_name}:Unstranded:{g.gene_id}:0:0"
        )
        tokens.append(token)
        records.append(
            ScoreRecord(
                modality="RNA_SEQ (- strand)",
                track=track_name,
                strand="- (Reverse)",
                gene=f"{g.gene_name} ({g.gene_id})",
                score_id=token,
            )
        )

    elif mod in (
        "DNASE",
        "ATAC",
        "CHIP_TF",
        "CHIP_HISTONE",
        "CAGE",
        "PROCAP",
    ):
      token = f"{target_variant}:{mod}:{track_name}:Unstranded:None:None:None"
      tokens.append(token)
      records.append(
          ScoreRecord(
              modality=mod,
              track=track_name,
              strand="Unstranded",
              gene="None",
              score_id=token,
          )
      )

  return tokens, records


def generate_track_prediction_link(
    *,
    variant: str | None = None,
    gene: str | None = None,
    gene_id: str | None = None,
    interval: str | None = None,
    biosample: str = "Muscle_Skeletal",
    modalities: Sequence[str] | str = (
        "SPLICE_JUNCTIONS",
        "RNA_SEQ",
        "DNASE",
        "CHIP_TF",
    ),
    tf: str = "CTCF",
    tp_renames: str | None = None,
    tp_legend_title: str | None = None,
    gtf_path: str | None = None,
) -> dict[str, object]:
  """Constructs Atlas track prediction deep-links and resolves locus structures.

  Args:
    variant: Variant in chr:pos:ref>alt format.
    gene: Target gene symbol.
    gene_id: Ensembl gene ID.
    interval: Explicit genomic interval viewport (chr:start-end).
    biosample: Target biosample or tissue name.
    modalities: Modalities to include (comma-separated string or sequence).
    tf: Transcription factor name for ChIP-TF tracks.
    tp_renames: Custom track rename overrides for the URL.
    tp_legend_title: Custom legend title for the track prediction card.
    gtf_path: Path or URL to the GTF feather file.

  Returns:
    Dict with 'url', 'interval', 'variant', 'target_gene',
    'positive_strand_genes', 'negative_strand_genes', and 'scores'.
  """
  gtf_df = load_gtf_dataframe(gtf_path)
  requested_modalities = _parse_modality_list(modalities)
  parsed_var = parse_variant_components(variant) if variant else None

  locus, target_gene_row = _resolve_locus(
      gene=gene,
      gene_id=gene_id,
      interval=interval,
      variant=parsed_var,
      gtf_df=gtf_df,
  )

  positive_genes, negative_genes = _collect_overlapping_genes(gtf_df, locus)

  junction_start, junction_end = None, None
  if "SPLICE_JUNCTIONS" in requested_modalities and parsed_var is not None:
    junction_start, junction_end = _resolve_splice_junction(
        gtf_df=gtf_df,
        chrom=locus.chrom,
        var_pos=parsed_var.position,
        target_gene_row=target_gene_row,
        positive_genes=positive_genes,
        negative_genes=negative_genes,
    )

  resolved_tracks = _resolve_tracks_from_catalog(
      requested_modalities=requested_modalities,
      biosample=biosample,
      tf=tf,
  )

  target_var = variant or (
      f"{locus.chrom}:{locus.start + (locus.end - locus.start) // 2}:A>G"
  )
  score_tokens, score_records = _build_score_tokens(
      target_variant=target_var,
      requested_modalities=requested_modalities,
      resolved_tracks=resolved_tracks,
      target_gene_row=target_gene_row,
      positive_genes=positive_genes,
      negative_genes=negative_genes,
      interval=locus,
      junction_start=junction_start,
      junction_end=junction_end,
  )

  l_items_str = build_layout_items(
      include_avi=True,
      modalities=requested_modalities,
  )

  query_dict: dict[str, str] = {
      "q": variant or str(locus),
      "m": "variant" if variant else "locus",
      "lItems": l_items_str,
      "scores": ",".join(score_tokens),
      "i": str(locus),
  }
  if tp_renames:
    query_dict["tpRenames"] = tp_renames
  if tp_legend_title:
    query_dict["tpLegendTitle"] = tp_legend_title

  final_url = f"{BASE_ATLAS_URL}/track-predictions?" + urllib.parse.urlencode(
      query_dict, quote_via=urllib.parse.quote, safe=":,-"
  )

  return {
      "url": final_url,
      "interval": str(locus),
      "variant": variant,
      "target_gene": (
          target_gene_row["gene_name"] if target_gene_row is not None else None
      ),
      "positive_strand_genes": [dataclasses.asdict(g) for g in positive_genes],
      "negative_strand_genes": [dataclasses.asdict(g) for g in negative_genes],
      "scores": [dataclasses.asdict(r) for r in score_records],
  }


def main() -> None:
  parser = argparse.ArgumentParser(
      description=(
          "AlphaGenome Atlas Deep-Link & Track Predictions Generator CLI"
      ),
      formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  )
  subparsers = parser.add_subparsers(dest="subcommand", required=True)

  # Subcommand: variant
  p_var = subparsers.add_parser(
      "variant",
      help="Generate an AlphaGenome Atlas exploration URL for a single variant",
  )
  p_var.add_argument("variant", help="Variant in chr:pos:ref>alt format")
  p_var.add_argument(
      "--biosample",
      "-b",
      help="Biosample or cell line name (e.g. K562, HepG2, Muscle_Skeletal)",
  )
  p_var.add_argument(
      "--modalities",
      "-m",
      default="RNA_SEQ,DNASE,CHIP_TF",
      help="Comma-separated modalities to include in layout",
  )
  p_var.add_argument(
      "--tf",
      dest="tfs",
      action="append",
      default=[],
      help="Transcription factor names for ChIP-TF tracks (e.g. GATA1, CTCF)",
  )
  p_var.add_argument(
      "--no_avi",
      action="store_true",
      help="Exclude top-level AVI score track",
  )

  # Subcommand: locus
  p_loc = subparsers.add_parser(
      "locus",
      help=(
          "Generate an AlphaGenome Atlas locus exploration URL for an interval"
      ),
  )
  p_loc.add_argument(
      "interval",
      help="Genomic coordinate interval (e.g. chr11:5288500-5290500)",
  )
  p_loc.add_argument(
      "--biosample",
      "-b",
      help="Biosample or cell line filter",
  )
  p_loc.add_argument(
      "--modalities",
      "-m",
      default="RNA_SEQ,DNASE,CHIP_TF",
      help="Comma-separated modalities to include",
  )
  p_loc.add_argument(
      "--tf",
      dest="tfs",
      action="append",
      default=[],
      help="Transcription factors for ChIP-TF filters",
  )
  p_loc.add_argument(
      "--no_avi",
      action="store_true",
      help="Exclude top-level AVI score track",
  )

  # Subcommand: table
  p_tab = subparsers.add_parser(
      "table",
      help=(
          "Format variant records or a JSON file into a Markdown table with"
          " embedded Atlas links"
      ),
  )
  p_tab.add_argument(
      "--input",
      "-i",
      help="Path to JSON file containing variant records",
  )
  p_tab.add_argument(
      "--variant",
      "-v",
      action="append",
      default=[],
      help="Variant string(s) to include in table",
  )
  p_tab.add_argument(
      "--biosample",
      "-b",
      help="Optional biosample filter to attach to links",
  )

  # Subcommand: track-predictions (comparison URLs)
  p_pred = subparsers.add_parser(
      "track-predictions",
      help=(
          "Construct /atlas/track-predictions comparison chart URLs with paired"
          " RNA-seq + splicing"
      ),
  )
  p_pred.add_argument(
      "--variant",
      "-v",
      help="Variant string in chr:pos:ref>alt format",
  )
  p_pred.add_argument(
      "--gene",
      "-g",
      help="Target gene symbol (e.g. CAPN3)",
  )
  p_pred.add_argument(
      "--gene_id",
      help="Target Ensembl gene ID (e.g. ENSG00000092529.26)",
  )
  p_pred.add_argument(
      "--interval",
      "--region",
      "-i",
      dest="interval",
      help="Genomic interval viewport in chr:start-end format",
  )
  p_pred.add_argument(
      "--biosample",
      "-b",
      default="Muscle_Skeletal",
      help=(
          "Target biosample or tissue query (e.g. Muscle_Skeletal, K562,"
          " Whole_Blood)"
      ),
  )
  p_pred.add_argument(
      "--modalities",
      "-m",
      default="SPLICE_JUNCTIONS,RNA_SEQ,DNASE,CHIP_TF",
      help=(
          "Comma-separated modalities to include (SPLICE_JUNCTIONS, RNA_SEQ,"
          " DNASE, ATAC, CHIP_TF)"
      ),
  )
  p_pred.add_argument(
      "--tf",
      default="CTCF",
      help="Transcription factor name for ChIP-TF tracks (e.g. CTCF, GATA1)",
  )
  p_pred.add_argument(
      "--rename",
      "--tp_renames",
      dest="tp_renames",
      help="Custom track rename overrides (e.g. ScoreId:CustomTitle)",
  )
  p_pred.add_argument(
      "--legend_title",
      "--tp_legend_title",
      dest="tp_legend_title",
      help="Custom legend title for the track prediction card",
  )
  p_pred.add_argument(
      "--gtf_path",
      help=(
          "Path or URL to the GTF feather file (defaults to"
          " $ALPHAGENOME_GTF_PATH or the public GCS URL)"
      ),
  )
  p_pred.add_argument(
      "--format",
      choices=["table", "json", "url"],
      default="table",
      help="Output format",
  )

  args = parser.parse_args()

  def _parse_modalities(raw: str) -> list[str]:
    return [m.strip() for m in raw.split(",") if m.strip()]

  if args.subcommand == "variant":
    modalities = _parse_modalities(args.modalities)
    config = VariantLinkConfig(
        variant=args.variant,
        biosample=args.biosample,
        modalities=modalities,
        tfs=args.tfs,
        include_avi=not args.no_avi,
    )
    url = build_variant_url(config)
    print(url)

  elif args.subcommand == "locus":
    modalities = _parse_modalities(args.modalities)
    config = LocusLinkConfig(
        interval=args.interval,
        biosample=args.biosample,
        modalities=modalities,
        tfs=args.tfs,
        include_avi=not args.no_avi,
    )
    url = build_locus_url(config)
    print(url)

  elif args.subcommand == "table":
    records: list[dict[str, object]] = []
    if args.input:
      with open(args.input, "r", encoding="utf-8") as f:
        data = json.load(f)
        if isinstance(data, list):
          records.extend(data)
        elif isinstance(data, dict):
          records.append(data)
    for v in args.variant:
      records.append({"variant": v})

    if not records:
      print(
          "Error: No variants provided via --input or --variant.",
          file=sys.stderr,
      )
      sys.exit(1)

    table_md = build_table_from_records(
        records,
        biosample=args.biosample,
    )
    print(table_md)

  elif args.subcommand == "track-predictions":
    try:
      result = generate_track_prediction_link(
          variant=args.variant,
          gene=args.gene,
          gene_id=args.gene_id,
          interval=args.interval,
          biosample=args.biosample,
          modalities=args.modalities,
          tf=args.tf,
          tp_renames=args.tp_renames,
          tp_legend_title=args.tp_legend_title,
          gtf_path=args.gtf_path,
      )
    except Exception as e:
      print(f"Error: {e}", file=sys.stderr)
      sys.exit(1)

    if args.format == "url":
      print(result["url"])
      return

    if args.format == "json":
      print(json.dumps(result, indent=2))
      return

    print("\n### AlphaGenome Atlas Track Predictions Deep-Link")
    print(f"\n**Generated URL**:\n{result['url']}\n")
    print(f"**Genomic Interval Viewport (`i`)**: `{result['interval']}`")
    if result["variant"]:
      print(f"**Target Variant (`q`)**: `{result['variant']}`")
    if result["target_gene"]:
      print(f"**Target Gene**: `{result['target_gene']}`")
    print()

    positive_genes = result["positive_strand_genes"]
    negative_genes = result["negative_strand_genes"]
    chrom = str(result["interval"]).split(":", maxsplit=1)[0]

    print("#### Overlapping Genes in Interval:")
    print(f"- **(+) Forward Strand Genes ({len(positive_genes)})**:")
    for g in positive_genes[:5]:
      mane_tag = " [MANE Select]" if g["is_mane"] else ""
      print(
          f"  - {g['gene_name']} ({g['gene_id']}){mane_tag}:"
          f" `{chrom}:{g['start']}-{g['end']}`"
      )
    if len(positive_genes) > 5:
      print(f"  - ... and {len(positive_genes) - 5} more (+)-strand genes")

    print(f"- **(-) Reverse Strand Genes ({len(negative_genes)})**:")
    for g in negative_genes[:5]:
      mane_tag = " [MANE Select]" if g["is_mane"] else ""
      print(
          f"  - {g['gene_name']} ({g['gene_id']}){mane_tag}:"
          f" `{chrom}:{g['start']}-{g['end']}`"
      )
    if len(negative_genes) > 5:
      print(f"  - ... and {len(negative_genes) - 5} more (-)-strand genes")
    print()

    print("#### Composed Track Prediction Scores (`scores`):")
    print("| Modality | Strand | Track Name | Gene ID / Target |")
    print("| :--- | :--- | :--- | :--- |")
    for r in result["scores"]:
      print(
          f"| `{r['modality']}` | {r['strand']} | `{r['track']}` |"
          f" {r['gene']} |"
      )
    print()


if __name__ == "__main__":
  main()

# ===== file: skills/alphagenome_single_variant_analysis/scripts/analyze_ism.py =====
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

r"""Generate ISM Sequence Logo for a variant.

Design Note:
  This tool generates ISM Sequence Logos to identify disrupted motifs at the
  variant position, helping explain *why* a regulatory or splicing site was
  lost or gained (mechanistic cause).

  The script extracts the top k-mer and prints its reverse complement.
  The agent must use its own knowledge about transcription factor binding
  motifs to identify candidate TFs that match the extracted motif or its
  reverse complement.

Usage:
  uv run analyze_ism.py --chrom=chr17 --pos=7675148 --ref=G --alt=A \
    --tissue=liver --ontology=UBERON:0002107 --modality=DNASE

Examples:
  uv run analyze_ism.py --chrom=chr17 --pos=7675148 --ref=G --alt=A \
    --tissue=liver --ontology=UBERON:0002107 --modality=DNASE

  uv run analyze_ism.py --chrom=chr21 --pos=46126238 --ref=G --alt=C \
    --tissue='skeletal muscle' --ontology=CL:0002545 --modality=SPLICE_SITE_USAGE \
    --gene=COL6A2

  uv run analyze_ism.py --chrom=chr7 --pos=5529776 --ref=C --alt=T \
    --tissue=HepG2 --ontology=EFO:0001187 --modality=CHIP_TF --gene=ACTB \
    --output_dir=./ism_plots
"""

# /// script
# requires-python = ">=3.10"
# dependencies = [
#   "alphagenome",
#   "numpy",
#   "python-dotenv",
# ]
# ///

from __future__ import annotations

import argparse
import os
from typing import Any, Sequence

from alphagenome.data import genome
from alphagenome.interpretation import ism
from alphagenome.models import dna_client
from alphagenome.models import variant_scorers
from alphagenome.visualization import plot_components
import dotenv
import numpy as np


def _reverse_complement(seq: str) -> str:
  """Returns the reverse complement of a DNA sequence."""
  return seq[::-1].translate(str.maketrans('ACGTacgt', 'TGCAtgca'))


def extract_ontology_scores(
    ism_results: list[tuple[Any, ...]],
    ontology_id: str,
    gene_name: str | None = None,
) -> tuple[list[float], list[Any]]:
  """Extracts scores for a specific ontology ID from ISM results."""
  scores_flat: list[float] = []
  variants_flat: list[Any] = []

  for adata, *_ in ism_results:
    var_obj = adata.uns['variant']
    score = 0.0

    if 'ontology_curie' in adata.var.columns:
      col_mask = adata.var['ontology_curie'] == ontology_id
      if col_mask.any():
        row_mask = slice(None)  # All rows
        if gene_name and 'gene_name' in adata.obs.columns:
          gene_mask = adata.obs['gene_name'] == gene_name
          if gene_mask.any():
            row_mask = gene_mask
        score = np.nanmean(adata.X[row_mask, col_mask])
      else:
        print(
            'Info: No scores found for ontology term'
            f' {ontology_id!r} in ISM result.'
        )

    scores_flat.append(score)
    variants_flat.append(var_obj)

  return scores_flat, variants_flat


def interpret_ism_matrix(
    ref_ism_mat: np.ndarray,
    bases: list[str],
    kmer_length: int,
    min_threshold: float,
) -> None:
  """Prints interpretation summary from an ISM matrix."""
  print('\n--- ISM Interpretation Summary ---')
  if not np.any(ref_ism_mat):
    print('ISM matrix is all zeros. No relevant tracks or scores found.')
    return

  max_scores_per_pos = np.max(np.abs(ref_ism_mat), axis=1)
  top_pos_idx = int(np.argmax(max_scores_per_pos))
  top_score = ref_ism_mat[top_pos_idx, :]
  center_idx = ref_ism_mat.shape[0] // 2

  print(
      f'Top Disrupted Position: {top_pos_idx - center_idx} (Relative to'
      ' Variant)'
  )
  print(f'Scores at Top Position: {dict(zip(bases, top_score))}')

  # Use relative threshold but ensure it's at least min_threshold
  threshold = max(np.max(np.abs(ref_ism_mat)) * 0.1, min_threshold)

  consensus_seq: list[str] = []
  for i in range(ref_ism_mat.shape[0]):
    row = ref_ism_mat[i, :]
    best_idx = np.argmax(np.abs(row))
    if abs(row[best_idx]) > threshold:
      consensus_seq.append(bases[best_idx])
    else:
      consensus_seq.append('.')

  consensus_str = ''.join(consensus_seq)
  print(f'Consensus Motif: {consensus_str}')
  print(f'Reverse Compl  : {_reverse_complement(consensus_str)}')

  if ref_ism_mat.shape[0] >= kmer_length:
    best_kmer_score = -1.0
    best_kmer_seq = ''
    best_kmer_start = 0
    for i in range(ref_ism_mat.shape[0] - kmer_length + 1):
      window = ref_ism_mat[i : i + kmer_length, :]
      score = np.sum(np.max(np.abs(window), axis=1))
      if score > best_kmer_score:
        best_kmer_score = score
        best_kmer_start = i
        seq = ''
        for j in range(kmer_length):
          w_row = window[j, :]
          seq += bases[np.argmax(np.abs(w_row))]
        best_kmer_seq = seq
    print(
        f'Top {kmer_length}-mer: {best_kmer_seq}'
        f' (Start: {best_kmer_start - center_idx},'
        f' Score: {best_kmer_score:.3f})'
    )
    print(f'RevComp {kmer_length}-mer: {_reverse_complement(best_kmer_seq)}')
  print('----------------------------------\n')


def analyze_ism(
    chrom: str,
    pos: int,
    ref: str,
    alt: str,
    tissue: str,
    ontology: str,
    modality: str,
    gene: str,
    output_dir: str,
    kmer_length: int,
    min_threshold: float,
) -> None:
  """Runs In-Silico Mutagenesis (ISM) analysis and plots the results."""
  api_key = os.environ.get('ALPHAGENOME_API_KEY')
  if not api_key:
    raise ValueError('ALPHAGENOME_API_KEY not found.')

  print('Initializing AlphaGenome Client...')
  dna_model = dna_client.create(
      api_key=api_key,
      address='dns:///gdmscience.googleapis.com:443',
  )

  variant = genome.Variant(chrom, pos, ref, alt)
  print(f'Variant: {variant}')

  ism_interval = variant.reference_interval.resize(32)
  sequence_interval = ism_interval.resize(dna_client.SEQUENCE_LENGTH_1MB)

  try:
    output_type = dna_client.OutputType[modality.upper()]
  except KeyError as e:
    raise ValueError(
        f'Unknown modality: {modality}. Valid options:'
        f' {[o.name for o in dna_client.OutputType]}'
    ) from e

  if output_type == dna_client.OutputType.SPLICE_JUNCTIONS:
    raise ValueError(
        'SPLICE_JUNCTIONS is NOT supported for ISM. Please use'
        ' SPLICE_SITE_USAGE instead.'
    )

  print(f'Scoring ISM for {tissue} ({output_type.name})...')

  modality_key = modality.upper()
  if modality_key in variant_scorers.RECOMMENDED_VARIANT_SCORERS:
    ism_scorer = variant_scorers.RECOMMENDED_VARIANT_SCORERS[modality_key]
  else:
    raise ValueError(
        f'No recommended scorer found for modality: {modality_key}. '
        'Available recommended scorers: '
        f'{list(variant_scorers.RECOMMENDED_VARIANT_SCORERS.keys())}'
    )

  print('Running ISM on REF background...')
  ref_ism_results = dna_model.score_ism_variants(
      interval=sequence_interval,
      ism_interval=ism_interval,
      variant_scorers=[ism_scorer],
  )

  ref_scores, ref_variants = extract_ontology_scores(
      ref_ism_results, ontology, gene_name=gene
  )
  ref_ism_mat = ism.ism_matrix(ref_scores, variants=ref_variants)

  max_score = np.max(np.abs(ref_ism_mat))
  if max_score == 0:
    print('WARNING: ISM matrix is empty (all zeros). Check ontology ID.')
  elif max_score < min_threshold:
    print(
        f'WARNING: Max ISM score is very low ({max_score:.3f}), below'
        f' threshold {min_threshold}. The result may not be reliable.'
    )

  print('Generating SeqLogo...')
  fig = plot_components.plot(
      [
          plot_components.SeqLogo(
              scores=ref_ism_mat,
              scores_interval=ism_interval,
              ylabel=f'ISM {tissue}\n{output_type.name}',
          )
      ],
      interval=ism_interval,
      fig_width=15,
      title=f'ISM Motif Analysis: {gene} {chrom}:{pos} ({tissue})',
      annotations=[plot_components.VariantAnnotation([variant], alpha=0.5)],
  )

  safe_tissue = tissue.replace(' ', '_').replace('/', '_')
  filename = os.path.join(output_dir, f'ism_{safe_tissue}_{modality}.png')
  os.makedirs(output_dir, exist_ok=True)
  fig.savefig(filename)
  print(f'Saved ISM SeqLogo to {filename}')

  bases = ['A', 'C', 'G', 'T']
  interpret_ism_matrix(ref_ism_mat, bases, kmer_length, min_threshold)


def main(argv: Sequence[str] | None = None) -> None:
  """Main entry point for the ISM analysis CLI tool."""
  dotenv.load_dotenv(os.path.expanduser('~/.env'))
  parser = argparse.ArgumentParser(
      description='Generate ISM Sequence Logo for a variant.'
  )
  parser.add_argument(
      '--chrom',
      required=True,
      help='Chromosome (e.g., chr17).',
  )
  parser.add_argument(
      '--pos', type=int, required=True, help='Position (1-based).'
  )
  parser.add_argument('--ref', required=True, help='Reference allele.')
  parser.add_argument('--alt', required=True, help='Alternate allele.')
  parser.add_argument(
      '--tissue', required=True, help='Tissue name for labeling.'
  )
  parser.add_argument(
      '--ontology', required=True, help='Ontology CURIE (e.g., UBERON:0002107).'
  )
  parser.add_argument(
      '--modality',
      required=True,
      help='Output modality (e.g., DNASE, CHIP_TF).',
  )
  parser.add_argument(
      '--gene', default='Unknown', help='Gene name for plot title.'
  )
  parser.add_argument('--output_dir', default='.', help='Output directory.')
  parser.add_argument(
      '--kmer_length',
      type=int,
      default=8,
      help='Length of k-mer to scan for top score.',
  )
  parser.add_argument(
      '--min_threshold',
      type=float,
      default=0.05,
      help='Minimum absolute score threshold for motif extraction.',
  )

  args = parser.parse_args(argv)

  analyze_ism(
      args.chrom,
      args.pos,
      args.ref,
      args.alt,
      args.tissue,
      args.ontology,
      args.modality,
      args.gene,
      args.output_dir,
      args.kmer_length,
      args.min_threshold,
  )


if __name__ == '__main__':
  main()

# ===== file: skills/alphagenome_single_variant_analysis/scripts/generate_ontology_mapping.py =====
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Generates tissue_ontology_mapping.json from the AlphaGenome API.

Usage:
 uv run scripts/generate_ontology_mapping.py

Can be imported and called programmatically:
  from generate_ontology_mapping import generate_mapping_file
  generate_mapping_file('/path/to/output.json')
"""

# /// script
# requires-python = ">=3.10"
# dependencies = [
#   "alphagenome",
#   "pandas",
#   "python-dotenv",
# ]
# ///

import json
import logging
import os

import dotenv

logger = logging.getLogger(__name__)

from alphagenome.models import dna_client
import pandas as pd


def clean_list(series: pd.Series) -> list[str]:
  """Clean a pandas series to a sorted list of unique non-empty values."""
  vals = set(series.dropna().astype(str))
  vals = {
      v
      for v in vals
      if v.strip() and v.lower() not in ('none', 'nan', 'null', '')
  }
  return sorted(list(vals))


def prune_empty(d):
  """Recursively remove empty values from nested dicts and lists."""
  if not isinstance(d, (dict, list)):
    return d
  if isinstance(d, list):
    return [
        v for v in (prune_empty(v) for v in d) if v not in (None, [], {}, '')
    ]
  if isinstance(d, dict):
    return {
        k: v
        for k, v in ((k, prune_empty(v)) for k, v in d.items())
        if v not in (None, [], {}, '')
    }


def create_biological_mapping(df: pd.DataFrame) -> dict:
  """Create a mapping from ontology CURIEs to biosample metadata."""
  df_proc = df.drop(
      columns=['genetically_modified', 'nonzero_mean', 'name'], errors='ignore'
  ).copy()
  df_proc['output_type'] = (
      df_proc['output_type']
      .astype(str)
      .str.replace('OutputType.', '', regex=False)
  )
  mapping = {}
  for curie, group in df_proc.groupby('ontology_curie'):
    if pd.isna(curie):
      continue
    entry = {
        'biosample': {
            'name': group['biosample_name'].iloc[0],
            'type': group['biosample_type'].iloc[0],
            'life': clean_list(group['biosample_life_stage']),
            'sources': clean_list(group['data_source']),
        },
        'molecular': {
            'histones': clean_list(group['histone_mark']),
            'tfs': clean_list(group['transcription_factor']),
        },
        'assays': {
            assay: {
                'tracks': clean_list(ag['output_type']),
                'marks': (
                    clean_list(ag['histone_mark'])
                    + clean_list(ag['transcription_factor'])
                ),
            }
            for assay, ag in group.groupby('Assay title')
        },
    }
    mapping[curie] = prune_empty(entry)
  return mapping


def generate_mapping_file(output_path: str) -> dict:
  """Fetches AlphaGenome metadata and writes the ontology mapping JSON.

  Args:
    output_path: Path to write the tissue_ontology_mapping.json file.

  Returns:
    The generated mapping dictionary.

  Raises:
    RuntimeError: If ALPHAGENOME_API_KEY is not set.
  """
  api_key = os.environ.get('ALPHAGENOME_API_KEY')
  if not api_key:
    raise RuntimeError(
        'ALPHAGENOME_API_KEY not set. '
        'Ensure the `.env` file contains ALPHAGENOME_API_KEY=<key> and '
        'use uv run to run this script.'
    )

  logger.info('Fetching output metadata from AlphaGenome API...')
  dna_model = dna_client.create(api_key=api_key)
  df = dna_model.output_metadata(dna_client.Organism.HOMO_SAPIENS).concatenate()
  logger.info('Got %d rows.', len(df))

  logger.info('Building ontology mapping...')
  mapping = create_biological_mapping(df)
  logger.info('Created %d entries.', len(mapping))

  os.makedirs(os.path.dirname(output_path), exist_ok=True)
  with open(output_path, 'w') as f:
    json.dump(mapping, f, indent=2)
  logger.info('Wrote mapping to %s', output_path)

  return mapping


def get_tissue_ontology_mapping_path(resource_dir: str) -> str:
  """Returns the path to the tissue ontology mapping JSON file.

  Args:
    resource_dir: Directory where the resources are stored.

  Returns:
    Absolute path to tissue_ontology_mapping.json.
  """
  return os.path.join(resource_dir, 'tissue_ontology_mapping.json')


def main():
  dotenv.load_dotenv(os.path.expanduser('~/.env'))
  script_dir = os.path.dirname(os.path.abspath(__file__))
  resource_dir = os.path.join(script_dir, '..', 'resources')
  generate_mapping_file(get_tissue_ontology_mapping_path(resource_dir))


if __name__ == '__main__':
  main()

# ===== file: skills/alphagenome_single_variant_analysis/scripts/interpret_splicing.py =====
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Quantitative analysis of splicing effects (Splice Sites & Junctions).

This script provides high-resolution, quantitative analysis of splicing changes.
While discovery scans give summary scores, this script analyzes specific
junctions to detect events like exon skipping or cryptic splicing.

Design Note:
  This tool provides quantitative analysis of specific splice junctions,
  complementary to analyze_ism.py which can be used to analyze motifs affecting
  splice site usage. While ISM helps identify *why* a site was lost or gained
  (motif disruption), this script reveals *what* structural changes occurred
  (e.g., exon skipping or cryptic junction usage). It offloads final judgment
  to the agent but provides heuristic flags (e.g., GAIN/LOSS) to guide the analysis.

Usage:
  uv run scripts/interpret_splicing.py --chrom=chr21 --pos=46126238 --ref=G --alt=C \
      --ontology_id=CL:0002545
"""

# /// script
# requires-python = ">=3.10"
# dependencies = [
#   "alphagenome",
#   "numpy",
#   "pandas",
#   "python-dotenv",
# ]
# ///

from __future__ import annotations

import argparse
import os
from typing import Any, Sequence

from alphagenome.data import genome
from alphagenome.models import dna_client
import dotenv
import numpy as np
import pandas as pd

API_ADDRESS = 'dns:///gdmscience.googleapis.com:443'


def get_track(obj: Any, attr: str, curie: str) -> Any:
  """Retrieves a track filtered by ontology CURIE."""
  if not hasattr(obj, attr):
    print(f"Warning: Object missing attribute '{attr}'.")
    return None
  data = getattr(obj, attr)
  if hasattr(data, 'filter_by_ontology'):
    return data.filter_by_ontology(curie)
  mask = data.metadata['ontology_curie'] == curie
  if not mask.any():
    print(f"Info: No data found for ontology term '{curie}' in track '{attr}'.")
    return None
  return data.filter_tracks(mask.values)


def junctions_to_df(junc_track: Any) -> pd.DataFrame:
  """Converts a JunctionTrack to a DataFrame."""
  if junc_track is None or len(junc_track.junctions) == 0:
    return pd.DataFrame()

  scores = None
  if hasattr(junc_track, 'values'):
    vals = junc_track.values
    # Handle different shapes of values array from API
    if vals.shape[0] == len(junc_track.junctions):
      scores = vals.mean(axis=1)
    elif len(vals.shape) > 1 and vals.shape[1] == len(junc_track.junctions):
      scores = vals.mean(axis=0)
    elif len(vals.shape) == 1 and len(vals) == len(junc_track.junctions):
      scores = vals

  if scores is None:
    print('Warning: Failed to parse scores for junctions.')
    return pd.DataFrame()

  rows = []
  for junction, score in zip(junc_track.junctions, scores):
    rows.append({
        'start': junction.start,
        'end': junction.end,
        'score': float(score),
        'strand': junction.strand,
    })
  return pd.DataFrame(rows)


def analyze_splicing(
    chrom: str,
    pos: int,
    ref: str,
    alt: str,
    ontology_id: str,
    window: int,
) -> None:
  """Runs the splicing analysis for a specific variant."""
  api_key = os.environ.get('ALPHAGENOME_API_KEY')
  if not api_key:
    raise ValueError('ALPHAGENOME_API_KEY environment variable not set.')

  dna_model = dna_client.create(api_key=api_key, address=API_ADDRESS)

  variant = genome.Variant(chrom, pos, ref, alt)
  zoom_interval = genome.Interval(chrom, pos - window // 2, pos + window // 2)
  pred_interval = zoom_interval.resize(131072)

  print(
      f'Quantifying splicing changes for {chrom}:{pos}:{ref}>{alt} in'
      f' {ontology_id}...'
  )

  requested_outputs = [
      dna_client.OutputType.SPLICE_JUNCTIONS,
      dna_client.OutputType.SPLICE_SITE_USAGE,
      dna_client.OutputType.RNA_SEQ,
  ]

  prediction = dna_model.predict_variant(
      interval=pred_interval,
      variant=variant,
      requested_outputs=requested_outputs,
      ontology_terms=[ontology_id],
  )

  print('\n--- Splice Site Usage Analysis ---')
  ss_ref = get_track(prediction.reference, 'splice_site_usage', ontology_id)
  ss_alt = get_track(prediction.alternate, 'splice_site_usage', ontology_id)

  if ss_ref and ss_alt:
    start = pred_interval.start
    idx = pos - start

    for offset in range(-2, 3):
      position = pos + offset
      index = idx + offset
      try:
        val_ref = (
            ss_ref.values[index].mean()
            if ss_ref.values.ndim > 1
            else ss_ref.values[index]
        )
        val_alt = (
            ss_alt.values[index].mean()
            if ss_alt.values.ndim > 1
            else ss_alt.values[index]
        )

        diff = val_alt - val_ref
        if abs(diff) > 0.05:
          print(
              f'Position {position} (Offset {offset}): REF={val_ref:.3f},'
              f' ALT={val_alt:.3f}, Delta={diff:.3f}'
          )
          if val_ref > 0.5 and val_alt < 0.1:
            print(f'  -> Loss of strong splice site at {position}!')
          elif val_ref < 0.1 and val_alt > 0.5:
            print(f'  -> Gain of new splice site at {position}!')
      except (IndexError, AttributeError, ValueError) as e:
        if not isinstance(e, IndexError):
          print(f'Warning: Error during splice site diff calculation: {e}')
        pass
  else:
    print('Splice site usage track missing.')

  print('\n--- Junction Analysis ---')
  junc_ref = prediction.reference.splice_junctions.filter_by_ontology(
      ontology_id
  )
  junc_alt = prediction.alternate.splice_junctions.filter_by_ontology(
      ontology_id
  )

  df_ref = junctions_to_df(junc_ref)
  df_alt = junctions_to_df(junc_alt)

  if not df_ref.empty and not df_alt.empty:
    merged = pd.merge(
        df_ref,
        df_alt,
        on=['start', 'end', 'strand'],
        how='outer',
        suffixes=('_REF', '_ALT'),
    ).fillna(0)
    merged['delta'] = merged['score_ALT'] - merged['score_REF']

    # Junctions overlapping variant
    variant_overlapping = merged[
        (merged['start'] < pos) & (merged['end'] > pos)
    ]

    print(f'Junctions overlapping variant ({pos}):')
    if variant_overlapping.empty:
      print('  None found.')
    else:
      for _, row in variant_overlapping.iterrows():
        print(
            f"  {int(row['start'])}-{int(row['end'])} (Strand {row['strand']}):"
            f" REF={row['score_REF']:.2f}, ALT={row['score_ALT']:.2f},"
            f" Delta={row['delta']:.2f}"
        )
        if row['score_REF'] > 5 and row['score_ALT'] < 1:
          print('  -> Skipping/Loss of canonical intron (Exon skipping?)')

    # Cryptic Junctions (Gain in ALT)
    cryptic = merged[(merged['score_ALT'] > 5) & (merged['score_REF'] < 1)]
    if not cryptic.empty:
      print('\nPotential Cryptic Junctions (Gain in ALT):')
      for _, row in cryptic.iterrows():
        print(
            f"  {int(row['start'])}-{int(row['end'])}:"
            f" REF={row['score_REF']:.2f} -> ALT={row['score_ALT']:.2f}"
        )

    print('\nTop 5 Most Changed Junctions:')
    top_changes = merged.reindex(
        merged['delta'].abs().sort_values(ascending=False).index
    ).head(5)
    print(top_changes[['start', 'end', 'score_REF', 'score_ALT', 'delta']])
  else:
    print('No junctions found or failed to parse.')

  print('\n--- RNA-seq Analysis ---')
  rna_ref = get_track(prediction.reference, 'rna_seq', ontology_id)
  rna_alt = get_track(prediction.alternate, 'rna_seq', ontology_id)

  if rna_ref and rna_alt:
    start_idx = pos - pred_interval.start - 50
    end_idx = pos - pred_interval.start + 50

    def safe_mean(arr: np.ndarray) -> np.ndarray:
      if arr.ndim > 1:
        return arr.mean(axis=1)
      return arr

    ref_vals = safe_mean(rna_ref.values)
    alt_vals = safe_mean(rna_alt.values)

    ref_window = ref_vals[start_idx:end_idx]
    alt_window = alt_vals[start_idx:end_idx]

    print(
        f'Mean RNA Coverage (+/- 50bp): REF={ref_window.mean():.2f},'
        f' ALT={alt_window.mean():.2f}'
    )
    if ref_window.mean() > 0:
      log2fc = np.log2((alt_window.mean() + 1e-3) / (ref_window.mean() + 1e-3))
      print(f'Log2 Fold Change at variant: {log2fc:.2f}')
  else:
    print('RNA-seq track missing.')


def main(argv: Sequence[str] | None = None) -> None:
  """Main entry point for the splicing analysis CLI tool."""
  dotenv.load_dotenv(os.path.expanduser('~/.env'))
  parser = argparse.ArgumentParser(
      description='Quantitative analysis of splicing effects.'
  )
  parser.add_argument(
      '--chrom', required=True, help='Chromosome (e.g., chr21).'
  )
  parser.add_argument(
      '--pos', type=int, required=True, help='Position (1-based).'
  )
  parser.add_argument('--ref', required=True, help='Reference allele.')
  parser.add_argument('--alt', required=True, help='Alternate allele.')
  parser.add_argument(
      '--ontology_id', required=True, help='Ontology CURIE (e.g., CL:0002545).'
  )
  parser.add_argument(
      '--window',
      type=int,
      default=1500,
      help='Window size around variant for analysis.',
  )
  args = parser.parse_args(argv)

  analyze_splicing(
      args.chrom,
      args.pos,
      args.ref,
      args.alt,
      args.ontology_id,
      args.window,
  )


if __name__ == '__main__':
  main()

# ===== file: skills/alphagenome_single_variant_analysis/scripts/lookup_gene_info.py =====
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Comprehensive gene and transcript lookup tool using GTF data.

Usage:
  # 1. Lookup gene symbol or coordinate to get ID and location
  uv run scripts/lookup_gene_info.py --genes='TP53,BRCA1'
  uv run scripts/lookup_gene_info.py --genes='chr17:7675148'

  # 2. Find genes near a coordinate
  uv run scripts/lookup_gene_info.py --coord='chr17:7675148' --window=50000

  # 3. List and filter transcripts for a gene
  uv run scripts/lookup_gene_info.py --genes='EGFR' --transcripts --mane
"""

# /// script
# requires-python = ">=3.10"
# dependencies = [
#   "alphagenome",
#   "pandas",
#   "python-dotenv",
# ]
# ///

from __future__ import annotations

import argparse
import os
import re
from typing import Sequence

from alphagenome.data import gene_annotation
import dotenv
import pandas as pd

GTF_URL = (
    'https://storage.googleapis.com/alphagenome/reference/gencode/'
    'hg38/gencode.v46.annotation.gtf.gz.feather'
)


def load_gtf(gtf_path: str | None = None) -> pd.DataFrame:
  """Loads the GTF feather file from a path or URL."""
  path = gtf_path or os.environ.get('ALPHAGENOME_GTF_PATH', GTF_URL)
  print(f'Loading GTF from {path}...')
  return pd.read_feather(path)


def parse_gene_input(genes: list[str]) -> list[str]:
  """Parses comma-separated gene input and deduplicates."""
  parsed = set()
  for gene in genes:
    parsed |= {x.strip() for x in gene.split(',') if x.strip()}
  return sorted(parsed)


def classify_queries(queries: list[str]) -> tuple[list[str], list[str]]:
  """Classifies queries into coordinates and gene symbols."""
  coords = []
  symbols = []
  for query in queries:
    if re.match(r'^chr[0-9XYM]+:\d+', query):
      coords.append(query)
    else:
      symbols.append(query)
  return coords, symbols


def parse_coord(coord_str: str) -> tuple[str, int, int]:
  """Parses coordinate string like chr1:100-200 or chr1:150."""
  chrom, pos_part = coord_str.split(':', 1)

  if '-' in pos_part:
    start_str, end_str = pos_part.split('-')
    return chrom, int(start_str), int(end_str)
  else:
    pos = int(pos_part)
    return chrom, pos, pos


# --- Mode 1: Gene Symbol <-> Coord Lookup (from lookup_ensg_gtf) ---
def run_gene_lookup(gtf: pd.DataFrame, genes_input: list[str]) -> None:
  """Looks up gene symbols or coordinates in GTF."""
  genes_of_interest = parse_gene_input(genes_input)
  coords_to_lookup, symbols_to_lookup = classify_queries(genes_of_interest)

  results = []

  # Handle symbols
  if symbols_to_lookup:
    mask = gtf['gene_name'].isin(symbols_to_lookup)
    result_df = gtf[mask][
        ['gene_name', 'gene_id_nopatch', 'Chromosome', 'Start', 'End', 'Strand']
    ]
    results.append(result_df)

  # Handle coordinates
  for coord in coords_to_lookup:
    chrom, pos, _ = parse_coord(coord)
    mask = (
        (gtf['Chromosome'] == chrom)
        & (gtf['Start'] <= pos)
        & (gtf['End'] >= pos)
    )
    result_df = gtf[mask][
        ['gene_name', 'gene_id_nopatch', 'Chromosome', 'Start', 'End', 'Strand']
    ]
    results.append(result_df)

  if not results:
    print('No matches found.')
    return

  df = pd.concat(results).drop_duplicates()
  if df.empty:
    print('No matches found.')
  else:
    print(df.to_string(index=False))


# --- Mode 2: Find Genes at Coordinate (from lookup_gene_at_coord) ---
def run_coord_search(gtf: pd.DataFrame, coord: str, window: int) -> None:
  """Finds genes near a coordinate."""
  chrom, start, end = parse_coord(coord)

  if start == end:
    search_start = start - window
    search_end = end + window
  else:
    search_start, search_end = start, end

  print(f'\nSearching for genes at {chrom}:{search_start:,}-{search_end:,}')
  print('-' * 50)

  mask = (
      (gtf['Chromosome'] == chrom)
      & (gtf['Start'] <= search_end)
      & (gtf['End'] >= search_start)
  )

  matching_genes = gtf[mask].copy()

  if matching_genes.empty:
    print('No genes found in this region.')
    return

  # Calculate distance if it's a single point query
  if start == end:

    def calc_dist(row):
      if row['Start'] <= start <= row['End']:
        return 0
      return min(abs(row['Start'] - start), abs(row['End'] - start))

    matching_genes['Distance'] = matching_genes.apply(calc_dist, axis=1)
    matching_genes = matching_genes.sort_values('Distance')
    cols = [
        'gene_name',
        'gene_id_nopatch',
        'Chromosome',
        'Start',
        'End',
        'Distance',
    ]
  else:
    matching_genes = matching_genes.sort_values('Start')
    cols = ['gene_name', 'gene_id_nopatch', 'Chromosome', 'Start', 'End']

  # Keep only gene features to avoid duplicate rows for exons/transcripts
  feature_col = 'Feature' if 'Feature' in matching_genes.columns else 'feature'
  if feature_col in matching_genes.columns:
    matching_genes = matching_genes[matching_genes[feature_col] == 'gene']

  if matching_genes.empty:
    print(
        'No gene features found (only exons/transcripts). Showing unique gene'
        ' names:'
    )
    print(matching_genes['gene_name'].unique())
  else:
    print(matching_genes[cols].drop_duplicates().to_string(index=False))


# --- Mode 3: List and Filter Transcripts (from lookup_transcripts) ---
def run_transcript_lookup(
    gtf: pd.DataFrame,
    genes_input: list[str],
    mane: bool,
    protein_coding: bool,
    transcript_support_level: str | None,
    longest: bool,
    details: bool,
) -> None:
  """Lists and filters transcripts for genes."""
  genes_list = parse_gene_input(genes_input)

  filtered = gtf[gtf['gene_name'].isin(genes_list)].copy()

  if filtered.empty:
    print(f'No data found for genes: {genes_list}')
    return

  if mane:
    print('Filtering to MANE transcripts...')
    filtered = gene_annotation.filter_to_mane_select_transcript(filtered)

  if protein_coding:
    print('Filtering to protein coding transcripts...')
    filtered = gene_annotation.filter_to_protein_coding_transcript(filtered)

  if transcript_support_level:
    print(
        f'Filtering to Transcript Support Level: {transcript_support_level}...'
    )
    tsl_list = [x.strip() for x in transcript_support_level.split(',')]
    if 'transcript_support_level' in filtered.columns:
      filtered['tsl_clean'] = (
          filtered['transcript_support_level'].astype(str).str.extract(r'^(\d)')
      )
      filtered = filtered[filtered['tsl_clean'].isin(tsl_list)]
    else:
      print(
          'Warning: "transcript_support_level" column not found. Cannot filter'
          ' by TSL.'
      )

  if longest:
    print('Filtering to longest transcript per gene...')
    filtered = gene_annotation.filter_to_longest_transcript(filtered)

  cols = ['gene_name', 'transcript_id']
  if details:
    for column in [
        'transcript_type',
        'transcript_support_level',
        'Chromosome',
        'Start',
        'End',
    ]:
      if column in filtered.columns:
        cols.append(column)

  print('\nResults:')
  if 'Feature' in filtered.columns:
    transcript_features = filtered[filtered['Feature'] == 'transcript']
    if not transcript_features.empty:
      filtered = transcript_features

  print(filtered[cols].drop_duplicates().to_string(index=False))


def main(argv: Sequence[str] | None = None) -> None:
  dotenv.load_dotenv(os.path.expanduser('~/.env'))
  parser = argparse.ArgumentParser(
      description='Lookup gene and transcript info using GTF data.'
  )

  group = parser.add_mutually_exclusive_group(required=True)
  group.add_argument(
      '--genes', help='Comma-separated gene symbols or coordinates to lookup.'
  )
  group.add_argument(
      '--coord', help='Genomic coordinate for search (e.g. chr17:7675148).'
  )

  parser.add_argument(
      '--window',
      type=int,
      default=50000,
      help='Window size for coordinate search (default 50kb).',
  )
  parser.add_argument(
      '--transcripts',
      action='store_true',
      help='List transcripts instead of gene info.',
  )

  # Transcript filters
  parser.add_argument(
      '--mane', action='store_true', help='Filter to MANE transcripts.'
  )
  parser.add_argument(
      '--protein_coding',
      action='store_true',
      help='Filter to protein coding transcripts.',
  )
  parser.add_argument(
      '--transcript_support_level',
      help='Filter by Transcript Support Level (e.g. 1,2).',
  )
  parser.add_argument(
      '--longest',
      action='store_true',
      help='Filter to longest transcript per gene.',
  )
  parser.add_argument(
      '--details', action='store_true', help='Show full transcript details.'
  )
  parser.add_argument(
      '--gtf_path',
      type=str,
      default=None,
      help=(
          'Path or URL to the GTF feather file (defaults to'
          ' $ALPHAGENOME_GTF_PATH or the public GCS URL).'
      ),
  )

  args = parser.parse_args(argv)

  gtf = load_gtf(args.gtf_path)

  if args.coord is not None:
    run_coord_search(gtf, args.coord, args.window)
  elif args.genes is not None:
    genes_list = [x.strip() for x in args.genes.split(',')]
    if args.transcripts:
      run_transcript_lookup(
          gtf,
          genes_list,
          args.mane,
          args.protein_coding,
          args.transcript_support_level,
          args.longest,
          args.details,
      )
    else:
      run_