api-swift / scripts / gen-api.py
6,425 words
   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
#!/usr/bin/env python3
"""scripts/gen-api.py — emits the typed Swift API from spec/openapi.json.

    python3 scripts/gen-api.py            # regenerate Sources/IrdAPI/Generated and the test artefacts
    python3 scripts/gen-api.py --check    # exit 1 when the committed output is stale (release gate)
    python3 scripts/gen-api.py --report   # print the type inventory and every auto-qualified name

Python 3 standard library only; deterministic (no hash-ordered iteration).

What it produces
  Sources/IrdAPI/Generated/<Module>.swift   Codable models, query structs, IrdOperation constants and
                                            the <Module>API struct with one method per operation
  Sources/IrdAPI/Generated/Shared.swift     types referenced from more than one module
  Sources/IrdAPI/Generated/Operations.swift IrdOperation.all
  Tests/IrdAPITests/Generated/*.swift       the coverage table (one typed call per operation) and the
                                            decode/encode round-trip table
  Tests/IrdAPITests/Fixtures/synth.json     bodies and responses synthesised from the schemas

The tables at the top are the only part humans edit: the 161-row operation name table
(transcribed from the sibling TypeScript client) and the naming overrides. Every
override must still apply, and every spec operation must have a row, else the run fails.
"""
import argparse
import difflib
import json
import os
import re
import sys
import tempfile
from collections import Counter, OrderedDict
from dataclasses import dataclass, field, replace

HEADER = "// Generated by scripts/gen-api.py from spec/openapi.json — do not edit.\n"
BASE_URL = "https://api.ird.ro"

# (method, path, module, name) — module grouping and names follow ird-ts.
OPERATIONS = [
    # auth + api-keys (6)
    ("POST", "/auth/device/start", "auth", "deviceStart"),
    ("POST", "/auth/device/poll", "auth", "devicePoll"),
    ("POST", "/auth/device/complete", "auth", "deviceComplete"),
    ("GET", "/auth/api-keys", "auth", "listApiKeys"),
    ("POST", "/auth/api-keys", "auth", "createApiKey"),
    ("POST", "/auth/api-keys/{id}/revoke", "auth", "revokeApiKey"),
    # credits (3)
    ("GET", "/credits/balance", "credits", "balance"),
    ("GET", "/credits/ledger", "credits", "ledger"),
    ("GET", "/credits/prices", "credits", "prices"),
    # support (4)
    ("GET", "/contact/threads", "support", "listThreads"),
    ("POST", "/contact/threads", "support", "createThread"),
    ("GET", "/contact/threads/{id}", "support", "getThread"),
    ("POST", "/contact/threads/{id}/messages", "support", "reply"),
    # domains + directory (9)
    ("GET", "/domains/check", "domains", "check"),
    ("GET", "/domains/info", "domains", "info"),
    ("GET", "/domains/preflight", "domains", "preflight"),
    ("GET", "/domains/dns-snapshot", "domains", "dnsSnapshot"),
    ("GET", "/domains/search", "domains", "search"),
    ("POST", "/domains/search", "domains", "searchDescriptions"),
    ("GET", "/domains/example", "domains", "example"),
    ("GET", "/domains/directory", "domains", "directory"),
    ("GET", "/domains/directory/{domain}", "domains", "directoryEntry"),
    # registrations (27)
    ("GET", "/domains/registrations", "registrations", "list"),
    ("POST", "/domains/registrations", "registrations", "register"),
    ("GET", "/domains/registrations/{id}", "registrations", "get"),
    ("POST", "/domains/registrations/{id}/renew", "registrations", "renew"),
    ("PUT", "/domains/registrations/{id}/auto-renew", "registrations", "setAutoRenew"),
    ("PUT", "/domains/registrations/{id}/sensitive", "registrations", "setSensitive"),
    ("PUT", "/domains/registrations/{id}/nameservers", "registrations", "setNameservers"),
    ("GET", "/domains/registrations/{id}/hosts", "registrations", "listHosts"),
    ("POST", "/domains/registrations/{id}/hosts", "registrations", "createHost"),
    ("PUT", "/domains/registrations/{id}/hosts/{host}", "registrations", "setHostIps"),
    ("DELETE", "/domains/registrations/{id}/hosts/{host}", "registrations", "deleteHost"),
    ("GET", "/domains/registrations/{id}/dsdata", "registrations", "listDsData"),
    ("POST", "/domains/registrations/{id}/dsdata", "registrations", "publishDsData"),
    ("DELETE", "/domains/registrations/{id}/dsdata", "registrations", "withdrawDsData"),
    ("POST", "/domains/registrations/{id}/transfer-out", "registrations", "transferOut"),
    ("PUT", "/domains/registrations/{id}/registrant", "registrations", "updateRegistrant"),
    ("POST", "/domains/registrations/{id}/registrant-email/start", "registrations", "startRegistrantEmailVerification"),
    ("POST", "/domains/registrations/{id}/registrant-email/confirm", "registrations", "confirmRegistrantEmail"),
    ("POST", "/domains/registrations/{id}/registrant-email/adopt", "registrations", "adoptRegistrantEmail"),
    ("GET", "/domains/registrations/{id}/trade", "registrations", "quoteTrade"),
    ("POST", "/domains/registrations/{id}/trade", "registrations", "trade"),
    ("POST", "/domains/transfers-in", "registrations", "transferIn"),
    ("POST", "/domains/trades-in", "registrations", "tradeIn"),
    ("POST", "/domains/adoptions", "registrations", "adopt"),
    ("GET", "/domains/actions", "registrations", "listActions"),
    ("GET", "/domains/actions/{id}", "registrations", "getAction"),
    ("POST", "/domains/actions/{id}/cancel", "registrations", "cancelAction"),
    # dns (18)
    ("POST", "/domains/registrations/{id}/dns", "dns", "enableHosting"),
    ("DELETE", "/domains/registrations/{id}/dns", "dns", "disableHosting"),
    ("GET", "/domains/registrations/{id}/dns/dnssec", "dns", "getDnssec"),
    ("POST", "/domains/registrations/{id}/dns/dnssec", "dns", "enableDnssec"),
    ("DELETE", "/domains/registrations/{id}/dns/dnssec", "dns", "disableDnssec"),
    ("GET", "/domains/registrations/{id}/dns/nameservers", "dns", "hostedNameservers"),
    ("POST", "/domains/registrations/{id}/dns/nameservers", "dns", "setHostedNameservers"),
    ("GET", "/dns/domains", "dns", "listZones"),
    ("GET", "/dns/domains/{domain}", "dns", "getZone"),
    ("PUT", "/dns/domains/{domain}/records", "dns", "setRecord"),
    ("DELETE", "/dns/domains/{domain}/records", "dns", "deleteRecord"),
    ("GET", "/dns/claims", "dns", "listClaims"),
    ("POST", "/dns/claims", "dns", "createClaim"),
    ("GET", "/dns/claims/{id}", "dns", "getClaim"),
    ("DELETE", "/dns/claims/{id}", "dns", "releaseClaim"),
    ("PUT", "/dns/claims/{id}/seed", "dns", "seedClaim"),
    ("DELETE", "/dns/claims/{id}/seed", "dns", "unseedClaim"),
    ("POST", "/dns/claims/{id}/verify", "dns", "verifyClaim"),
    # sharing (7)
    ("GET", "/domains/registrations/{id}/grants", "sharing", "listDomainGrants"),
    ("POST", "/domains/registrations/{id}/grants", "sharing", "invite"),
    ("DELETE", "/domains/registrations/{id}/grants/{grant-id}", "sharing", "revokeGrant"),
    ("GET", "/grants", "sharing", "listGrants"),
    ("POST", "/grants/{id}/accept", "sharing", "acceptGrant"),
    ("POST", "/grants/{id}/decline", "sharing", "declineGrant"),
    ("POST", "/grants/{id}/leave", "sharing", "leaveGrant"),
    # vps (34)
    ("GET", "/vps/tiers", "vps", "listTiers"),
    ("GET", "/vps/system-images", "vps", "listSystemImages"),
    ("GET", "/vps/ssh-keys", "vps", "listSshKeys"),
    ("POST", "/vps/ssh-keys", "vps", "addSshKey"),
    ("DELETE", "/vps/ssh-keys/{id}", "vps", "deleteSshKey"),
    ("GET", "/vps/availability", "vps", "availability"),
    ("GET", "/vps/instances", "vps", "listInstances"),
    ("POST", "/vps/instances", "vps", "createInstance"),
    ("GET", "/vps/apps", "vps", "appCatalog"),
    ("GET", "/vps/apps/deployments", "vps", "listAppDeployments"),
    ("POST", "/vps/apps/deployments", "vps", "deployApp"),
    ("GET", "/vps/apps/deployments/{id}", "vps", "getAppDeployment"),
    ("POST", "/vps/apps/deployments/{id}/reveal-password", "vps", "revealAppPassword"),
    ("GET", "/vps/instances/{id}", "vps", "getInstance"),
    ("DELETE", "/vps/instances/{id}", "vps", "destroyInstance"),
    ("GET", "/vps/instances/{id}/metrics", "vps", "getMetrics"),
    ("POST", "/vps/instances/{id}/queue-notify", "vps", "setQueueNotify"),
    ("POST", "/vps/instances/{id}/images", "vps", "createSnapshot"),
    ("POST", "/vps/instances/{id}/restart", "vps", "restart"),
    ("POST", "/vps/instances/{id}/reset", "vps", "reset"),
    ("POST", "/vps/instances/{id}/shutdown", "vps", "shutdown"),
    ("POST", "/vps/instances/{id}/power-off", "vps", "powerOff"),
    ("POST", "/vps/instances/{id}/power-on", "vps", "powerOn"),
    ("PUT", "/vps/instances/{id}/rdns", "vps", "setRdns"),
    ("GET", "/vps/instances/{id}/domains", "vps", "listInstanceDomains"),
    ("POST", "/vps/instances/{id}/domains", "vps", "connectDomain"),
    ("DELETE", "/vps/instances/{id}/domains/{connection-id}", "vps", "disconnectDomain"),
    ("GET", "/vps/volumes", "vps", "listVolumes"),
    ("POST", "/vps/volumes", "vps", "createVolume"),
    ("DELETE", "/vps/volumes/{id}", "vps", "deleteVolume"),
    ("GET", "/vps/images", "vps", "listImages"),
    ("DELETE", "/vps/images/{id}", "vps", "deleteImage"),
    ("GET", "/vps/actions/{id}", "vps", "getAction"),
    ("GET", "/vps/activity", "vps", "listActivity"),
    # transfers (9)
    ("POST", "/vps/instances/{id}/transfer", "transfers", "offerInstance"),
    ("DELETE", "/vps/instances/{id}/transfer", "transfers", "withdrawInstanceOffer"),
    ("POST", "/vps/volumes/{id}/transfer", "transfers", "offerVolume"),
    ("DELETE", "/vps/volumes/{id}/transfer", "transfers", "withdrawVolumeOffer"),
    ("POST", "/vps/images/{id}/transfer", "transfers", "offerImage"),
    ("DELETE", "/vps/images/{id}/transfer", "transfers", "withdrawImageOffer"),
    ("GET", "/vps/transfers", "transfers", "list"),
    ("POST", "/vps/transfers/{id}/accept", "transfers", "accept"),
    ("POST", "/vps/transfers/{id}/decline", "transfers", "decline"),
    # tunnels (6)
    ("GET", "/tunnels", "tunnels", "list"),
    ("POST", "/tunnels", "tunnels", "create"),
    ("GET", "/tunnels/{id}", "tunnels", "get"),
    ("DELETE", "/tunnels/{id}", "tunnels", "remove"),
    ("PATCH", "/tunnels/{id}", "tunnels", "update"),
    ("POST", "/tunnels/{id}/verify-dns", "tunnels", "verifyDns"),
    # ipfs (18)
    ("GET", "/ipfs/pins", "ipfs", "listPins"),
    ("POST", "/ipfs/pins", "ipfs", "pin"),
    ("GET", "/ipfs/pins/{id}", "ipfs", "getPin"),
    ("DELETE", "/ipfs/pins/{id}", "ipfs", "unpin"),
    ("POST", "/ipfs/uploads", "ipfs", "startUpload"),
    ("GET", "/ipfs/uploads/{id}", "ipfs", "getUpload"),
    ("GET", "/ipfs/names", "ipfs", "listNames"),
    ("POST", "/ipfs/names", "ipfs", "createName"),
    ("GET", "/ipfs/names/{id}", "ipfs", "getName"),
    ("DELETE", "/ipfs/names/{id}", "ipfs", "deleteName"),
    ("PUT", "/ipfs/names/{id}/target", "ipfs", "publishTarget"),
    ("GET", "/ipfs/domains", "ipfs", "listDomains"),
    ("POST", "/ipfs/domains", "ipfs", "attachDomain"),
    ("GET", "/ipfs/domains/{id}", "ipfs", "getDomain"),
    ("GET", "/ipfs/domains/{id}/pins", "ipfs", "listDomainPins"),
    ("POST", "/ipfs/domains/{id}/pins", "ipfs", "updateDomainPins"),
    ("DELETE", "/ipfs/domains/{id}", "ipfs", "detachDomain"),
    ("GET", "/ipfs/usage", "ipfs", "usage"),
    # pins — Pinning Service API (5)
    ("GET", "/pins", "pins", "list"),
    ("POST", "/pins", "pins", "add"),
    ("GET", "/pins/{requestid}", "pins", "get"),
    ("POST", "/pins/{requestid}", "pins", "replace"),
    ("DELETE", "/pins/{requestid}", "pins", "remove"),
    # p2p (12)
    ("GET", "/p2p/apps", "p2p", "listApps"),
    ("POST", "/p2p/apps", "p2p", "createApp"),
    ("GET", "/p2p/apps/{id}", "p2p", "getApp"),
    ("DELETE", "/p2p/apps/{id}", "p2p", "deleteApp"),
    ("PATCH", "/p2p/apps/{id}", "p2p", "updateApp"),
    ("POST", "/p2p/apps/{id}/turn-credentials", "p2p", "mintTurnCredentials"),
    ("POST", "/p2p/apps/{id}/mailbox-credentials", "p2p", "mintMailboxCredentials"),
    ("GET", "/p2p/apps/{id}/domains", "p2p", "listAppDomains"),
    ("POST", "/p2p/apps/{id}/domains", "p2p", "attachDomain"),
    ("DELETE", "/p2p/apps/{id}/domains/{domain-id}", "p2p", "detachDomain"),
    ("POST", "/p2p/apps/{id}/domains/{domain-id}/verify-dns", "p2p", "verifyDomainDns"),
    ("GET", "/p2p/usage", "p2p", "usage"),
    # jobs (3)
    ("POST", "/jobs", "jobs", "enqueue"),
    ("GET", "/jobs/{id}", "jobs", "get"),
    ("GET", "/jobs/{id}/result", "jobs", "getResult"),
]

MODULE_ORDER = ["auth", "credits", "support", "domains", "registrations", "dns", "sharing", "vps",
                "transfers", "tunnels", "ipfs", "pins", "p2p", "jobs"]
MODULE_FILE = {"auth": "Auth", "credits": "Credits", "support": "Support", "domains": "Domains",
               "registrations": "Registrations", "dns": "DNS", "sharing": "Sharing", "vps": "VPS",
               "transfers": "Transfers", "tunnels": "Tunnels", "ipfs": "IPFS", "pins": "Pins",
               "p2p": "P2P", "jobs": "Jobs"}
MODULE_API = {m: MODULE_FILE[m] + "API" for m in MODULE_ORDER}
# Prefix used to disambiguate a name that collides across modules.
MODULE_PREFIX = {"auth": "Auth", "credits": "Credit", "support": "Support", "domains": "Domain",
                 "registrations": "Registration", "dns": "DNS", "sharing": "Sharing", "vps": "VPS",
                 "transfers": "Transfer", "tunnels": "Tunnel", "ipfs": "IPFS", "pins": "PinningService",
                 "p2p": "P2P", "jobs": "Job", "shared": "Common"}

# Site labels are "METHOD /path#body|<status>/<key>/<key>[]..." — see Site.label().
TYPE_NAME_OVERRIDES = {
    "POST /jobs#body": "JobSpec",
    "POST /jobs#body/domain-availability-bulk": "DomainAvailabilityBulkJob",
    "POST /jobs#body/embedding": "EmbeddingJob",
    "POST /jobs#body/llm-chat": "LlmChatJob",
    "POST /jobs#body/llm-raw-completion": "LlmRawCompletionJob",
    "POST /jobs#body/nlp-analyze": "NlpAnalyzeJob",
    "POST /jobs#body/nlp-detect-language": "NlpDetectLanguageJob",
    "POST /jobs#body/llm-chat/messages[]": "ChatMessage",
    "GET /jobs/{id}#200/job": "Job",
    "POST /jobs#202/job": "QueuedJob",
    "GET /jobs/{id}/result#200": "JobResult",
    "POST /ipfs/uploads#201/upload": "Upload",
    "POST /auth/device/start#200": "DeviceStartResponse",
    "POST /auth/device/poll#200": "DevicePollResponse",
    "POST /auth/device/complete#200": "DeviceCompleteResponse",
    "POST /auth/device/complete#200/user": "AccountUser",
    "GET /credits/ledger#200/entries[]": "LedgerEntry",
    "GET /credits/ledger#200/entries[]/resource": "LedgerResource",
    "GET /credits/prices#200/registrar": "RegistrarPrices",
    "GET /contact/threads/{id}#200": "ThreadResponse",
    "GET /contact/threads/{id}#200/messages[]": "ThreadMessage",
    "GET /contact/threads/{id}#200/messages[]/replies[]": "ThreadReply",
    "GET /domains/example#200": "DomainNameResponse",
    "GET /domains/search#200": "SearchResponse",
    "GET /domains/dns-snapshot#200/records[]": "SnapshotRecord",
    "GET /domains/directory#200/entries[]": "DirectoryEntry",
    "GET /domains/registrations/{id}#200/registration": "Registration",
    "GET /domains/registrations#200/registrations[]/dsdata[]": "DsRecord",
    "GET /domains/registrations/{id}/hosts#200/hosts[]": "HostDetail",
    "GET /domains/registrations/{id}/trade#200/estimates[]": "RenewalEstimate",
    "GET /domains/actions/{id}#200/action": "RegistrationAction",
    "POST /domains/registrations/{id}/dns#body/records[]": "RecordSpec",
    "POST /domains/registrations/{id}/dns#202/zones[]": "CreatedZone",
    "GET /dns/domains#200/domains[]": "ZoneSummary",
    "GET /dns/domains/{domain}#200": "Zone",
    "GET /dns/domains/{domain}#200/records[]": "ZoneRecord",
    "GET /dns/claims#200/claims[]/delegation": "ClaimDelegation",
    "GET /dns/claims#200/claims[]/registry": "ClaimRegistry",
    "GET /dns/claims#200/claims[]/seed": "ClaimSeed",
    "GET /dns/claims#200/claims[]/last_check": "ClaimCheck",
    "GET /vps/instances/{id}#200/instance": "Instance",
    "GET /vps/actions/{id}#200/action": "VPSAction",
    "GET /vps/apps/deployments#200/deployments[]": "AppDeployment",
    "GET /vps/instances/{id}/domains#200/connections[]": "DomainConnection",
    "GET /vps/activity#200/activity[]": "ActivityEntry",
    "GET /vps/instances/{id}/metrics#200/series[]/points[]": "MetricPoint",
    "GET /vps/instances/{id}/metrics#200/series[]": "MetricSeries",
    "GET /tunnels#200/tunnels[]/settings": "TunnelSettings",
    "POST /tunnels#body": "CreateTunnelBody",
    "PATCH /tunnels/{id}#body": "UpdateTunnelBody",
    "GET /ipfs/pins/{id}#200/pin": "Pin",
    "POST /ipfs/pins#body": "PinSpec",
    "GET /ipfs/domains/{id}#200/domain": "GatewayDomain",
    "POST /ipfs/domains#201": "GatewayDomainResponse",
    "GET /ipfs/domains/{id}/pins#200/pins[]": "DomainPin",
    "GET /ipfs/names/{id}#200/name": "IpnsName",
    "GET /pins#200": "PinResults",
    "GET /pins#200/results[]": "PinStatus",
    "GET /p2p/apps#200/apps[]/domains[]": "AppDomain",
    "POST /p2p/apps/{id}/turn-credentials#200/credentials": "TurnCredentials",
    "POST /p2p/apps/{id}/mailbox-credentials#200/credentials": "MailboxCredentials",
}
# Field names for prefixItems tuples, by site label.
TUPLE_FIELD_NAMES = {
    "GET /vps/instances/{id}/metrics#200/series[]/points[]": ["timestamp", "value"],
}
# Enum names by site label (the automatic name is <Owner><Prop>).
ENUM_NAME_OVERRIDES = {
    "GET /domains/check#200/status": "DomainAvailability",
    "GET /domains/preflight#200/verdict": "PreflightVerdict",
    "GET /domains/preflight#200/sponsorship": "PreflightSponsorship",
    "POST /domains/registrations/{id}/dns#202/nameservers_mode": "HostedNameserversMode",
    "GET /vps/instances/{id}/metrics#200/source": "MetricsSource",
    "GET /vps/apps/deployments#200/deployments[]/dns_state": "DnsConnectionState",
    "GET /tunnels#200/tunnels[]/state": "HostnameState",
    "GET /tunnels#200/tunnels[]/cert_status": "CertStatus",
    "POST /ipfs/uploads#body/format": "UploadFormat",
    "GET /pins#query/match": "PinMatch",
    "GET /pins#200/results[]/status": "PinRequestStatus",
}
ENUM_CASE_OVERRIDES = {"bytes/s": "bytesPerSecond"}
# Single-value enums folded into an existing enum: (property key, values) -> superset values.
ENUM_ALIASES = {
    ("status", ("queued",)): ("queued", "processing", "succeeded", "failed"),
}
PARAM_NAME_OVERRIDES = {"requestid": "requestId"}
SINGULAR_OVERRIDES = {"series": "series", "dsdata": "dsdata", "status": "status", "address": "address"}

SWIFT_KEYWORDS = {
    "associatedtype", "class", "deinit", "enum", "extension", "fileprivate", "func", "import", "init", "inout",
    "internal", "let", "open", "operator", "private", "precedencegroup", "protocol", "public", "rethrows", "static",
    "struct", "subscript", "typealias", "var", "break", "case", "catch", "continue", "default", "defer", "do", "else",
    "fallthrough", "for", "guard", "if", "in", "repeat", "return", "throw", "switch", "where", "while", "Any", "as",
    "await", "false", "is", "nil", "self", "Self", "super", "throws", "true", "try", "Type",
}
RESERVED_NAMES = {
    "IrdClient", "IrdError", "JSONValue", "Configuration", "IrdOperation", "IrdSecurity", "HTTPMethod", "QueryItem",
    "RawAPI", "DomainGate", "GateRules", "GateTarget", "GateDenial", "PollOptions", "Paginator", "HTTPResponse",
    "HTTPTransport", "URLSessionHTTPTransport", "IrdClock", "SystemClock", "CredentialProvider", "CredentialStore",
    "NoCredential", "StaticCredential", "InMemoryCredentialStore", "KeychainCredentialStore", "CredentialStoreError",
    "Data", "Date", "URL", "String", "Int", "Double", "Bool", "Array", "Dictionary", "Optional",
    "Error", "Result", "Task", "Duration",
    # Foundation / SwiftUI names a consumer would have to qualify; the resolver prefixes them by module.
    "Thread", "Image", "Host", "Text", "Label", "Section", "List", "Form", "Table", "Link", "Color", "Font", "Menu",
    "State", "Group", "Path", "Timer", "Notification", "Bundle", "Process", "Port", "Stream", "Unit", "Locale",
    "Calendar", "Scanner", "Pipe", "Lock", "Operation", "Button", "Toggle", "Picker", "Alert", "Environment", "Binding",
    "View", "App", "Scene", "Window", "Document", "File", "Progress", "Stepper", "Slider", "Divider", "Spacer",
}
METHODS = ("get", "post", "put", "patch", "delete")


def die(msg):
    print("gen-api: " + msg, file=sys.stderr)
    sys.exit(2)


# ----------------------------------------------------------------------------- identifiers

def words(s):
    return [w for w in re.split(r"[^A-Za-z0-9]+", s) if w]


def pascal(s):
    return "".join(w[:1].upper() + w[1:] for w in words(s))


def camel(s):
    ws = words(s)
    if not ws:
        return "_"
    out = ws[0][:1].lower() + ws[0][1:] + "".join(w[:1].upper() + w[1:] for w in ws[1:])
    if out[0].isdigit():
        out = "_" + out
    return out


def ident(s):
    out = camel(s)
    return "`%s`" % out if out in SWIFT_KEYWORDS else out


def singular(s):
    if s in SINGULAR_OVERRIDES:
        return SINGULAR_OVERRIDES[s]
    if s.endswith("ies"):
        return s[:-3] + "y"
    if s.endswith("ses") or s.endswith("xes"):
        return s[:-2]
    if s.endswith("s") and not s.endswith("ss"):
        return s[:-1]
    return s


def first_sentence(text, limit=240):
    text = (text or "").strip().replace("\n", " ")
    if not text:
        return ""
    if len(text) <= limit:
        return text
    m = re.search(r"\.\s", text)
    if m and m.end() <= limit + 40:
        return text[: m.start() + 1]
    return text[:limit].rstrip() + "…"


def doc_lines(text):
    return [("/// " + l).rstrip() for l in (text or "").strip().split("\n") if l.strip()]


# ----------------------------------------------------------------------------- IR

@dataclass(frozen=True)
class TypeRef:
    kind: str                # prim | array | map | json | object | enum | tuple | oneof
    arg: object = None       # prim: Swift name; array/map: element TypeRef; others: registry id
    nullable: bool = False


@dataclass
class Site:
    op_key: str
    module: str
    where: str               # "body" or the success status
    path: tuple              # property keys, "[]" for array items
    key: str                 # property key holding this value (None at the top)
    in_array: bool = False

    def label(self):
        return "%s#%s" % (self.op_key, "/".join((self.where,) + self.path))

    @property
    def top(self):
        return not self.path


@dataclass
class Prop:
    key: str
    type: TypeRef
    required: bool
    description: str = ""

    @property
    def swift(self):
        return ident(self.key)

    @property
    def optional(self):
        return (not self.required) or self.type.nullable


@dataclass
class Definition:
    id: str
    kind: str                # object | enum | tuple | oneof | query
    sites: list = field(default_factory=list)
    name: str = None
    fixed: bool = False      # name pinned by an override
    module: str = None       # single module or "shared"
    # object
    props: list = field(default_factory=list)
    # enum
    values: tuple = ()
    # tuple
    items: list = field(default_factory=list)
    fields: list = field(default_factory=list)
    # oneof
    alternatives: list = field(default_factory=list)   # (const, shape id)
    discriminator: str = None
    # query
    params: list = field(default_factory=list)         # Prop-like entries
    op_name: str = None

    @property
    def has_required_nullable(self):
        return any(p.required and p.type.nullable for p in self.props)


@dataclass
class Param:
    name: str
    type: TypeRef
    required: bool
    description: str = ""

    @property
    def swift(self):
        return ident(PARAM_NAME_OVERRIDES.get(self.name, self.name))


@dataclass
class Operation:
    method: str
    path: str
    module: str
    name: str
    security: str
    summary: str
    description: str
    statuses: list
    path_params: list = field(default_factory=list)      # Param
    query_params: list = field(default_factory=list)     # Param
    body: TypeRef = None
    body_required: bool = False                          # body has required properties
    response: TypeRef = None                             # None: no content
    query_def: Definition = None

    @property
    def key(self):
        return "%s %s" % (self.method, self.path)

    @property
    def const(self):
        return "%s_%s" % (self.module, self.name)


class Registry:
    def __init__(self):
        self.defs = OrderedDict()      # id -> Definition
        self.by_canon = {}             # canonical key -> id
        self.order = []                # ids in first-seen order
        self.warnings = []

    def _register(self, canon, make):
        if canon in self.by_canon:
            return self.defs[self.by_canon[canon]]
        did = "D%d" % (len(self.defs) + 1)
        d = make(did)
        self.defs[did] = d
        self.by_canon[canon] = did
        self.order.append(did)
        return d

    # -- canonical keys
    @staticmethod
    def type_key(t):
        if t.kind in ("array", "map"):
            return "%s<%s>%s" % (t.kind, Registry.type_key(t.arg), "?" if t.nullable else "")
        return "%s:%s%s" % (t.kind, t.arg, "?" if t.nullable else "")

    def intern(self, schema, site, key_hint=None):
        """Turns a schema into a TypeRef, registering shapes/enums/tuples/oneofs."""
        if not isinstance(schema, dict):
            die("non-object schema at %s" % site.label())
        if "$ref" in schema:
            die("$ref at %s" % site.label())
        if "oneOf" in schema:
            alts = schema["oneOf"]
            others = [a for a in alts if a.get("type") != "null"]
            nulls = len(alts) - len(others)
            if nulls and len(others) == 1:
                return replace(self.intern(others[0], site, key_hint), nullable=True)
            if others and all(o.get("type") == "object" and "properties" in o for o in others):
                return self.intern_oneof(others, site)
            die("unsupported oneOf at %s" % site.label())
        if "allOf" in schema:
            types = {a.get("type") for a in schema["allOf"]}
            if len(types) != 1 or list(types)[0] not in ("string", "integer", "number", "boolean"):
                die("unsupported allOf at %s" % site.label())
            return self.intern({"type": list(types)[0]}, site, key_hint)
        if "const" in schema:
            die("const outside a discriminated oneOf at %s" % site.label())
        if "enum" in schema:
            values = tuple(schema["enum"])
            if not all(isinstance(v, str) for v in values):
                die("non-string enum at %s" % site.label())
            if len(values) == 1:
                alias = ENUM_ALIASES.get((site.key, values))
                if alias is None:
                    return TypeRef("prim", "String")
                values = alias
            return TypeRef("enum", self.intern_enum(values, site).id)
        t = schema.get("type")
        if t == "string":
            return TypeRef("prim", "String")
        if t == "integer":
            return TypeRef("prim", "Int")
        if t == "number":
            return TypeRef("prim", "Double")
        if t == "boolean":
            return TypeRef("prim", "Bool")
        if t == "null":
            die("bare null type at %s (widen it before interning)" % site.label())
        if t == "array":
            if "prefixItems" in schema:
                return TypeRef("tuple", self.intern_tuple(schema["prefixItems"], site).id)
            if isinstance(schema.get("items"), dict):
                path = site.path[:-1] + (site.path[-1] + "[]",) if site.path else ("[]",)
                child = Site(site.op_key, site.module, site.where, path, site.key, True)
                return TypeRef("array", self.intern(schema["items"], child, site.key))
            return TypeRef("array", TypeRef("json"))
        if t == "object":
            if "properties" in schema:
                return TypeRef("object", self.intern_shape(schema, site).id)
            ap = schema.get("additionalProperties")
            if isinstance(ap, dict):
                if not ap:
                    return TypeRef("map", TypeRef("json"))
                return TypeRef("map", self.intern(ap, site, site.key))
            return TypeRef("json")
        return TypeRef("json")

    def intern_shape(self, schema, site):
        props_schema = schema["properties"]
        required = set(schema.get("required", []))
        props = []
        for key, sub in props_schema.items():
            child = Site(site.op_key, site.module, site.where, site.path + (key,), key)
            t = self.intern(sub, child, key)
            props.append(Prop(key, t, key in required, first_sentence(sub.get("description", ""), 400)))
        canon = "object" + json.dumps(sorted((p.key, self.type_key(p.type), p.required) for p in props))
        d = self._register(canon, lambda did: Definition(did, "object", props=props))
        if d.sites:
            fresh = {p.key: p.description for p in props}
            for p in d.props:
                if not p.description and fresh.get(p.key):
                    p.description = fresh[p.key]
        d.sites.append(site)
        return d

    def intern_enum(self, values, site):
        canon = "enum" + json.dumps(list(values))
        d = self._register(canon, lambda did: Definition(did, "enum", values=values))
        d.sites.append(site)
        return d

    def intern_tuple(self, items, site):
        types = [self.intern(it, site, site.key) for it in items]
        canon = "tuple" + json.dumps([self.type_key(t) for t in types])
        d = self._register(canon, lambda did: Definition(did, "tuple", items=types))
        d.sites.append(site)
        return d

    def intern_oneof(self, alternatives, site):
        disc = None
        for key in alternatives[0]["properties"]:
            if all("const" in a["properties"].get(key, {}) for a in alternatives):
                disc = key
                break
        if disc is None:
            die("oneOf without a shared const discriminator at %s" % site.label())
        alts = []
        for a in alternatives:
            const = a["properties"][disc]["const"]
            stripped = dict(a)
            stripped["properties"] = {k: v for k, v in a["properties"].items() if k != disc}
            stripped["required"] = [k for k in a.get("required", []) if k != disc]
            child = Site(site.op_key, site.module, site.where, site.path + (const,), const)
            alts.append((const, self.intern_shape(stripped, child).id))
        canon = "oneof" + json.dumps([(c, s) for c, s in alts]) + disc
        d = self._register(canon, lambda did: Definition(did, "oneof", alternatives=alts, discriminator=disc))
        d.sites.append(site)
        return TypeRef("oneof", d.id)


# ----------------------------------------------------------------------------- spec handling

def load_spec(path):
    with open(path) as f:
        return json.load(f)


def verify_assumptions(spec):
    if not str(spec.get("openapi", "")).startswith("3.1"):
        die("expected OpenAPI 3.1, got %s" % spec.get("openapi"))
    if spec.get("components", {}).get("schemas"):
        die("component schemas appeared; the generator inlines everything")
    text = json.dumps(spec)
    if '"$ref"' in text:
        die("$ref appeared in the spec")
    for path, item in spec["paths"].items():
        for method, op in item.items():
            if method not in METHODS:
                continue
            key = "%s %s" % (method.upper(), path)
            for p in op.get("parameters", []):
                if p.get("in") not in ("path", "query"):
                    die("%s: parameter in %s" % (key, p.get("in")))
            template_params = set(re.findall(r"\{([^}]+)\}", path))
            declared = {p["name"] for p in op.get("parameters", []) if p["in"] == "path"}
            if template_params != declared:
                die("%s: path params %s vs declared %s" % (key, template_params, declared))
            rb = op.get("requestBody")
            if rb and list(rb.get("content", {}).keys()) != ["application/json"]:
                die("%s: request content types %s" % (key, list(rb.get("content", {}).keys())))
            for code, r in op["responses"].items():
                if "content" in r and list(r["content"].keys()) != ["application/json"]:
                    die("%s %s: content types %s" % (key, code, list(r["content"].keys())))
            if not [c for c in op["responses"] if c.startswith("2")]:
                die("%s: no success response" % key)


def security_kind(op, key):
    sec = op.get("security")
    kinds = tuple(sorted(tuple(sorted(s.keys())) for s in (sec or [])))
    table = {
        ((),): "anonymous",
        ((), ("apiKey",)): "anonymousOrKey",
        (("accountJwt",), ("apiKey",)): "keyOrJwt",
        (("accountJwt",),): "jwtOnly",
    }
    if kinds not in table:
        die("%s: unknown security %s" % (key, sec))
    return table[kinds]


def widen(a, b, where):
    """Merges two success schemas: identical keeps, null vs X widens to nullable X,
    a property present in one becomes optional."""
    if a == b:
        return a
    if a.get("type") == "null" or b.get("type") == "null":
        other = b if a.get("type") == "null" else a
        if "oneOf" in other and any(x.get("type") == "null" for x in other["oneOf"]):
            return other
        return {"oneOf": [other, {"type": "null"}]}
    if a.get("type") == "object" and b.get("type") == "object" and "properties" in a and "properties" in b:
        props = OrderedDict()
        for k in list(a["properties"]) + [k for k in b["properties"] if k not in a["properties"]]:
            if k in a["properties"] and k in b["properties"]:
                props[k] = widen(a["properties"][k], b["properties"][k], where + "/" + k)
            else:
                props[k] = a["properties"].get(k) or b["properties"].get(k)
        required = [k for k in a.get("required", []) if k in b.get("required", [])]
        out = dict(a)
        out["properties"] = props
        out["required"] = required
        return out
    die("cannot widen success schemas at %s" % where)


def build_operations(spec, reg):
    ops = []
    seen = set()
    for method, path, module, name in OPERATIONS:
        item = spec["paths"].get(path)
        op = item.get(method.lower()) if item else None
        key = "%s %s" % (method, path)
        if op is None:
            die("operation table row has no spec operation: %s" % key)
        seen.add(key)
        statuses = sorted(c for c in op["responses"] if c.startswith("2"))
        o = Operation(method, path, module, name, security_kind(op, key), op.get("summary", ""),
                      op.get("description", ""), statuses)
        # parameters
        for p in op.get("parameters", []):
            site = Site(key, module, "query", (p["name"],), p["name"])
            sc = p["schema"]
            if p["in"] == "path":
                o.path_params.append(Param(p["name"], TypeRef("prim", "String"), True, p.get("description", "")))
                continue
            if sc.get("type") == "boolean" or sc.get("enum") == ["true", "false"]:
                t = TypeRef("prim", "Bool")
            else:
                t = reg.intern(sc, site, p["name"])
            o.query_params.append(Param(p["name"], t, bool(p.get("required")), first_sentence(p.get("description", ""), 400)))
        # body
        rb = op.get("requestBody")
        if rb:
            schema = rb["content"]["application/json"]["schema"]
            site = Site(key, module, "body", (), None)
            o.body = reg.intern(schema, site)
            o.body_required = bool(schema.get("required")) or "oneOf" in schema
        # response
        merged = None
        for code in statuses:
            r = op["responses"][code]
            if "content" not in r:
                continue
            sc = r["content"]["application/json"]["schema"]
            merged = sc if merged is None else widen(merged, sc, key)
        if merged is not None:
            site = Site(key, module, statuses[0], (), None)
            o.response = reg.intern(merged, site)
        ops.append(o)
    declared = {"%s %s" % (m.upper(), p) for p, item in spec["paths"].items() for m in item if m in METHODS}
    missing = sorted(declared - seen)
    if missing:
        die("spec operations without a table row: %s" % missing)
    return ops


# ----------------------------------------------------------------------------- naming

def def_module(d):
    mods = {s.module for s in d.sites}
    return list(mods)[0] if len(mods) == 1 else "shared"


def method_name_of(op_key, ops_by_key):
    return ops_by_key[op_key].name


def candidate_name(d, ops_by_key):
    for s in d.sites:
        if s.label() in TYPE_NAME_OVERRIDES:
            d.fixed = True
            return TYPE_NAME_OVERRIDES[s.label()]
    if d.kind == "query":
        return pascal(d.op_name) + "Query"
    if d.kind == "enum":
        return None   # named after shapes
    nested = [s for s in d.sites if not s.top]
    if nested:
        c = Counter(pascal(singular(s.key) if s.in_array else s.key) for s in nested)
        return sorted(c.items(), key=lambda kv: (-kv[1], kv[0]))[0][0]
    tops = [s for s in d.sites if s.top]
    suffix = "Body" if tops[0].where == "body" else "Response"
    op_keys = []
    for s in tops:
        if s.op_key not in op_keys:
            op_keys.append(s.op_key)
    if len(op_keys) == 1:
        return pascal(method_name_of(op_keys[0], ops_by_key)) + suffix
    if d.kind == "object":
        keys = [p.key for p in d.props if p.required] or [p.key for p in d.props]
        if len(keys) <= 3:
            return "".join(pascal(k) for k in keys) + suffix
    first = sorted(method_name_of(k, ops_by_key) for k in op_keys)[0]
    return pascal(first) + suffix


def enum_candidate(d, reg):
    for s in d.sites:
        if s.label() in ENUM_NAME_OVERRIDES:
            d.fixed = True
            return ENUM_NAME_OVERRIDES[s.label()]
    owners = []   # (owner name, prop key, in_array, sites)
    for od in reg.defs.values():
        if od.kind == "object":
            for p in od.props:
                t = p.type
                in_array = False
                while t.kind in ("array", "map"):
                    t = t.arg
                    in_array = True
                if t.kind == "enum" and t.arg == d.id:
                    owner = od.name if any(not s.top for s in od.sites) else MODULE_PREFIX[od.module]
                    owners.append((owner, p.key, in_array, len(od.sites)))
    if owners:
        owner, key, in_array, _ = sorted(owners, key=lambda o: (-o[3], o[0]))[0]
        return owner + pascal(singular(key) if in_array else key)
    # only query parameters hold it
    s = d.sites[0]
    return MODULE_PREFIX[def_module(d)] + pascal(s.key)


def resolve_collisions(defs, ops_by_key, warnings):
    """Renames until every name is unique: cross-module collisions get the module prefix,
    same-module collisions keep the most-used shape and qualify the rest by method."""
    for _ in range(6):
        by_name = OrderedDict()
        for d in defs:
            by_name.setdefault(d.name, []).append(d)
        clashes = {n: ds for n, ds in by_name.items() if len(ds) > 1 or n in RESERVED_NAMES}
        if not clashes:
            return
        for name, ds in clashes.items():
            movable = [d for d in ds if not d.fixed]
            if not movable:
                die("override collision on %s: %s" % (name, [s.label() for d in ds for s in d.sites[:1]]))
            modules = {d.module for d in ds}
            if len(modules) > 1 or name in RESERVED_NAMES:
                for d in movable:
                    d.name = MODULE_PREFIX[d.module] + name
                continue
            keep = None if any(d.fixed for d in ds) else sorted(ds, key=lambda d: (-len(d.sites), d.sites[0].label()))[0]
            for d in movable:
                if d is keep:
                    continue
                d.name = pascal(method_name_of(d.sites[0].op_key, ops_by_key)) + name
                warnings.append("auto-qualified %s -> %s" % (d.sites[0].label(), d.name))
    die("could not resolve name collisions")


def assign_names(reg, ops):
    ops_by_key = {o.key: o for o in ops}
    used_overrides = set()
    for d in reg.defs.values():
        d.module = def_module(d)
        for s in d.sites:
            if s.label() in TYPE_NAME_OVERRIDES:
                used_overrides.add(s.label())
    unused = sorted(set(TYPE_NAME_OVERRIDES) - used_overrides)
    if unused:
        die("unused TYPE_NAME_OVERRIDES: %s" % unused)
    non_enum = [d for d in reg.defs.values() if d.kind != "enum"]
    for d in non_enum:
        d.name = candidate_name(d, ops_by_key)
    resolve_collisions(non_enum, ops_by_key, reg.warnings)
    enums = [d for d in reg.defs.values() if d.kind == "enum"]
    for d in enums:
        d.name = enum_candidate(d, reg)
    resolve_collisions(non_enum + enums, ops_by_key, reg.warnings)
    unused_enum = set(ENUM_NAME_OVERRIDES) - {s.label() for d in enums for s in d.sites}
    if unused_enum:
        die("unused ENUM_NAME_OVERRIDES: %s" % sorted(unused_enum))
    for d in reg.defs.values():
        if d.kind == "tuple":
            names = None
            for s in d.sites:
                names = TUPLE_FIELD_NAMES.get(s.label(), names)
            d.fields = names or ["item%d" % i for i in range(len(d.items))]
            if len(d.fields) != len(d.items):
                die("tuple field names for %s do not match arity" % d.name)


# ----------------------------------------------------------------------------- emission

class Writer:
    def __init__(self):
        self.lines = []
        self.level = 0

    def line(self, s=""):
        self.lines.append(("    " * self.level + s) if s else "")

    def doc(self, text):
        for l in doc_lines(text):
            self.line(l)

    def indent(self):
        self.level += 1

    def dedent(self):
        self.level -= 1

    def text(self):
        return "\n".join(self.lines).rstrip("\n") + "\n"


def swift_type(t, reg):
    if t.kind == "prim":
        base = t.arg
    elif t.kind == "array":
        base = "[%s]" % swift_type(t.arg, reg)
    elif t.kind == "map":
        base = "[String: %s]" % swift_type(t.arg, reg)
    elif t.kind == "json":
        base = "JSONValue"
    else:
        base = reg.defs[t.arg].name
    return base + ("?" if t.nullable else "")


def prop_type(p, reg):
    base = swift_type(replace(p.type, nullable=False), reg)
    return base + ("?" if p.optional else "")


def enum_case(value):
    if value in ENUM_CASE_OVERRIDES:
        return ENUM_CASE_OVERRIDES[value]
    return ident(value)


def emit_struct(w, d, reg):
    conforms = "Codable, Sendable, Hashable"
    idp = next((p for p in d.props if p.key == "id" and p.required and not p.type.nullable
                and p.type.kind == "prim" and p.type.arg in ("String", "Int")), None)
    if idp:
        conforms += ", Identifiable"
    sites = sorted({s.op_key for s in d.sites})
    w.doc("Shared by %d operations." % len(sites) if len(sites) > 1 else "Used by %s." % sites[0])
    w.line("public struct %s: %s {" % (d.name, conforms))
    w.indent()
    for p in d.props:
        if p.description:
            w.doc(p.description)
        w.line("public var %s: %s" % (p.swift, prop_type(p, reg)))
    w.line()
    params = ", ".join("%s: %s%s" % (p.swift, prop_type(p, reg), " = nil" if p.optional else "") for p in d.props)
    w.line("public init(%s) {" % params)
    w.indent()
    for p in d.props:
        w.line("self.%s = %s" % (p.swift, p.swift))
    w.dedent()
    w.line("}")
    w.line()
    w.line("enum CodingKeys: String, CodingKey {")
    w.indent()
    for p in d.props:
        raw = p.key
        sw = p.swift.strip("`")
        w.line("case %s%s" % (p.swift, (' = "%s"' % raw) if raw != sw else ""))
    w.dedent()
    w.line("}")
    if d.has_required_nullable:
        w.line()
        w.line("/// Explicit so required-but-nullable fields encode as `null` rather than vanishing.")
        w.line("public func encode(to encoder: any Encoder) throws {")
        w.indent()
        w.line("var container = encoder.container(keyedBy: CodingKeys.self)")
        for p in d.props:
            fn = "encodeIfPresent" if (not p.required) else "encode"
            w.line("try container.%s(%s, forKey: .%s)" % (fn, p.swift, p.swift))
        w.dedent()
        w.line("}")
    w.dedent()
    w.line("}")


def emit_enum(w, d):
    cases = [(v, enum_case(v)) for v in d.values]
    w.doc("Values this build does not know decode as `.unrecognized`.")
    w.line("public enum %s: RawRepresentable, Codable, Sendable, Hashable {" % d.name)
    w.indent()
    for _, c in cases:
        w.line("case %s" % c)
    w.line("/// A value the server sent that this version of the package does not list.")
    w.line("case unrecognized(String)")
    w.line()
    w.line("/// Every value the spec listed when this file was generated.")
    w.line("public static let known: [%s] = [%s]" % (d.name, ", ".join("." + c for _, c in cases)))
    w.line()
    w.line("public init(rawValue: String) {")
    w.indent()
    w.line("switch rawValue {")
    for v, c in cases:
        w.line('case "%s": self = .%s' % (v, c))
    w.line("default: self = .unrecognized(rawValue)")
    w.line("}")
    w.dedent()
    w.line("}")
    w.line()
    w.line("public var rawValue: String {")
    w.indent()
    w.line("switch self {")
    for v, c in cases:
        w.line('case .%s: return "%s"' % (c, v))
    w.line("case .unrecognized(let raw): return raw")
    w.line("}")
    w.dedent()
    w.line("}")
    w.line()
    w.line("public init(from decoder: any Decoder) throws {")
    w.indent()
    w.line("self.init(rawValue: try decoder.singleValueContainer().decode(String.self))")
    w.dedent()
    w.line("}")
    w.line()
    w.line("public func encode(to encoder: any Encoder) throws {")
    w.indent()
    w.line("var container = encoder.singleValueContainer()")
    w.line("try container.encode(rawValue)")
    w.dedent()
    w.line("}")
    w.dedent()
    w.line("}")


def emit_tuple(w, d, reg):
    w.doc("A fixed-arity JSON array.")
    w.line("public struct %s: Codable, Sendable, Hashable {" % d.name)
    w.indent()
    for f, t in zip(d.fields, d.items):
        w.line("public var %s: %s" % (ident(f), swift_type(t, reg)))
    w.line()
    w.line("public init(%s) {" % ", ".join("%s: %s" % (ident(f), swift_type(t, reg)) for f, t in zip(d.fields, d.items)))
    w.indent()
    for f in d.fields:
        w.line("self.%s = %s" % (ident(f), ident(f)))
    w.dedent()
    w.line("}")
    w.line()
    w.line("public init(from decoder: any Decoder) throws {")
    w.indent()
    w.line("var container = try decoder.unkeyedContainer()")
    for f, t in zip(d.fields, d.items):
        w.line("%s = try container.decode(%s.self)" % (ident(f), swift_type(t, reg)))
    w.dedent()
    w.line("}")
    w.line()
    w.line("public func encode(to encoder: any Encoder) throws {")
    w.indent()
    w.line("var container = encoder.unkeyedContainer()")
    for f in d.fields:
        w.line("try container.encode(%s)" % ident(f))
    w.dedent()
    w.line("}")
    w.dedent()
    w.line("}")


def emit_oneof(w, d, reg):
    alts = [(c, reg.defs[s]) for c, s in d.alternatives]
    w.doc("Discriminated by `%s`." % d.discriminator)
    w.line("public enum %s: Codable, Sendable, Hashable {" % d.name)
    w.indent()
    for c, s in alts:
        w.line("case %s(%s)" % (ident(c), s.name))
    w.line()
    w.line("/// The wire discriminator.")
    w.line("public var %s: String {" % ident(d.discriminator))
    w.indent()
    w.line("switch self {")
    for c, s in alts:
        w.line('case .%s: return "%s"' % (ident(c), c))
    w.line("}")
    w.dedent()
    w.line("}")
    w.line()
    w.line("private enum DiscriminatorKey: String, CodingKey { case %s = \"%s\" }" % (ident(d.discriminator), d.discriminator))
    w.line()
    w.line("public init(from decoder: any Decoder) throws {")
    w.indent()
    w.line("let kind = try decoder.container(keyedBy: DiscriminatorKey.self).decode(String.self, forKey: .%s)" % ident(d.discriminator))
    w.line("switch kind {")
    for c, s in alts:
        w.line('case "%s": self = .%s(try %s(from: decoder))' % (c, ident(c), s.name))
    w.line("default: throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: \"unknown %s \\(kind)\"))" % d.discriminator)
    w.line("}")
    w.dedent()
    w.line("}")
    w.line()
    w.line("public func encode(to encoder: any Encoder) throws {")
    w.indent()
    w.line("var container = encoder.container(keyedBy: DiscriminatorKey.self)")
    w.line("try container.encode(%s, forKey: .%s)" % (ident(d.discriminator), ident(d.discriminator)))
    w.line("switch self {")
    for c, s in alts:
        w.line("case .%s(let payload): try payload.encode(to: encoder)" % ident(c))
    w.line("}")
    w.dedent()
    w.line("}")
    w.dedent()
    w.line("}")


def query_item_expr(p, reg):
    t = p.type
    if t.kind == "prim" and t.arg == "String":
        return "value"
    if t.kind == "prim" and t.arg == "Bool":
        return 'value ? "true" : "false"'
    if t.kind == "prim":
        return "String(value)"
    if t.kind == "enum":
        return "value.rawValue"
    die("unsupported query parameter type for %s" % p.name)


def emit_query(w, d, reg):
    w.doc("Query parameters of `%s`; unset fields are omitted." % d.op_name)
    w.line("public struct %s: Sendable, Hashable {" % d.name)
    w.indent()
    for p in d.params:
        if p.description:
            w.doc(p.description)
        w.line("public var %s: %s?" % (p.swift, swift_type(p.type, reg)))
    w.line()
    w.line("public init(%s) {" % ", ".join("%s: %s? = nil" % (p.swift, swift_type(p.type, reg)) for p in d.params))
    w.indent()
    for p in d.params:
        w.line("self.%s = %s" % (p.swift, p.swift))
    w.dedent()
    w.line("}")
    w.line()
    w.line("/// The items in spec order.")
    w.line("public var queryItems: [QueryItem] {")
    w.indent()
    w.line("var items: [QueryItem] = []")
    for p in d.params:
        w.line('if let value = %s { items.append(QueryItem("%s", %s)) }' % (p.swift, p.name, query_item_expr(p, reg)))
    w.line("return items")
    w.dedent()
    w.line("}")
    w.dedent()
    w.line("}")


def emit_definition(w, d, reg):
    if d.kind == "object":
        emit_struct(w, d, reg)
    elif d.kind == "enum":
        emit_enum(w, d)
    elif d.kind == "tuple":
        emit_tuple(w, d, reg)
    elif d.kind == "oneof":
        emit_oneof(w, d, reg)
    elif d.kind == "query":
        emit_query(w, d, reg)
    w.line()


def method_signature(o, reg):
    parts = ["%s: String" % p.swift for p in o.path_params]
    parts += ["%s: String" % p.swift for p in o.query_params if p.required]
    if o.query_def:
        parts.append("query: %s = %s()" % (o.query_def.name, o.query_def.name))
    if o.body is not None:
        bt = swift_type(o.body, reg)
        parts.append("body: %s" % bt if o.body_required else "body: %s? = nil" % bt)
    ret = " -> %s" % swift_type(o.response, reg) if o.response is not None else ""
    return "public func %s(%s) async throws%s" % (o.name, ", ".join(parts), ret)


def method_call(o):
    args = [".%s" % o.const]
    if o.path_params:
        args.append("params: [%s]" % ", ".join('"%s": %s' % (p.name, p.swift) for p in o.path_params))
    req = ['QueryItem("%s", %s)' % (p.name, p.swift) for p in o.query_params if p.required]
    if req or o.query_def:
        q = "[%s]" % ", ".join(req) if req else ""
        if o.query_def:
            q = (q + " + " if q else "") + "query.queryItems"
        args.append("query: %s" % q)
    if o.body is not None:
        args.append("body: body")
    fn = "request" if o.response is not None else "requestNoContent"
    return "try await client.%s(%s)" % (fn, ", ".join(args))


def emit_module(module, ops, reg, defs_for_module):
    w = Writer()
    w.lines.append(HEADER.rstrip("\n"))
    w.line()
    w.line("import Foundation")
    w.line()
    w.line("// MARK: - Types")
    w.line()
    for d in defs_for_module:
        emit_definition(w, d, reg)
    w.line("// MARK: - Operations")
    w.line()
    w.line("extension IrdOperation {")
    w.indent()
    for o in ops:
        w.line('public static let %s = IrdOperation(method: .%s, pathTemplate: "%s", module: "%s", name: "%s", security: .%s)'
               % (o.const, o.method.lower(), o.path, o.module, o.name, o.security))
    w.line()
    w.line("static let %sOperations: [IrdOperation] = [%s]" % (module, ", ".join("." + o.const for o in ops)))
    w.dedent()
    w.line("}")
    w.line()
    w.doc("The `%s` operations (%d)." % (module, len(ops)))
    w.line("public struct %s: Sendable {" % MODULE_API[module])
    w.indent()
    w.line("let client: IrdClient")
    for o in ops:
        w.line()
        if o.summary:
            w.doc(o.summary)
        desc = first_sentence(o.description)
        if desc and desc != o.summary:
            w.doc(desc)
        w.doc("`%s %s` — %s" % (o.method, o.path, ", ".join(o.statuses)))
        if o.security == "jwtOnly":
            w.doc("Requires an account session (JWT); API keys answer 401.")
        elif o.security in ("anonymous", "anonymousOrKey"):
            w.doc("Anonymous allowed.")
        w.line(method_signature(o, reg) + " {")
        w.indent()
        w.line(method_call(o))
        w.dedent()
        w.line("}")
    w.dedent()
    w.line("}")
    w.line()
    w.line("extension IrdClient {")
    w.indent()
    w.line("public var %s: %s { %s(client: self) }" % (module, MODULE_API[module], MODULE_API[module]))
    w.dedent()
    w.line("}")
    return w.text()


def emit_shared(defs, reg):
    w = Writer()
    w.lines.append(HEADER.rstrip("\n"))
    w.line()
    w.line("import Foundation")
    w.line()
    w.line("// MARK: - Types used by more than one module")
    w.line()
    for d in defs:
        emit_definition(w, d, reg)
    return w.text()


def emit_operations(ops):
    w = Writer()
    w.lines.append(HEADER.rstrip("\n"))
    w.line()
    w.line("import Foundation")
    w.line()
    w.line("extension IrdOperation {")
    w.indent()
    w.line("/// Every operation of the spec, in module order (%d)." % len(ops))
    w.line("public static let all: [IrdOperation] = %s" % " + ".join("%sOperations" % m for m in MODULE_ORDER))
    w.dedent()
    w.line("}")
    return w.text()


# ----------------------------------------------------------------------------- test artefacts

def synth_json(t, reg, key, variant):
    """A JSON value matching `t`; `full` fills every property, `nulls` omits optional
    ones and writes null into required-nullable ones."""
    if t.nullable and variant == "nulls":
        return None
    if t.kind == "prim":
        return {"String": key or "value", "Int": 1, "Double": 1.5, "Bool": True}[t.arg]
    if t.kind == "json":
        return key or "value"
    if t.kind == "array":
        return [synth_json(replace(t.arg, nullable=False), reg, key, variant)]
    if t.kind == "map":
        return {"k": synth_json(replace(t.arg, nullable=False), reg, key, variant)}
    d = reg.defs[t.arg]
    if d.kind == "enum":
        return d.values[0]
    if d.kind == "tuple":
        return [synth_json(it, reg, key, variant) for it in d.items]
    if d.kind == "oneof":
        const, sid = d.alternatives[0]
        out = OrderedDict([(d.discriminator, const)])
        out.update(synth_json(TypeRef("object", sid), reg, key, variant))
        return out
    out = OrderedDict()
    for p in d.props:
        if variant == "nulls":
            if not p.required:
                continue
            out[p.key] = None if p.type.nullable else synth_json(p.type, reg, p.key, variant)
        else:
            out[p.key] = synth_json(replace(p.type, nullable=False), reg, p.key, variant)
    return out


def swift_literal(t, reg, key):
    """Swift source for a minimal value of `t` (required properties only)."""
    if t.kind == "prim":
        return {"String": '"%s"' % (key or "value"), "Int": "1", "Double": "1.5", "Bool": "true"}[t.arg]
    if t.kind == "json":
        return '"%s"' % (key or "value")
    if t.kind == "array":
        return "[%s]" % swift_literal(replace(t.arg, nullable=False), reg, key)
    if t.kind == "map":
        return '["k": %s]' % swift_literal(replace(t.arg, nullable=False), reg, key)
    d = reg.defs[t.arg]
    if d.kind == "enum":
        return "." + enum_case(d.values[0])
    if d.kind == "tuple":
        return "%s(%s)" % (d.name, ", ".join("%s: %s" % (ident(f), swift_literal(it, reg, f)) for f, it in zip(d.fields, d.items)))
    if d.kind == "oneof":
        const, sid = d.alternatives[0]
        return ".%s(%s)" % (ident(const), swift_literal(TypeRef("object", sid), reg, key))
    args = ", ".join("%s: %s" % (p.swift, swift_literal(replace(p.type, nullable=False), reg, p.key))
                     for p in d.props if p.required and not p.type.nullable)
    return "%s(%s)" % (d.name, args)


def coverage_call(o, reg):
    args = ["%s: \"%s\"" % (p.swift, p.name) for p in o.path_params]
    args += ["%s: \"%s\"" % (p.swift, p.name) for p in o.query_params if p.required]
    if o.body is not None and o.body_required:
        args.append("body: %s" % swift_literal(o.body, reg, None))
    call = "c.%s.%s(%s)" % (o.module, o.name, ", ".join(args))
    return ("_ = try await " if o.response is not None else "try await ") + call


def coverage_url(o):
    path = re.sub(r"\{([^}]+)\}", lambda m: m.group(1), o.path)
    req = [p for p in o.query_params if p.required]
    q = "?" + "&".join("%s=%s" % (p.name, p.name) for p in req) if req else ""
    return BASE_URL + path + q


def emit_coverage(ops, reg):
    w = Writer()
    w.lines.append(HEADER.rstrip("\n"))
    w.line()
    w.line("import Foundation")
    w.line("@testable import IrdAPI")
    w.line()
    w.line("/// One typed call per operation with placeholder arguments (path parameters are their own names).")
    w.line("struct CoverageCase: Sendable {")
    w.indent()
    w.line("let key: String")
    w.line("let method: String")
    w.line("let url: String")
    w.line("let status: Int")
    w.line("let hasBody: Bool")
    w.line("let call: @Sendable (IrdClient) async throws -> Void")
    w.dedent()
    w.line("}")
    w.line()
    w.line("enum GeneratedCoverage {")
    w.indent()
    for m in MODULE_ORDER:
        w.line("static let %s: [CoverageCase] = [" % m)
        w.indent()
        for o in ops:
            if o.module != m:
                continue
            w.line('CoverageCase(key: "%s", method: "%s", url: "%s", status: %s, hasBody: %s) { c in %s },'
                   % (o.key, o.method, coverage_url(o), o.statuses[0], "true" if (o.body is not None and o.body_required) else "false",
                      coverage_call(o, reg)))
        w.dedent()
        w.line("]")
    w.line()
    w.line("static let all: [CoverageCase] = %s" % " + ".join(MODULE_ORDER))
    w.dedent()
    w.line("}")
    return w.text()


def emit_synth_cases(ops, reg):
    w = Writer()
    w.lines.append(HEADER.rstrip("\n"))
    w.line()
    w.line("import Foundation")
    w.line("@testable import IrdAPI")
    w.line()
    w.line("/// Decode-then-encode closures for every typed body and response; nil when the operation has none.")
    w.line("struct SynthCase: Sendable {")
    w.indent()
    w.line("let key: String")
    w.line("let body: (@Sendable (Data) throws -> Data)?")
    w.line("let response: (@Sendable (Data) throws -> Data)?")
    w.dedent()
    w.line("}")
    w.line()
    w.line("func roundTrip<T: Codable>(_ type: T.Type) -> @Sendable (Data) throws -> Data {")
    w.indent()
    w.line("{ data in try JSONEncoder().encode(try JSONDecoder().decode(T.self, from: data)) }")
    w.dedent()
    w.line("}")
    w.line()
    w.line("enum GeneratedSynth {")
    w.indent()
    for m in MODULE_ORDER:
        w.line("static let %s: [SynthCase] = [" % m)
        w.indent()
        for o in ops:
            if o.module != m:
                continue
            body = "roundTrip(%s.self)" % swift_type(replace(o.body, nullable=False), reg) if o.body is not None else "nil"
            resp = "roundTrip(%s.self)" % swift_type(replace(o.response, nullable=False), reg) if o.response is not None else "nil"
            w.line('SynthCase(key: "%s", body: %s, response: %s),' % (o.key, body, resp))
        w.dedent()
        w.line("]")
    w.line()
    w.line("static let all: [SynthCase] = %s" % " + ".join(MODULE_ORDER))
    w.dedent()
    w.line("}")
    return w.text()


def synth_fixture(ops, reg):
    out = OrderedDict()
    for o in ops:
        entry = OrderedDict()
        if o.body is not None:
            entry["body"] = OrderedDict([("full", synth_json(o.body, reg, None, "full")),
                                         ("nulls", synth_json(o.body, reg, None, "nulls"))])
        if o.response is not None:
            entry["response"] = OrderedDict([("full", synth_json(o.response, reg, None, "full")),
                                             ("nulls", synth_json(o.response, reg, None, "nulls"))])
        out[o.key] = entry
    return json.dumps(out, indent=1, ensure_ascii=False) + "\n"


# ----------------------------------------------------------------------------- driver

def generate(spec_path):
    spec = load_spec(spec_path)
    verify_assumptions(spec)
    reg = Registry()
    ops = build_operations(spec, reg)
    # query structs
    for o in ops:
        optional = [p for p in o.query_params if not p.required]
        if optional:
            d = Definition("Q_" + o.const, "query", params=optional, op_name=o.name)
            d.sites = [Site(o.key, o.module, "query", (), None)]
            reg.defs[d.id] = d
            reg.order.append(d.id)
            o.query_def = d
    assign_names(reg, ops)
    # file placement
    per_module = OrderedDict((m, []) for m in MODULE_ORDER)
    shared = []
    for did in reg.order:
        d = reg.defs[did]
        (per_module[d.module] if d.module in per_module else shared).append(d)
    files = OrderedDict()
    for m in MODULE_ORDER:
        files["Sources/IrdAPI/Generated/%s.swift" % MODULE_FILE[m]] = emit_module(m, [o for o in ops if o.module == m], reg, per_module[m])
    files["Sources/IrdAPI/Generated/Shared.swift"] = emit_shared(shared, reg)
    files["Sources/IrdAPI/Generated/Operations.swift"] = emit_operations(ops)
    files["Tests/IrdAPITests/Generated/CoverageCases.swift"] = emit_coverage(ops, reg)
    files["Tests/IrdAPITests/Generated/SynthCases.swift"] = emit_synth_cases(ops, reg)
    files["Tests/IrdAPITests/Fixtures/synth.json"] = synth_fixture(ops, reg)
    return files, reg, ops


def report(reg, ops):
    kinds = Counter(d.kind for d in reg.defs.values())
    print("operations: %d; shapes: %d; enums: %d; tuples: %d; oneofs: %d; query structs: %d" % (
        len(ops), kinds["object"], kinds["enum"], kinds["tuple"], kinds["oneof"], kinds["query"]))
    for w in reg.warnings:
        print("WARN " + w)
    for did in reg.order:
        d = reg.defs[did]
        print("%-6s %-36s %-14s %s" % (d.kind, d.name, d.module, d.sites[0].label() if d.sites else ""))


def write_files(root, files):
    generated_dirs = {os.path.dirname(p) for p in files if "/Generated/" in p}
    for rel in sorted(generated_dirs):
        full = os.path.join(root, rel)
        if os.path.isdir(full):
            for name in os.listdir(full):
                if name.endswith(".swift") and os.path.join(rel, name) not in files:
                    os.remove(os.path.join(full, name))
    for rel, text in files.items():
        full = os.path.join(root, rel)
        os.makedirs(os.path.dirname(full), exist_ok=True)
        with open(full, "w") as f:
            f.write(text)


def check(root, files):
    stale = False
    for rel, text in files.items():
        full = os.path.join(root, rel)
        current = open(full).read() if os.path.exists(full) else ""
        if current != text:
            stale = True
            print("STALE " + rel)
            for l in list(difflib.unified_diff(current.splitlines(), text.splitlines(), rel, "generated", lineterm=""))[:40]:
                print("  " + l)
    for rel in ("Sources/IrdAPI/Generated", "Tests/IrdAPITests/Generated"):
        full = os.path.join(root, rel)
        if os.path.isdir(full):
            for name in os.listdir(full):
                if name.endswith(".swift") and os.path.join(rel, name) not in files:
                    stale = True
                    print("EXTRA " + os.path.join(rel, name))
    return not stale


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--spec", default="spec/openapi.json")
    ap.add_argument("--out", default=".")
    ap.add_argument("--check", action="store_true")
    ap.add_argument("--report", action="store_true")
    args = ap.parse_args()
    root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
    os.chdir(root)
    files, reg, ops = generate(args.spec)
    if args.report:
        report(reg, ops)
        return
    if args.check:
        ok = check(args.out, files)
        print("gen-api --check: %s" % ("up to date" if ok else "STALE"))
        sys.exit(0 if ok else 1)
    write_files(args.out, files)
    for w in reg.warnings:
        print("WARN " + w)
    total = sum(t.count("\n") for t in files.values())
    print("gen-api: wrote %d files (%d lines) for %d operations" % (len(files), total, len(ops)))


if __name__ == "__main__":
    main()

static mirror of HEAD · about · clone: git clone https://ird.cod-sursa.ro/api-swift.git