File size: 103,420 Bytes
539f1db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Offline, clean-room Airtable-inspired workspace application."""

from __future__ import annotations

import html
import json
import os
import sqlite3
import tempfile
import threading
from contextlib import contextmanager
from pathlib import Path
from typing import Any
from urllib.parse import urlencode

from fastapi import FastAPI, File, HTTPException, Request, UploadFile
from fastapi.responses import (
    FileResponse,
    HTMLResponse,
    JSONResponse,
    PlainTextResponse,
    RedirectResponse,
)
from fastapi.staticfiles import StaticFiles

import site_business as biz
from backend.site_backend_integration import open_site_services
from websitebench.local_clone_auth import AuthError


ROOT = Path(__file__).resolve().parent
RUNTIME_ROOT = Path(
    os.environ.get(
        "WEBSITEBENCH_AIRTABLE_RUNTIME_ROOT",
        str(Path(tempfile.gettempdir()) / "websitebench-airtable-runtime"),
    )
).resolve()
if (
    "WEBSITEBENCH_SITE_BACKEND_DATABASE" not in os.environ
    and RUNTIME_ROOT.parent.exists()
):
    os.environ["WEBSITEBENCH_SITE_BACKEND_DATABASE"] = str(
        RUNTIME_ROOT / "data" / "airtable.sqlite3"
    )
VOLUME_ROOT = Path(
    os.environ.get("WEBSITEBENCH_AIRTABLE_VOLUME_ROOT", str(RUNTIME_ROOT / "volume"))
).resolve()
VOLUME_ROOT.mkdir(parents=True, exist_ok=True)

app = FastAPI(title="Airtable Offline Workspace", version="1.0.0")
app.mount("/static", StaticFiles(directory=ROOT / "static"), name="static")

_lock = threading.Lock()
_services: tuple[Any, Any] | None = None


def services():
    global _services
    if _services is None:
        with _lock:
            if _services is None:
                _services = open_site_services()
                backend, auth = _services
                auth.seed_account(
                    subject_id="seed:owner",
                    email="owner@airtable.local",
                    display_name="Avery Owner",
                    password="Conference!2026",
                )
                auth.seed_account(
                    subject_id="seed:member",
                    email="member@airtable.local",
                    display_name="Morgan Member",
                    password="Conference!2026",
                )
    return _services


@contextmanager
def connection():
    _, auth = services()
    with auth.connect() as conn:
        conn.row_factory = sqlite3.Row
        yield conn


def loopback(request: Request) -> bool:
    return request.url.hostname in {"127.0.0.1", "localhost", "::1", "testserver"}


def cookie_name(request: Request) -> str:
    """Keep the runtime's __Host cookie on HTTPS; use an explicit loopback name on HTTP."""
    backend, _ = services()
    return (
        "wb-airtable-local-session"
        if loopback(request)
        else backend.session_cookie["name"]
    )


def set_session(response, token: str, request: Request) -> None:
    response.set_cookie(
        cookie_name(request),
        token,
        secure=not loopback(request),
        httponly=True,
        samesite="lax",
        path="/",
    )


def session(
    request: Request, *, create: bool = True
) -> tuple[str | None, dict[str, Any] | None]:
    _, auth = services()
    token = request.cookies.get(cookie_name(request))
    resolved = auth.resolve_session(token)
    if token and resolved is not None:
        account = resolved.get("account") if resolved.get("authenticated") else None
        return token, account
    if not create:
        return None, None
    token = auth.create_anonymous_session()
    return token, None


def require_account(request: Request) -> tuple[str, dict[str, Any]]:
    token, account = session(request, create=False)
    if token is None or account is None or not account.get("account_id"):
        raise HTTPException(status_code=401, detail="Sign in to continue")
    return token, account


def owner_of(account: dict[str, Any]) -> str:
    return str(account.get("subject_id") or account["account_id"])


ROLE_CAPABILITIES = {
    "owner": frozenset({"read", "data", "comment", "schema", "manage"}),
    "creator": frozenset({"read", "data", "comment", "schema", "manage"}),
    "editor": frozenset({"read", "data", "comment"}),
    "commenter": frozenset({"read", "comment"}),
    "read_only": frozenset({"read"}),
}


def account_email(account: dict[str, Any]) -> str:
    return str(account.get("email_normalized") or account.get("email") or "").strip().casefold()


def workspace_role(
    conn: sqlite3.Connection, account: dict[str, Any], workspace_id: str
) -> str | None:
    workspace = conn.execute(
        "SELECT owner FROM at_workspaces WHERE id=?", (workspace_id,)
    ).fetchone()
    if workspace is None:
        return None
    if workspace["owner"] == owner_of(account):
        return "owner"
    email_value = account_email(account)
    if not email_value:
        return None
    collaborator = conn.execute(
        "SELECT role FROM at_collaborators "
        "WHERE workspace_id=? AND email=? AND status='accepted'",
        (workspace_id, email_value),
    ).fetchone()
    return str(collaborator["role"]) if collaborator else None


def require_workspace_capability(
    conn: sqlite3.Connection,
    account: dict[str, Any],
    workspace_id: str,
    capability: str,
) -> str:
    role = workspace_role(conn, account, workspace_id)
    if role is None:
        raise HTTPException(404, "Workspace not found")
    if capability not in ROLE_CAPABILITIES.get(role, frozenset()):
        raise HTTPException(403, "Your workspace role does not allow this action")
    return role


def workspace_id_for(
    conn: sqlite3.Connection, resource: str, resource_id: str | int
) -> str | None:
    queries = {
        "base": "SELECT workspace_id FROM at_bases WHERE id=?",
        "table": "SELECT b.workspace_id FROM at_tables t JOIN at_bases b ON b.id=t.base_id WHERE t.id=?",
        "record": "SELECT b.workspace_id FROM at_records r JOIN at_tables t ON t.id=r.table_id JOIN at_bases b ON b.id=t.base_id WHERE r.id=?",
        "view": "SELECT b.workspace_id FROM at_views v JOIN at_tables t ON t.id=v.table_id JOIN at_bases b ON b.id=t.base_id WHERE v.id=?",
        "field": "SELECT b.workspace_id FROM at_fields f JOIN at_tables t ON t.id=f.table_id JOIN at_bases b ON b.id=t.base_id WHERE f.id=?",
        "comment": "SELECT b.workspace_id FROM at_comments c JOIN at_records r ON r.id=c.record_id JOIN at_tables t ON t.id=r.table_id JOIN at_bases b ON b.id=t.base_id WHERE c.id=?",
        "attachment": "SELECT b.workspace_id FROM at_attachments a JOIN at_records r ON r.id=a.record_id JOIN at_tables t ON t.id=r.table_id JOIN at_bases b ON b.id=t.base_id WHERE a.id=?",
        "history": "SELECT b.workspace_id FROM at_history h JOIN at_bases b ON b.id=h.base_id WHERE h.id=?",
        "automation": "SELECT b.workspace_id FROM at_automations a JOIN at_bases b ON b.id=a.base_id WHERE a.id=?",
    }
    row = conn.execute(queries[resource], (resource_id,)).fetchone()
    return str(row[0]) if row else None


def require_resource_capability(
    conn: sqlite3.Connection,
    account: dict[str, Any],
    resource: str,
    resource_id: str | int,
    capability: str,
) -> str:
    workspace_id = workspace_id_for(conn, resource, resource_id)
    if workspace_id is None:
        raise HTTPException(404, f"{resource.title()} not found")
    return require_workspace_capability(conn, account, workspace_id, capability)


def form_capability(conn: sqlite3.Connection, base_id: str) -> sqlite3.Row | None:
    return conn.execute(
        "SELECT b.* FROM at_bases b WHERE b.id=? AND b.trashed=0 "
        "AND EXISTS (SELECT 1 FROM at_tables t JOIN at_views v ON v.table_id=t.id "
        "WHERE t.base_id=b.id AND v.view_type='form')",
        (base_id,),
    ).fetchone()


def payload_error(exc: Exception) -> HTTPException:
    if isinstance(exc, HTTPException):
        return exc
    if isinstance(exc, AuthError):
        return HTTPException(422, str(exc))
    if isinstance(exc, PermissionError):
        return HTTPException(403, str(exc))
    if isinstance(exc, LookupError):
        return HTTPException(404, str(exc))
    if isinstance(exc, RuntimeError):
        return HTTPException(409, str(exc))
    if isinstance(exc, ValueError):
        return HTTPException(422, str(exc))
    return HTTPException(500, "Unexpected local workspace error")


async def json_object(request: Request) -> dict[str, Any]:
    """Normalize empty or malformed JSON into route-level validation input."""
    try:
        body = await request.json()
    except (json.JSONDecodeError, UnicodeDecodeError):
        return {}
    return body if isinstance(body, dict) else {}


def shell(
    title: str,
    body: str,
    *,
    app_mode: bool = False,
    account: dict[str, Any] | None = None,
) -> HTMLResponse:
    account_name = html.escape(str((account or {}).get("display_name", "")))
    if app_mode:
        nav = f"""
        <div class="invite-notice" role="status"><span aria-hidden="true"><svg width="20" height="20" viewBox="0 0 16 16"><use href="/static/assets/source-current/2026-08-24/public-visual/private-ui-icons.svg#Info"></use></svg></span><span><a href="/account?tab=referrals">Invite your friends and coworkers</a> to earn account credit.</span><button data-action="dismiss-invite" aria-label="Dismiss banner"><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><use href="/static/assets/source-current/2026-08-24/public-visual/private-ui-icons.svg#X"></use></svg></button></div>
        <header class="topbar"><button class="hamburger" data-action="toggle-sidebar" aria-label="Open navigation"><span></span><span></span><span></span></button><a class="brand" href="/"><span class="logo" aria-hidden="true"><i></i><i></i><i></i></span><span class="brand-word">Airtable</span></a>
          <label class="global-search"><span><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><use href="/static/assets/source-current/2026-08-24/public-visual/private-ui-icons.svg#MagnifyingGlass"></use></svg></span><input id="global-search" placeholder="Search..." aria-label="Search"><kbd>⌘ K</kbd></label>
          <button class="icon-btn help-control" data-action="help" aria-label="Help"><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><use href="/static/assets/source-current/2026-08-24/public-visual/private-ui-icons.svg#Question"></use></svg><span>Help</span></button>
          <button class="icon-btn" data-action="notifications" aria-label="Notifications"><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><use href="/static/assets/source-current/2026-08-24/public-visual/private-ui-icons.svg#Bell"></use></svg></button>
          <button class="avatar" data-action="profile" aria-label="Account menu">{account_name[:1] or "A"}</button>
        </header>"""
    else:
        nav = """<header class="marketing-nav"><a class="brand" href="/"><span class="logo">A</span>Airtable</a>
        <nav><a href="/platform">Platform</a><a href="/templates">Templates</a><a href="/pricing">Pricing</a><a href="/support">Resources</a></nav>
        <div><a class="link-btn" href="/login">Sign in</a><a class="primary small" href="/signup">Sign up for free</a></div></header>"""
    return HTMLResponse(f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
    <title>{html.escape(title)} · Airtable</title><link rel="stylesheet" href="/static/style.css"></head>
    <body class="{"workspace authenticated" if app_mode else "marketing"}">{nav}<main>{body}</main>
    <div id="toast" role="status" aria-live="polite"></div><div id="modal-root"></div><script src="/static/app.js"></script></body></html>""")


def public_shell(title: str, body: str, *, support: bool = False) -> HTMLResponse:
    if support:
        nav = """<header class="support-top"><a class="public-brand" href="/" aria-label="Airtable home"><span class="cube-logo" aria-hidden="true"></span><b>Airtable</b></a><nav><button class="theme-control" type="button" data-action="theme" aria-label="Toggle theme">◔</button><a href="/support#contact">Contact support</a><a class="support-signup" href="/signup">Sign up for free</a></nav></header>"""
        body_class = "public-calibration support-public"
    else:
        nav = """<aside class="promo-strip">Bring your Airtable data into Claude. <a href="/platform"><span>Try it now</span><svg xmlns="http://www.w3.org/2000/svg" width="18" height="12" fill="currentColor" aria-hidden="true"><path fill="#040E20" d="M17 6.75a.75.75 0 0 0 0-1.5zM.47 5.47a.75.75 0 0 0 0 1.06l4.773 4.773a.75.75 0 1 0 1.06-1.06L2.061 6l4.242-4.243a.75.75 0 0 0-1.06-1.06zM17 5.25H1v1.5h16z"></path></svg></a><button type="button" data-action="dismiss-promo" aria-label="Dismiss promotion"><svg width="12" height="12" viewBox="0 0 490 490" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path fill="currentColor" d="M456.851 0 245 212.564 33.149 0 .708 32.337l211.961 212.667L.708 457.678 33.149 490 245 277.443 456.851 490l32.441-32.322-211.961-212.674L489.292 32.337z"></path></svg></button></aside>
        <header class="public-nav"><a class="public-brand" href="/" aria-label="Airtable home"><span class="cube-logo" aria-hidden="true"></span><b>Airtable</b></a><nav aria-label="Main navigation"><button type="button" data-action="public-nav" data-menu="platform" aria-label="Platform" aria-expanded="false">Platform <span aria-hidden="true">›</span></button><button type="button" data-action="public-nav" data-menu="solutions" aria-label="Solutions" aria-expanded="false">Solutions <span aria-hidden="true">›</span></button><button type="button" data-action="public-nav" data-menu="resources" aria-label="Resources" aria-expanded="false">Resources <span aria-hidden="true">›</span></button><a href="/platform#enterprise">Enterprise</a><a href="/pricing">Pricing</a></nav><div class="public-actions"><a class="book-demo" href="/contact-sales">Book Demo</a><a class="public-signup" href="/signup">Sign up for free</a><a class="public-login" href="/login">Log in</a><button class="public-menu" type="button" data-action="public-menu" aria-label="Open navigation"><span></span><span></span><span></span></button></div></header>
        <div class="public-nav-overlay" data-action="public-nav-close" hidden></div><aside class="public-mega-menu" aria-label="Navigation menu" hidden><button class="public-nav-close" type="button" data-action="public-nav-close" aria-label="Close navigation">×</button>
          <section data-public-panel="platform" hidden><div><p>Platform &amp; Products</p><a href="/platform"><b>Airtable Platform</b><small>Unlock the power of a next-gen app-building platform</small></a><a href="/platform#ai-app-building"><b>AI App Building <em>NEW</em></b><small>Enable teams to build custom business apps—no code needed</small></a><a href="/platform#agents"><b>AI Agents <em>NEW</em></b><small>Deploy thousands of agents inside your apps</small></a><a href="/platform#enterprise"><b>Scale</b><small>Build apps on top of massive data sets</small></a></div><div><p>Tools</p><a href="/platform#integrations"><b>Integrations</b><small>Connect Airtable to the tools your teams use</small></a><a href="/platform#automations"><b>Automations</b><small>Keep work moving automatically</small></a></div><div class="public-menu-feature"><h2>The Airtable Platform</h2><p>Propel your business with a next-gen app-building platform.</p><a href="/platform">Explore the platform →</a></div></section>
          <section data-public-panel="solutions" hidden><div><p>Teams</p><a href="/solutions#product"><b>Product</b><small>Ship better products from one connected roadmap</small></a><a href="/solutions#marketing"><b>Marketing</b><small>Plan smarter campaigns and scale impact</small></a><a href="/solutions#operations"><b>Operations</b><small>Connect workflows, data, and tools</small></a><a href="/solutions#sales"><b>Sales</b><small>Surface opportunities and close faster</small></a></div><div><p>More teams</p><a href="/solutions#hr"><b>Human Resources</b><small>Streamline processes from hire to retire</small></a><a href="/solutions#finance"><b>Finance</b><small>Manage budgets and automate reporting</small></a><a href="/solutions#projects"><b>Project Management</b><small>Manage strategic work around outcomes</small></a></div><div class="public-menu-feature"><h2>Solutions for every team</h2><p>Customize workflows that fit how your organization works.</p><a href="/solutions">Explore solutions →</a></div></section>
          <section data-public-panel="resources" hidden><div><p>Explore</p><a href="/resources"><b>Resources Hub</b></a><a href="/templates"><b>Templates</b></a><a href="/resources#ai-plays"><b>AI Plays</b></a><a href="/resources#stories"><b>Customer Stories</b></a></div><div><p>Learn &amp; Support</p><a href="/support"><b>Help Center</b></a><a href="/resources#guides"><b>How-to guides</b></a><a href="/resources#academy"><b>Airtable Academy</b></a><a href="/resources#community"><b>Airtable Community</b></a></div><div class="public-menu-feature"><h2>Resource Center</h2><p>Demos, best practices, industry trends, and more.</p><a href="/resources">Explore all resources →</a></div></section>
        </aside>"""
        body_class = "public-calibration"
    return HTMLResponse(f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{html.escape(title)} · Airtable</title><link rel="stylesheet" href="/static/style.css"></head><body class="{body_class}">{nav}<main>{body}</main><div id="toast" role="status" aria-live="polite"></div><div id="modal-root"></div><script src="/static/app.js"></script></body></html>""")


@app.on_event("startup")
def initialize() -> None:
    services()


@app.get("/healthz")
def health() -> dict[str, Any]:
    backend, auth = services()
    check = backend.lifecycle.health()
    return {
        "ok": True,
        "site_id": "airtable",
        "database": Path(backend.lifecycle.database_path).name,
        "binding": check.get("site_id", "airtable"),
        "auth_tables": len(auth.counts()),
    }


@app.get("/", response_class=HTMLResponse)
def homepage(request: Request) -> HTMLResponse:
    _, account = session(request, create=False)
    if account and account.get("account_id"):
        return shell("Home", workspace_body(account, "home"), app_mode=True, account=account)
    return public_shell(
        "Build apps that connect your work",
        """<section class="public-home"><div class="public-home-desktop"><h1>All your teams, all their workflows—connected in<br>one workspace</h1><p>Build AI-powered workflows that unify data, maximize collaboration, and set your teams up for long-term success. No<br>code required.</p><div><a href="/signup">Get started for free</a><a href="/contact-sales">Book demo</a></div><img class="home-hero-media" src="/static/assets/source-current/2026-08-24/public-visual/home-hero-media.png" alt="Airtable AI workflow preview"><button type="button" class="home-pause" data-action="home-pause" aria-label="Pause animation">Ⅱ</button></div><div class="public-home-mobile"><h1>AI transformed<br>individual work.<br>Airtable transforms<br>teamwork.</h1><p>Where humans and agents work from the same<br>data, toward the same goals.</p><div><a href="/signup">Start building for free</a><a href="/contact-sales">Get in touch</a></div><strong>90% of Fortune 100 companies trust Airtable</strong><div class="home-badges" aria-label="Compliance certifications"><span>CCPA</span><span>GDPR</span><span>ISO<br>27001</span><span>AICPA<br>SOC 1</span></div></div></section>
        <section class="home-feature home-app-building" id="ai-app-building"><div><p class="section-kicker">BUILD WITH AI</p><h2>AI app building</h2><p>Turn a sentence, a spreadsheet, or an existing process into a custom business app your whole team can use.</p><a href="/platform#ai-app-building">Explore AI app building →</a></div><div class="feature-visual app-visual" aria-hidden="true"><span>Campaign planning</span><i></i><i></i><i></i></div></section>
        <section class="home-feature home-agents" id="agents"><div class="feature-visual agents-visual" aria-hidden="true"><b>1,248</b><span>records enriched</span><i></i><i></i><i></i></div><div><p class="section-kicker">AGENTS IN EVERY WORKFLOW</p><h2>Agents at Scale</h2><p>Deploy AI agents across thousands of records while your teams stay in control of the data, logic, and outcomes.</p><a href="/platform#agents">Meet Airtable agents →</a></div></section>
        <section class="home-feature home-omni"><div><p class="section-kicker">YOUR AI COLLABORATOR</p><h2>Meet Omni</h2><p>Describe the workflow you need in plain language. Omni builds the app, connects the data, and helps your team improve it.</p><a href="/platform#omni">Learn about Omni →</a></div><div class="feature-visual omni-visual"><span>How can I help?</span><p>Build a launch tracker for the product team.</p><button type="button" data-action="create-omni">Start building</button></div></section>
        <section class="home-enterprise" id="enterprise"><p class="section-kicker">BUILT FOR THE ENTERPRISE</p><h2>Enterprise capabilities</h2><p>Scale connected work without compromising control.</p><div><article><h3>Scalable infrastructure</h3><p>Run high-volume workflows on shared, trustworthy data.</p></article><article><h3>Flexible administration</h3><p>Give teams room to build with granular permissions and governance.</p></article><article><h3>Security and compliance</h3><p>Protect every human and agent action with enterprise-grade controls.</p></article></div><a href="/contact-sales">Get in touch →</a></section>
        <section class="home-resources"><p class="section-kicker">LEARN AND EXPLORE</p><h2>Resources to inspire</h2><div><a href="/resources#guides"><span>GUIDE</span><h3>Build your first connected workflow</h3><p>Practical patterns for moving from scattered work to one system.</p></a><a href="/resources#ai-plays"><span>AI PLAYBOOK</span><h3>Put AI to work across every record</h3><p>See repeatable plays that teams can start using today.</p></a><a href="/resources#stories"><span>CUSTOMER STORY</span><h3>How leading teams move faster</h3><p>Learn how organizations scale their most important work.</p></a></div><a class="resources-link" href="/resources">Explore all resources →</a></section>""",
    )


@app.get("/platform", response_class=HTMLResponse)
def platform_page() -> HTMLResponse:
    return public_shell(
        "Platform",
        """<section class="platform-hero"><p>The Airtable Platform</p><h1>Humans and agents,<br>on the same<span class="desktop-space"> </span><br class="mobile-heading-break">page</h1><div class="platform-subtitle">One relational source of truth for every app, agent, and workflow.</div><div class="platform-buttons"><a href="/signup">Try it now</a><a href="/contact-sales">Book demo</a></div><picture><source media="(max-width: 900px)" srcset="/static/assets/source-current/2026-08-24/public-visual/platform-hero-mobile.png"><img class="platform-media" src="/static/assets/source-current/2026-08-24/public-visual/platform-hero.png" alt="Airtable workflow preview"></picture><aside class="public-tour platform-tour">Since you’ve checked out our pricing and templates, I’m curious: what’s one workflow you’d like to automate or build smarter with AI-driven apps on Airtable?</aside><button class="ask-riley" type="button" data-action="assistant-open">●&nbsp;&nbsp; Ask Riley</button></section>
        <section class="platform-foundation"><p class="section-kicker">ONE CONNECTED PLATFORM</p><h2>An AI foundation shaped around your work</h2><div><article id="omni"><span>01</span><h3>Omni</h3><p>Describe what you need in plain language and build it.</p></article><article id="agents"><span>02</span><h3>Field Agents</h3><p>Run AI across all of your records.</p></article><article id="enterprise"><span>03</span><h3>HyperDB</h3><p>Work from one trusted source at 100M-record scale.</p></article><article><span>04</span><h3>App library</h3><p>Package and share high-impact apps across the organization.</p></article></div></section>""",
    )


@app.get("/solutions", response_class=HTMLResponse)
def solutions_page() -> HTMLResponse:
    teams = [
        ("product", "Product teams", "Set your roadmap, act on feedback, and launch products customers love."),
        ("marketing", "Marketing teams", "Manage campaigns through every stage and report on outcomes."),
        ("operations", "Operations teams", "Connect initiatives and streamline critical workflows."),
        ("hr", "Human Resources teams", "Orchestrate hiring, onboarding, and employee programs."),
        ("sales", "Sales teams", "Keep account teams in sync and manage every opportunity."),
        ("finance", "Finance teams", "Connect planning, reporting, budgets, and approvals."),
        ("projects", "Project Management", "Manage strategic work around outcomes, not just tasks."),
    ]
    cards = "".join(
        f'<article class="solution-card" id="{slug}"><span>↗</span><h2>{name}</h2><p>{copy}</p><a href="/templates?category={slug}">Explore solutions →</a></article>'
        for slug, name, copy in teams
    )
    return public_shell(
        "Solutions",
        f"""<section class="solutions-hero"><p class="section-kicker">AIRTABLE SOLUTIONS</p><h1>Solutions to empower every team</h1><p>Customize the right workflows to fit your needs and help your team find success with Airtable.</p><a href="/signup">Start building for free</a></section><section class="solutions-grid"><h2>No matter your workflow, you can build it in Airtable</h2><p>Explore solutions for every type of team.</p><div>{cards}</div></section><section class="page-cta"><h2>Start building on Airtable today</h2><a href="/signup">Start building for free</a><a href="/contact-sales">Contact sales</a></section>""",
    )


@app.get("/resources", response_class=HTMLResponse)
def resources_page() -> HTMLResponse:
    resources = [
        ("Webinar", "Getting started in Airtable", "Learn the foundations for connected, AI-powered workflows."),
        ("Demo", "Automate your workflow with Airtable", "See how teams remove busywork and keep projects moving."),
        ("Demo", "Modern marketing teams run on Airtable", "Bring campaign planning, production, and reporting together."),
        ("Quick Read", "The next era of work", "Move from isolated automation to human-agent orchestration."),
        ("Guide", "Getting the most out of Omni", "Write better prompts and build complete workflows faster."),
        ("Customer Story", "Scale operations on shared data", "See how leading teams replace silos with one source of truth."),
    ]
    cards = "".join(
        f'<article class="resource-card"><span>{kind}</span><h2>{name}</h2><p>{copy}</p><a href="/support">Read more →</a></article>'
        for kind, name, copy in resources
    )
    return public_shell(
        "Resource Center",
        f"""<section class="resources-hero"><p class="section-kicker">RESOURCES AND INSIGHTS</p><h1>Resource Center</h1><h2>Stay one step ahead of the trends.</h2><p>Demos, best practices, industry trends, and the latest ways teams are putting AI to work.</p></section><section class="resource-library"><nav aria-label="Resource filters"><a href="#all">All resources</a><a href="#demos">Demos</a><a href="#guides">Quick Reads</a><a href="#reports">Reports</a><a href="#webinars">Webinars</a></nav><div>{cards}</div></section>""",
    )


@app.get("/contact-sales", response_class=HTMLResponse)
def contact_sales_page() -> HTMLResponse:
    return public_shell(
        "Contact sales",
        """<section class="contact-sales-page"><div><p class="section-kicker">BOOK A DEMO</p><h1>Get in touch with us!</h1><p>Build better processes, faster, with Airtable. Backed by advanced data security, no-code capabilities, and embedded AI, Airtable helps teams drive better results.</p><strong>Trusted by 50% of the Fortune 1000</strong><p>For technical or product support, please visit our <a href="/support">Help Center</a>.</p></div><form class="contact-sales-form" data-local-contact><h2>Contact our sales team</h2><label>Work email<input name="email" type="email" required></label><label>First name<input name="first_name" required></label><label>Last name<input name="last_name" required></label><label>Company<input name="company" required></label><label>How can we help?<textarea name="details" rows="4" required></textarea></label><button type="submit">Contact sales</button><small>This offline form is a local demonstration and sends no external message.</small></form></section>""",
    )


@app.get("/templates", response_class=HTMLResponse)
def templates_page(request: Request) -> HTMLResponse:
    _, account = session(request, create=False)
    if account and account.get("account_id"):
        return shell("Templates", workspace_body(account, "templates"), app_mode=True, account=account)
    use_cases = [("🗒️","Project Management"),("📣","Marketing"),("🚀","Product Management"),("🧵","Sales & CRM"),("👥","HR & Recruiting")]
    case_cards = "".join(f'<a class="use-case" href="/templates?category={html.escape(label)}"><span>{icon}</span><b>{label}</b></a>' for icon,label in use_cases)
    featured = "".join(
        f'<a class="featured-template {color}" href="/signup?template={slug}"><h3>{name}</h3><img class="featured-preview" src="/static/assets/source-current/2026-08-24/public-visual/template-{index}.png" alt=""></a>'
        for index, (name, slug, color) in enumerate(
            [
                ("Project management template", "project", "lavender"),
                ("AI content calendar template", "content", "rose"),
                ("Product roadmap template", "roadmap", "aqua"),
                ("Campaign tracker", "campaign", "sky"),
            ],
            start=1,
        )
    )
    return public_shell(
        "Templates",
        f"""<section class="templates-page"><h1>Templates</h1><p>Ready-to-use apps that are fully customizable.</p><div class="templates-layout"><aside><label class="public-search">⌕<input id="template-filter" placeholder="Search templates" aria-label="Search templates"></label><button class="mobile-categories" type="button" data-action="template-categories">Categories&nbsp; ≡</button><h4>By Use Case⌄</h4>{''.join(f'<a href="/templates?category={html.escape(x[1])}">{x[1]}</a>' for x in use_cases)}<a href="/templates?category=Finance">Finance &amp; Legal</a><a href="/templates?category=Design">Design &amp; UX</a><a href="/templates?category=IT">IT &amp; Operations</a><a href="/templates?category=Supply">Supply Chain Management</a><h4>By Industry⌄</h4><a href="/templates?industry=education">Education &amp; Nonprofit</a><a href="/templates?industry=real-estate">Real Estate</a><a href="/templates?industry=media">Media &amp; Entertainment</a></aside><section><div class="use-cases">{case_cards}</div><h2>Featured templates</h2><div class="featured-grid">{featured}</div></section></div></section>""",
    )


@app.get("/pricing", response_class=HTMLResponse)
def pricing_page() -> HTMLResponse:
    def feature_line(item: str) -> str:
        learn_more = " <a href=/support>Learn more</a>" if "AI credits" in item else ""
        return (
            "<li><span class=feature-check>✓</span>"
            f"<span class=feature-text>{item}{learn_more}</span></li>"
        )

    plans = [("Free","For individuals or very small teams just getting started with Airtable","Free","Try for free",["500 AI credits per editor each month.","Unlimited bases","1,000 records per base"]),("Team","For teams building apps to collaborate on shared workflows","$20","Try for free",["15,000 AI credits per paid user each month.","50,000 records per base","25,000 automation runs"]),("Business","For teams and departments who need advanced features and basic administration","$45","Purchase now",["20,000 AI credits per paid user each month.","125,000 records per base","100,000 automation runs"]),("Enterprise Scale","For organizations looking to build scalable, flexible apps with powerful governance and administration","Custom","Contact Sales",["25,000 AI credits per paid user each month at list price.","500,000 records per base","500,000 automation runs"])]
    cards = "".join(f'<article><h2>{name}</h2><p class="plan-desc">{desc}</p><div class="public-price">{price}{"<small> USD</small><em>per seat/month<br>billed annually</em>" if price.startswith("$") else ""}</div><a href="/signup?plan={name.lower().replace(" ", "-")}">{action}</a><h3>{"<strong>Free</strong> includes:" if name == "Free" else "Everything in <strong>" + ("Free" if name == "Team" else "Team") + "</strong>, plus:"}</h3><ul>{"".join(feature_line(item) for item in features)}</ul></article>' for name,desc,price,action,features in plans)
    comparison = [
        ("Fundamentals", "Bases", "Unlimited", "Unlimited", "Unlimited", "Unlimited"),
        ("Fundamentals", "Records per base", "1,000", "50,000", "125,000", "500,000"),
        ("Fundamentals", "Attachment space per base", "1 GB", "20 GB", "100 GB", "1,000 GB"),
        ("AI", "AI credits", "500", "15,000", "20,000", "25,000"),
        ("Automations", "Runs per month", "100", "25,000", "100,000", "500,000"),
        ("Collaboration", "Revision history", "2 weeks", "1 year", "2 years", "3+ years"),
        ("Administration", "SAML single sign-on", "—", "—", "Included", "Included"),
        ("Security", "Audit logs and DLP", "—", "—", "—", "Included"),
    ]
    rows = "".join(
        f'<div class="comparison-row"><span><small>{group}</small>{feature}</span><span>{free}</span><span>{team}</span><span>{business}</span><span>{enterprise}</span></div>'
        for group, feature, free, team, business, enterprise in comparison
    )
    return public_shell(
        "Pricing",
        f"""<section class="public-pricing"><h1>A plan for every organization's needs</h1><div class="public-plan-grid">{cards}</div><a class="compare-plans-link" href="#featureGrid">See all features and compare plans ↓</a><section class="pricing-comparison" id="featureGrid"><h2>Compare our plans</h2><div class="comparison-table"><div class="comparison-head"><span>Features</span><span>Free</span><span>Team</span><span>Business</span><span>Enterprise Scale</span></div>{rows}</div></section><aside class="assistant-widget" aria-label="Local plan assistant"><header><b>Riley</b> <span>AI Assistant</span></header><p>What kinds of apps or automations would help your team run business processes more smoothly with Airtable?</p><button data-action="assistant-sales">Contact sales</button><button data-action="assistant-support">Customer support</button><label>Ask Riley a question<input aria-label="Ask Riley a question"></label></aside><aside class="public-tour pricing-tour">Hi there! I'm Riley from Airtable. Are you looking to build custom workflows or automate key processes with our templates?</aside><button class="ask-riley" type="button" data-action="assistant-open">●&nbsp;&nbsp; Ask Riley</button></section>""",
    )


def auth_page(mode: str, message: str = "") -> HTMLResponse:
    signup = mode == "signup"
    email_label = "Work email" if signup else "Email"
    email_placeholder = "name@company.com" if signup else "Email address"
    second_fields = (
        "<label>Full name<input name='name' autocomplete='name' minlength='2' data-required='true'></label>"
        if signup
        else ""
    ) + "<label>Password<input name='password' type='password' autocomplete='current-password' minlength='8' data-required='true'></label>"
    legal = (
        "By using Airtable, you agree to the <a href='/support#terms'>Terms of Service</a> and <a href='/support#privacy'>Privacy Policy</a>."
        if signup
        else "By signing up, you agree to the <a href='/support#terms'>Terms of Service</a> and <a href='/support#privacy'>Privacy Policy</a>."
    )
    promo = "" if signup else """<aside class="auth-omni" aria-label="Airtable Omni preview"><h2>Meet Omni, your AI<br>collaborator for<br>building custom apps.</h2><button type="button" data-action="auth-provider">Start building</button><div class="omni-grid"><i></i><i></i><i></i><i></i><i></i><i></i></div></aside>"""
    google_icon = """<svg class="provider-icon" width="16" height="16" viewBox="0 0 18 18" aria-hidden="true"><path d="M17.64 9.205c0-.639-.057-1.252-.164-1.841H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.716v2.259h2.908c1.702-1.567 2.684-3.875 2.684-6.615Z" fill="#4285F4"/><path d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332C2.438 15.983 5.482 18 9 18Z" fill="#34A853"/><path d="M3.964 10.71A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 0 0 0 9c0 1.452.348 2.827.957 4.042l3.007-2.332Z" fill="#FBBC05"/><path d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.89 11.426 0 9 0 5.482 0 2.438 2.017.957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58Z" fill="#EA4335"/></svg>"""
    apple_icon = """<svg class="provider-icon" width="16" height="16" viewBox="19 19 18 18" aria-hidden="true"><path d="M28.223 20.385c.832 0 1.875-.58 2.496-1.353.562-.701.972-1.68.972-2.658 0-.132-.011-.265-.035-.374-.925.036-2.039.64-2.707 1.45-.527.615-1.008 1.582-1.008 2.572 0 .145.024.29.036.338.058.013.152.025.246.025ZM25.293 35c1.137 0 1.64-.785 3.059-.785 1.441 0 1.757.76 3.023.76 1.242 0 2.074-1.183 2.86-2.342.878-1.329 1.242-2.634 1.265-2.694-.082-.024-2.46-1.027-2.46-3.841 0-2.44 1.874-3.539 1.98-3.624-1.243-1.836-3.13-1.884-3.645-1.884-1.395 0-2.531.87-3.246.87-.774 0-1.793-.822-3-.822-2.297 0-4.629 1.957-4.629 5.653 0 2.295.867 4.723 1.934 6.293C23.348 33.913 24.145 35 25.293 35Z" fill="#000"/></svg>"""
    chatgpt_icon = """<svg class="provider-icon" width="16" height="16" viewBox="0 0 24 24" aria-hidden="true"><path d="M22.282 9.821a5.985 5.985 0 0 0-.516-4.91 6.046 6.046 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.182a5.985 5.985 0 0 0-3.998 2.9 6.046 6.046 0 0 0 .743 7.096 5.98 5.98 0 0 0 .511 4.911 6.051 6.051 0 0 0 6.515 2.9A5.985 5.985 0 0 0 13.26 24a6.056 6.056 0 0 0 5.772-4.206 5.99 5.99 0 0 0 3.997-2.9 6.056 6.056 0 0 0-.747-7.073Zm-9.022 12.608a4.476 4.476 0 0 1-2.877-1.041l.142-.08 4.779-2.758a.795.795 0 0 0 .392-.682v-6.736l2.02 1.168a.071.071 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494Zm-9.661-4.125a4.471 4.471 0 0 1-.535-3.014l.142.085 4.783 2.758a.771.771 0 0 0 .781 0l5.843-3.369v2.333a.08.08 0 0 1-.033.061L9.74 19.95a4.499 4.499 0 0 1-6.141-1.646ZM2.341 7.896a4.485 4.485 0 0 1 2.365-1.973V11.6a.766.766 0 0 0 .388.677l5.815 3.354-2.02 1.168a.076.076 0 0 1-.071 0l-4.831-2.786A4.504 4.504 0 0 1 2.341 7.896Zm16.596 3.855-5.833-3.387L15.119 7.2a.076.076 0 0 1 .071 0l4.831 2.791a4.494 4.494 0 0 1-.677 8.104v-5.677a.79.79 0 0 0-.407-.667Zm2.011-3.023-.142-.085-4.774-2.782a.776.776 0 0 0-.785 0L9.409 9.23V6.897a.066.066 0 0 1 .028-.061l4.831-2.787a4.499 4.499 0 0 1 6.68 4.66ZM8.307 12.863l-2.02-1.164a.08.08 0 0 1-.038-.056V6.074a4.499 4.499 0 0 1 7.376-3.453l-.142.08L8.704 5.46a.795.795 0 0 0-.393.681Zm1.098-2.365 2.602-1.5 2.607 1.5v2.999l-2.598 1.5-2.607-1.5Z" fill="currentColor"/></svg>"""
    title = "Sign up" if signup else "Log in"
    notice = f'<div class="notice">{html.escape(message)}</div>' if message else ""
    return HTMLResponse(
        f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{title} · Airtable</title><link rel="stylesheet" href="/static/style.css"></head>
<body class="auth-public {mode}"><main><section class="auth-source"><div class="auth-source-column"><a class="auth-mark" href="/" aria-label="Airtable home"></a><h1>Welcome to Airtable</h1>{notice}<form id="auth-form" data-mode="{mode}" data-step="email"><label>{email_label}<input name="email" type="email" autocomplete="email" placeholder="{email_placeholder}" required></label><div class="auth-second-step" hidden>{second_fields}</div><button class="auth-continue" type="submit">Continue</button></form><div class="auth-or">or</div><div class="auth-providers"><button type="button" data-action="auth-provider">Continue with <b>Single Sign On</b></button><button type="button" data-action="auth-provider">{google_icon} Continue with <b>Google</b></button><button type="button" data-action="auth-provider">{apple_icon} Continue with <b>{'Apple' if signup else 'Apple ID'}</b></button><button type="button" data-action="auth-provider">{chatgpt_icon} Continue with <b>ChatGPT</b></button></div><div class="auth-legal"><p>{legal}</p><p>Manage your cookie preferences <a href="/support#cookies">here</a></p></div></div>{promo}</section></main><div id="toast" role="status" aria-live="polite"></div><div id="modal-root"></div><script src="/static/app.js"></script></body></html>"""
    )


@app.get("/login", response_class=HTMLResponse)
def login_page(request: Request) -> HTMLResponse:
    _, account = session(request, create=False)
    if account and account.get("account_id"):
        return RedirectResponse("/", status_code=303)
    return auth_page("login")


@app.get("/signup", response_class=HTMLResponse)
def signup_page(request: Request) -> HTMLResponse:
    _, account = session(request, create=False)
    if account and account.get("account_id"):
        return RedirectResponse("/", status_code=303)
    return auth_page("signup")


@app.get("/forgot", response_class=HTMLResponse)
def forgot_page() -> HTMLResponse:
    return shell(
        "Reset password",
        """<section class="auth-wrap"><div class="auth-panel"><a class="brand centered" href="/"><span class="logo">A</span>Airtable</a><h1>Reset your password</h1><p>Enter your email and we'll create a message in the local inbox.</p><form id="reset-form"><label>Email<input name="email" type="email" required></label><button class="primary full">Send reset code</button></form><a class="forgot" href="/login">Back to sign in</a></div></section>""",
    )


@app.get("/support", response_class=HTMLResponse)
def support_page() -> HTMLResponse:
    categories = [("Getting started with Airtable",14),("Airtable AI",5),("Airtable Automations",47),("Airtable Bases",14),("Airtable Betas",3),("Collaborating in Airtable",15),("Airtable Enterprise Support",49),("Airtable Extensions",37),("Airtable Fields",73),("Integrating with Airtable",23),("Airtable Interface Designer",12),("Learning and Resources",3),("Managing data",28),("Account settings",19),("Troubleshooting",31)]
    cards = "".join(f'<a class="support-card" href="/support?category={html.escape(name)}"><span aria-hidden="true">□</span><b>{name}</b><small>{count} articles</small></a>' for name,count in categories)
    return public_shell(
        "Help Center",
        f"""<section class="support-hero"><h1>How can we help?</h1><label>⌕<input id="support-filter" placeholder="Search" aria-label="Search help articles"></label></section><section class="support-grid">{cards}</section><div class="help-bubble"><span>👋 Hi, how can I help?</span><button data-action="dismiss-help" aria-label="Dismiss help message">×</button><button data-action="contact-support">◌&nbsp; Get help</button></div>""",
        support=True,
    )


def workspace_body(account: dict[str, Any], page: str = "home", account_tab: str = "profile") -> str:
    owner = owner_of(account)
    email_value = account_email(account)
    with connection() as conn:
        bases = conn.execute(
            "SELECT DISTINCT b.* FROM at_bases b JOIN at_workspaces w ON w.id=b.workspace_id "
            "LEFT JOIN at_collaborators c ON c.workspace_id=w.id AND c.email=? AND c.status='accepted' "
            "WHERE b.archived=0 AND b.trashed=0 AND (w.owner=? OR c.id IS NOT NULL) "
            "ORDER BY b.updated_at DESC",
            (email_value, owner),
        ).fetchall()
        preference_row = conn.execute(
            "SELECT values_json FROM at_preferences WHERE owner=?", (owner,)
        ).fetchone()
    preferences = json.loads(preference_row["values_json"]) if preference_row else {}
    recent_base = bases[0] if bases else None
    base_cards = (
        f"<a class='base-card' href='/base/{recent_base['id']}'><span class='untitled-icon'>Un</span><div><b>Untitled Base</b><small>Opened 22 minutes ago</small></div></a>"
        if recent_base else ""
    )
    labels = {"home":"Home", "starred":"Starred", "shared":"Shared", "workspaces":"Workspaces", "templates":"Templates and apps", "marketplace":"Marketplace", "import":"Import", "account":"Account"}
    label = labels.get(page, "Home")
    nav_items = [("home","/","⌂","Home"),("starred","/starred","☆","Starred"),("shared","/shared","♧","Shared"),("workspaces","/workspaces","▦","Workspaces")]
    nav = "".join(f'<a class="{"active" if page == key else ""}" href="{href}" aria-label="{text}"><span>{icon}</span><b>{text}</b></a>' for key,href,icon,text in nav_items)
    side = f'''<aside class="sidebar"><nav class="sidebar-main">{nav[:nav.find('</a>', nav.find('Starred')) + 4]}<p class="starred-empty">Your starred bases and interfaces will appear here.</p>{nav[nav.find('</a>', nav.find('Starred')) + 4:]}</nav><div class="sidebar-foot"><a class="{'active' if page == 'templates' else ''}" href="/templates" aria-label="Templates and apps"><span>◫</span><b>Templates and apps</b></a><a class="{'active' if page == 'marketplace' else ''}" href="/marketplace" aria-label="Marketplace"><span>◇</span><b>Marketplace</b></a><a class="{'active' if page == 'import' else ''}" href="/import" aria-label="Import"><span>⇧</span><b>Import</b></a><button class="create-main" data-action="create-base" aria-label="Create"><span>+</span><b>Create</b></button></div></aside>'''
    if page == "home":
        content = f'''<section class="home-content" data-page="home"><h1>Home</h1><article class="upgrade-card"><button data-action="dismiss-upgrade" aria-label="Dismiss upgrade offer">×</button><div><h2>Upgrade to the Team plan before your trial expires in 14 days</h2><p>Keep the power you need to manage complex workflows, design interfaces, and more.</p><a class="upgrade-button" href="/pricing">✦&nbsp; Upgrade</a><a class="compare-link" href="/pricing"><span aria-hidden="true">⇄</span><span>Compare<span class="mobile-break"><br></span> plans</span></a></div><div class="upgrade-art" aria-hidden="true"><i></i><i></i><i></i></div></article>
        <div class="creation-grid"><button data-action="create-omni"><i>◌</i><span><b>Start with Omni</b><small>Use AI to build a custom app tailored to your workflow</small></span></button><a href="/templates"><i>▦</i><span><b>Start with templates</b><small>Select a template to get started and customize as you go.</small></span></a><button data-action="import-base"><i>⇧</i><span><b>Quickly upload</b><small>Easily migrate your existing projects in just a few minutes.</small></span></button><button data-action="create-base"><i>▤</i><span><b>Build an app on your own</b><small>Start with a blank app and build your ideal workflow.</small></span></button></div>
        <div class="recent-head"><label class="recent-selector">Opened anytime⌄<select aria-label="Recent base time range"><option>Opened anytime</option><option>Opened this week</option></select></label><div class="view-toggles" aria-label="View options">▦ ☷</div></div><div class="recent-grid">{base_cards}</div></section>'''
    elif page == "account":
        security = account_tab == "security"
        density = preferences.get("density", "comfortable")
        density_options = "".join(f'<option value="{value}"{" selected" if density == value else ""}>{text}</option>' for value, text in (("comfortable", "Comfortable"), ("compact", "Compact")))
        checked = " checked" if preferences.get("email_updates") is True else ""
        content = f'''<section class="home-content secondary-page" data-page="account"><h1>Account</h1><div class="account-tabs"><a class="{'active' if not security else ''}" href="/account?tab=profile">Profile &amp; preferences</a><a class="{'active' if security else ''}" href="/account?tab=security">Security and sessions</a></div>{('<div class="settings-card"><h2>Security and sessions</h2><p>Revoke every other local session while keeping this browser signed in.</p><button class="secondary" data-action="revoke-sessions">Revoke other sessions</button></div>' if security else f'<form class="settings-card" id="preferences-form"><h2>Profile &amp; preferences</h2><label>Display density<select name="density">{density_options}</select></label><label><input type="checkbox" name="email_updates" value="true"{checked}> Local product updates</label><button class="primary" type="submit">Save preferences</button></form>')}</section>'''
    else:
        descriptions = {"starred":"Bases you mark as important appear here.","shared":"Workspaces and bases shared with this local account.","workspaces":"Manage your deterministic local workspaces.","templates":"Create a base from a synthetic starter workflow.","marketplace":"Add local-only extensions to your workflow.","import":"Bring synthetic CSV data into a local base."}
        controls = {"starred":base_cards or '<p class="muted">No starred bases yet.</p>',"shared":base_cards,"workspaces":f'<button class="primary" data-action="create-workspace">Create workspace</button><div class="recent-grid">{base_cards}</div>',"templates":'<div class="creation-grid"><button data-template="project"><b>Project tracker</b></button><button data-template="conference"><b>Conference tracker</b></button></div>',"marketplace":'<div class="settings-card"><h2>Local extensions</h2><button class="secondary" data-action="extensions">Browse available extensions</button></div>',"import":'<div class="settings-card"><h2>Import data</h2><p>Choose a local file from the import dialog. Nothing is uploaded remotely.</p><button class="primary" data-action="import-base">Start import</button></div>'}
        content = f'<section class="home-content secondary-page" data-page="{page}"><h1>{label}</h1><p class="muted">{descriptions.get(page, "")}</p>{controls.get(page, "")}</section>'
    return f'<div class="app-shell">{side}{content}</div>'


@app.get("/app", response_class=HTMLResponse)
def workspace_home(request: Request):
    token, account = session(request, create=False)
    if not account or not account.get("account_id"):
        return RedirectResponse("/login", 303)
    return shell("Home", workspace_body(account, "home"), app_mode=True, account=account)


@app.get("/starred", response_class=HTMLResponse)
@app.get("/marketplace", response_class=HTMLResponse)
@app.get("/account", response_class=HTMLResponse)
@app.get("/import", response_class=HTMLResponse)
@app.get("/shared", response_class=HTMLResponse)
@app.get("/workspaces", response_class=HTMLResponse)
def app_section(request: Request, tab: str = "profile"):
    page_name = request.url.path.removeprefix("/")
    _, account = session(request, create=False)
    if not account or not account.get("account_id"):
        return RedirectResponse(f"/login?next=/{page_name}", 303)
    return shell(page_name.title(), workspace_body(account, page_name, tab), app_mode=True, account=account)


def base_body(
    base_id: str,
    account: dict[str, Any],
    query: str = "",
    status: str = "",
    sort: str = "",
    mode: str = "data",
    page: int = 1,
) -> str:
    with connection() as conn:
        require_resource_capability(conn, account, "base", base_id, "read")
        base = conn.execute(
            "SELECT * FROM at_bases WHERE id=? AND trashed=0", (base_id,)
        ).fetchone()
        if base is None:
            raise HTTPException(404, "Base not found")
        table = conn.execute(
            "SELECT * FROM at_tables WHERE base_id=? ORDER BY position LIMIT 1",
            (base_id,),
        ).fetchone()
        fields = conn.execute(
            "SELECT * FROM at_fields WHERE table_id=? ORDER BY position", (table["id"],)
        ).fetchall()
        views = conn.execute(
            "SELECT * FROM at_views WHERE table_id=? ORDER BY rowid", (table["id"],)
        ).fetchall()
        records = biz.list_records(
            conn, table["id"], query=query, status=status, sort=sort
        )
    page_size = 25
    total_records = len(records)
    total_pages = max(1, (total_records + page_size - 1) // page_size)
    page_index = min(max(1, page), total_pages)
    page_start = (page_index - 1) * page_size
    page_records = records[page_start : page_start + page_size]
    field_names = [r["name"] for r in fields if not r["hidden"]][:7]
    source_labels = {"Speaker": "Name", "Company": "Notes", "Track": "Assignee", "Status": "Status"}
    headers = "".join(
        f"<th>{html.escape(source_labels.get(n, n))}<button class='column-menu' data-action='field-menu' data-field='{html.escape(n)}' aria-label='Open {html.escape(source_labels.get(n, n))} field menu'>⌄</button></th>"
        for n in field_names
    )
    rows = ""
    for idx, record in enumerate(page_records, page_start + 1):
        cells = "".join(
            f"<td data-field='{html.escape(n)}'>{html.escape(str(record['values'].get(n, '')))}</td>"
            for n in field_names
        )
        rows += f"<tr data-record-id='{record['id']}'><td class='row-head'><input type='checkbox' class='row-select' aria-label='Select row {idx}'>{idx}</td>{cells}<td class='row-action'><a class='row-open' href='/base/{base_id}/record/{record['id']}' aria-label='Open record'>↗</a></td></tr>"
    if not rows:
        rows = f"<tr class='empty-row'><td colspan='{len(field_names) + 2}'><b>No records match this view</b><span>Clear filters or add a record.</span><button class='secondary' data-action='clear-filters'>Clear filters</button></td></tr>"
    view_items = "".join(
        f"<button class='view-item {'active' if v['view_type'] == 'grid' else ''}' data-view='{v['view_type']}' data-view-id='{v['id']}'><span>{ {'grid': '▦', 'gallery': '▤', 'kanban': '▥', 'calendar': '▣', 'form': '▧'}.get(v['view_type'], '▦') }</span>{html.escape(v['name'])}</button>"
        for v in views
    )
    preserved = {k: v for k, v in {"q": query, "status": status, "sort": sort}.items() if v}
    previous_query = urlencode({**preserved, "page": max(1, page_index - 1)})
    next_query = urlencode({**preserved, "page": min(total_pages, page_index + 1)})
    pagination = f'<nav class="grid-pagination" aria-label="Record pages"><a class="{"disabled" if page_index == 1 else ""}" href="/base/{base_id}?{previous_query}" aria-disabled="{"true" if page_index == 1 else "false"}">← Previous</a><a class="{"disabled" if page_index == total_pages else ""}" href="/base/{base_id}?{next_query}" aria-disabled="{"true" if page_index == total_pages else "false"}">Next →</a></nav>'
    data_stage = f"""<div class="table-tabs"><button class="active" data-action="table-menu">Table 1</button><button class="table-dropdown" data-action="table-menu" aria-label="Open table menu">⌄</button><button data-action="add-table">+ Add or import</button><span></span><button data-action="extensions">Tools ⌄</button></div>
    <div class="base-main"><aside class="view-sidebar"><button class="create-view" data-action="create-view">+ Create new…</button><div class="view-search">⌕ <input class="view-filter" placeholder="Find a view" aria-label="Find a view"></div>{view_items}</aside>
    <section class="grid-area"><div class="grid-toolbar"><button data-action="view-menu">☰</button><button data-action="view-menu">▦ Grid view ⌄</button><span></span><button data-action="hide-fields">◉ Hide fields</button><button data-action="filter">≡ Filter</button><button data-action="group">▤ Group</button><button data-action="sort">⇅ Sort</button><button data-action="color">◈ Color</button><button data-action="row-height">↕</button><button data-action="invite">↗ Share and sync</button><label class="record-search-control"><button type="button" data-action="toggle-record-search" aria-label="Search records">⌕</button><input id="record-search" value="{html.escape(query)}" placeholder="Search records" aria-label="Search records input"></label></div>
    <div class="bulkbar" hidden><b><span id="selected-count">0</span> selected</b><button data-action="bulk-status">Set confirmed</button><button data-action="bulk-archive">Archive</button><button data-action="bulk-delete">Delete</button></div>
    <div class="grid-wrap"><table class="data-grid"><thead><tr><th class="row-head"><input id="select-all" type="checkbox" aria-label="Select all"></th>{headers}<th></th></tr></thead><tbody>{rows}</tbody></table><button class="add-record" data-action="add-record">+</button></div>
    <footer class="grid-foot"><button data-action="add-record">+ Add record</button><span>{total_records} records · Page {page_index} of {total_pages}</span>{pagination}</footer></section></div>"""

    automations_stage = """<div class="mode-title">☰ <span>Automations</span></div><div class="automation-mode"><aside><div class="mode-icon">⑂</div><h2>Let Airtable do work for you</h2><p>Automate your most common tasks. <a href="/support">Learn More</a></p><button class="catalog-button" data-action="automation-catalog">▦&nbsp; Browse catalog</button><hr><h3>Suggested automations</h3><button data-action="automation-configure"><i>◌</i><span><b>Send an email</b><small>When Status is Done, send an email</small></span></button><button data-action="automation-configure"><i>◌</i><span><b>Send a Slack message</b><small>When Status is Done, send a Slack message</small></span></button><button data-action="automation-configure"><i>◇</i><span><b>Update a record</b><small>When Status is Done, set Status to Todo</small></span></button><button data-action="automation-configure"><i>◌</i><span><b>Send a weekly digest</b><small>At 9:00 pm Monday, email records where Status is Done</small></span></button></aside><section><div class="trigger-row"><b>TRIGGER</b><button data-action="automation-configure">Add trigger</button></div><h3>Suggested triggers for you:</h3><div class="trigger-list"><button data-action="automation-configure"><i>◇</i>When a record matches conditions</button><button data-action="automation-configure"><i>▧</i>When a form is submitted</button><button data-action="automation-configure"><i>▦</i>When a record is created</button><button data-action="automation-configure"><i>▤</i>When a record is updated</button><button data-action="automation-configure"><i>◴</i>At a scheduled time</button><button data-action="automation-configure"><i>▥</i>When a record enters a view</button></div><button class="see-all" data-action="automation-catalog">See all...</button></section></div>"""

    interfaces_stage = f"""<section class="builder-landing interfaces-landing"><h1>Visualize and act on your data with AI</h1><p>Build easy-to-use interfaces that make even complex workflows simple—for everyone on your team.</p><div><button data-action="interface-ai">Try building with AI</button><a href="/interface/{base_id}">Build it yourself</a></div><article class="interface-preview"><aside><b>Project<br>Management</b><span>Management</span><strong>Insights</strong><span>Team</span><span>Shipped vs estimated</span><span>Work</span></aside><section><small>Management › Insights</small><span class="preview-tools">Filter&nbsp;&nbsp;&nbsp;&nbsp; Sort&nbsp;&nbsp;&nbsp; ⌕&nbsp;&nbsp; ···</span><h2>Insights</h2><p>On this page, you can view insights across all of your projects. To view insights for a specific project, choose the project from the dropdown below.</p><div class="preview-metrics"><div><small>Percent Complete</small><b>19%</b></div><div><small>Payment Overdue</small><b>81%</b></div></div><div class="preview-charts"><div class="donut"><strong class="chart-title">Store Breakdown</strong><span class="donut-legend">Status<br>●&nbsp; To do<br>●&nbsp; In progress<br>●&nbsp; Done<br>●&nbsp; Blocked<br>●&nbsp; Not committed</span></div><div class="bars"><strong class="chart-title">Sales by Country – Retail vs. Online</strong><i></i><i></i><i></i><i></i><i></i><i></i></div></div><div class="preview-timeline"><b>Initiatives timeline</b><span>Status&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2024</span></div></section></article></section>"""

    forms_stage = f"""<section class="builder-landing forms-landing"><div class="form-copy"><h1>Gather and organize<br>your data with AI</h1><p>Quickly collect data from a broad audience, even outside of Airtable.</p><div><button data-action="form-ai">Try building with AI</button><a href="/forms/{base_id}">Build it yourself</a><a href="/templates">View templates</a></div></div><div class="form-preview"><div class="form-art"></div><article><span class="mini-airtable">◇</span><h3>New Feedback</h3><label>Name<i></i></label><label>Feedback<i></i></label><label>Notes<i></i></label><label>Type<i></i></label><button data-action="preview-form-submit">Submit Feedback</button></article></div></section>"""

    stage = {
        "data": data_stage,
        "automations": automations_stage,
        "interfaces": interfaces_stage,
        "forms": forms_stage,
    }.get(mode, data_stage)
    labels = {"data": "Data", "automations": "Automations", "interfaces": "Interfaces", "forms": "Forms"}
    nav = "".join(
        f'<button class="{"active" if mode == key else ""}" data-action="base-mode" data-mode="{key}">{label}</button>'
        for key, label in labels.items()
    )
    omni_footer_title = (
        "Automations catalog" if mode == "automations" else "Connect your favorite AI tool"
    )
    omni_footer_copy = (
        "Easily set up automated workflows with Omni"
        if mode == "automations"
        else "Bring Airtable to where you work"
    )
    omni = f"""<aside class="omni-shell"><nav class="omni-rail"><a href="/app" aria-label="Airtable home">◆</a><button data-action="omni-home" aria-label="Omni">◌</button><button data-action="omni-start" aria-label="Start a chat">✎</button><button data-action="history" aria-label="History">↶</button><button data-action="omni-settings" aria-label="Settings">⌯</button><span></span><a href="/support" aria-label="Help">?</a><button data-action="notifications" aria-label="Notifications">◉</button><button class="omni-account" data-action="profile" aria-label="Account">A</button></nav><section class="omni-chat"><header><b>New chat</b><button data-action="omni-expand" aria-label="Expand chat">↗</button><button data-action="omni-collapse" aria-label="Collapse chat">«</button></header><main><div class="omni-spinner"><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i></div><h2>How can I help?</h2><div class="omni-prompt"><span>Ask or build anything…</span><footer><button data-action="omni-tools">⌘ Tools</button><button data-action="omni-attach" aria-label="Attach">◎</button><button data-action="omni-send" aria-label="Send">↑</button></footer></div></main><footer><div><b>{omni_footer_title}</b><small>{omni_footer_copy}</small></div><button data-action="extensions">Connect</button></footer></section></aside>"""
    onboarding = (
        """<section class="blank-base-onboarding" role="dialog" aria-label="Welcome to Airtable"><div class="scene" aria-hidden="true"></div><div class="copy"><h3>Welcome, Airtable</h3><p>We’d love to show you around so you can see what Airtable is all about. It’ll only take a couple minutes.</p><div class="actions"><button data-action="dismiss-onboarding">Skip</button><button data-action="onboarding-next">Let's go!</button></div></div></section>"""
        if base_id == "base-untitled" and mode == "data"
        else ""
    )
    # Preserve the source-observed fixture label used by the private visual
    # contracts, while making every user-created base visibly addressable by
    # its persisted name.
    displayed_base_name = (
        "Untitled Base"
        if base_id in {"base-conference", "base-untitled"}
        else str(base["name"])
    )
    base_name = html.escape(displayed_base_name)
    return f"""<div class="base-workspace">{omni}<div class="base-app mode-{mode}" data-base-id="{base_id}" data-table-id="{table["id"]}"><div class="base-head"><a class="logo-button" href="/app">◆</a><button class="base-name" data-action="rename-base">{base_name} ⌄</button><nav>{nav}</nav><div class="trial-chip">Trial: 14 days left</div><div class="base-actions"><button class="secondary compact" data-action="launch">Launch</button><button class="icon-btn" data-action="copy-link">↗</button><button class="secondary compact share-main" data-action="invite">Share</button></div></div>{stage}</div>{onboarding}</div>"""


@app.get("/base/{base_id}", response_class=HTMLResponse)
def base_page(
    base_id: str, request: Request, q: str = "", status: str = "", sort: str = "", page: int = 1
):
    token, account = session(request, create=False)
    if not account or not account.get("account_id"):
        return RedirectResponse(f"/login?next=/base/{base_id}", 303)
    return shell(
        "Conference Tracker",
        base_body(base_id, account, q, status, sort, page=page),
        app_mode=True,
        account=account,
    )


@app.get("/base/{base_id}/{mode}", response_class=HTMLResponse)
def base_mode_page(
    base_id: str,
    mode: str,
    request: Request,
    q: str = "",
    status: str = "",
    sort: str = "",
    page: int = 1,
):
    if mode not in {"automations", "interfaces", "forms"}:
        raise HTTPException(404, "Base mode unavailable")
    _, account = session(request, create=False)
    if not account or not account.get("account_id"):
        return RedirectResponse(f"/login?next=/base/{base_id}/{mode}", 303)
    return shell(
        f"{mode.title()} · Conference Tracker",
        base_body(base_id, account, q, status, sort, mode, page),
        app_mode=True,
        account=account,
    )


@app.get("/base/{base_id}/record/{record_id}", response_class=HTMLResponse)
def record_detail_page(base_id: str, record_id: str, request: Request):
    _, account = session(request, create=False)
    if not account or not account.get("account_id"):
        return RedirectResponse(f"/login?next=/base/{base_id}/record/{record_id}", 303)
    with connection() as conn:
        require_resource_capability(conn, account, "base", base_id, "read")
        row = conn.execute(
            "SELECT r.*,b.name AS base_name FROM at_records r "
            "JOIN at_tables t ON t.id=r.table_id JOIN at_bases b ON b.id=t.base_id "
            "WHERE r.id=? AND b.id=? AND r.trashed=0",
            (record_id, base_id),
        ).fetchone()
    if row is None:
        raise HTTPException(404, "Record not found")
    values = json.loads(row["values_json"] or "{}")
    fields = "".join(
        f"<div class='field-row'><b>{html.escape(str(key))}</b><span>{html.escape(str(value or ''))}</span></div>"
        for key, value in values.items()
    )
    title = str(values.get("Speaker") or values.get("Name") or "Untitled")
    return shell(
        f"{title} · {row['base_name']}",
        f"<section class='home-content secondary-page record-detail-page'><a href='/base/{base_id}'>← Back to base</a><p class='eyebrow'>RECORD DETAIL</p><h1>{html.escape(title)}</h1><div class='settings-card'>{fields}<div class='field-row'><b>Status</b><span>{html.escape(row['status'])}</span></div><div class='field-row'><b>Priority</b><span>{html.escape(row['priority'])}</span></div></div></section>",
        app_mode=True,
        account=account,
    )


@app.get("/share/{share_token}", response_class=HTMLResponse)
def public_share(share_token: str):
    with connection() as conn:
        base = conn.execute(
            "SELECT * FROM at_bases WHERE share_token=? AND trashed=0", (share_token,)
        ).fetchone()
        if base is None:
            raise HTTPException(404, "This shared view is unavailable")
        table = conn.execute(
            "SELECT * FROM at_tables WHERE base_id=? LIMIT 1", (base["id"],)
        ).fetchone()
        records = biz.list_records(conn, table["id"])
    cards = "".join(
        f"<article class='shared-card'><h3>{html.escape(str(r['values'].get('Speaker') or r['values'].get('Name')))}</h3><p>{html.escape(str(r['values'].get('Company', '')))}</p><span class='pill green'>{html.escape(r['status'])}</span></article>"
        for r in records
    )
    return shell(
        f"Shared · {base['name']}",
        f"<section class='content-hero blue'><p class='eyebrow'>SHARED VIEW · READ ONLY</p><h1>{html.escape(base['name'])}</h1><p>This public link is served entirely by the local clone.</p></section><section class='shared-grid'>{cards}</section>",
    )


@app.get("/forms/{base_id}", response_class=HTMLResponse)
def form_view(base_id: str):
    with connection() as conn:
        base = form_capability(conn, base_id)
    if base is None:
        raise HTTPException(404, "Form unavailable")
    return shell(
        "Speaker nomination",
        f"""<section class="form-page"><div class="form-card"><div class="form-cover"></div><h1>Speaker nomination</h1><p>Suggest a speaker for {html.escape(base["name"])}. Required fields are marked.</p><form id="public-form" data-base-id="{base_id}"><label>Speaker name *<input name="Speaker" required></label><label>Email *<input name="Email" type="email" required></label><label>Company<input name="Company"></label><label>Track<select name="Track"><option>AI</option><option>Design</option><option>Leadership</option></select></label><label>Notes<textarea name="Notes" rows="4"></textarea></label><button class="primary">Submit</button></form></div></section>""",
    )


@app.get("/interface/{base_id}", response_class=HTMLResponse)
def interface_view(base_id: str, request: Request):
    _, account = session(request, create=False)
    if not account:
        return RedirectResponse("/login", 303)
    with connection() as conn:
        require_resource_capability(conn, account, "base", base_id, "read")
        base = conn.execute(
            "SELECT name FROM at_bases WHERE id=?", (base_id,)
        ).fetchone()
        table = conn.execute(
            "SELECT id FROM at_tables WHERE base_id=? LIMIT 1", (base_id,)
        ).fetchone()
        records = biz.list_records(conn, table["id"]) if table else []
    confirmed = sum(1 for r in records if r["status"] == "Confirmed")
    bars = "".join(
        f"<div><span>{html.escape(str(r['values'].get('Speaker') or r['values'].get('Name')))}</span><i style='width:{max(10, float(r['values'].get('Score', 5) or 5) * 9)}%'></i></div>"
        for r in records[:8]
    )
    return shell(
        "Conference dashboard",
        f"""<div class="interface"><aside><a class="brand" href="/base/{base_id}"><span class="logo">A</span>{html.escape(base["name"] if base else "Interface")}</a><nav><button class="active" data-action="interface-tab" data-tab="overview">Overview</button><button data-action="interface-tab" data-tab="speakers">Speakers</button><button data-action="interface-tab" data-tab="schedule">Schedule</button></nav></aside><section><header><h1>Conference overview</h1><button class="secondary" data-action="interface-filter">Filter</button></header><div class="metric-grid"><article><span>Total speakers</span><b>{len(records)}</b><small>current records</small></article><article><span>Confirmed</span><b>{confirmed}</b><small>ready to schedule</small></article><article><span>Confirmation rate</span><b>{round(100 * confirmed / max(1, len(records)))}%</b><small>local calculation</small></article></div><article class="chart"><h2>Speaker score</h2>{bars}</article></section></div>""",
        app_mode=True,
        account=account,
    )


@app.post("/api/auth/login")
async def api_login(request: Request):
    data = await json_object(request)
    token, _ = session(request)
    try:
        result = services()[1].sign_in(
            token,
            email=str(data.get("email", "")),
            password=str(data.get("password", "")),
        )
    except Exception as exc:
        raise payload_error(exc)
    response = JSONResponse(
        {"ok": True, "account": result["account"], "redirect": "/"}
    )
    set_session(response, result["session_token"], request)
    return response


@app.post("/api/auth/signup")
async def api_signup(request: Request):
    data = await json_object(request)
    token, _ = session(request)
    auth = services()[1]
    try:
        auth.start_registration(
            token,
            email=str(data.get("email", "")),
            display_name=str(data.get("name", "")),
            password=str(data.get("password", "")),
        )
        mail = auth.local_mail_for_session(token, purpose="registration")
    except Exception as exc:
        raise payload_error(exc)
    response = JSONResponse(
        {
            "ok": True,
            "verification_required": True,
            "local_code": mail.get("verification_code") if mail else None,
            "message": "Verification message created in the local inbox.",
        }
    )
    set_session(response, token, request)
    return response


@app.post("/api/auth/signup/verify")
async def api_signup_verify(request: Request):
    data = await json_object(request)
    token, _ = session(request)
    auth = services()[1]
    try:
        auth.verify_registration_code(token, str(data.get("code", "")))
        result = auth.complete_registration(token)
    except Exception as exc:
        raise payload_error(exc)
    response = JSONResponse(
        {"ok": True, "account": result["account"], "redirect": "/"}
    )
    set_session(response, result["session_token"], request)
    return response


@app.post("/api/auth/logout")
def api_logout(request: Request):
    token, _ = session(request, create=False)
    services()[1].sign_out(token)
    response = JSONResponse({"ok": True, "redirect": "/login"})
    if token:
        response.delete_cookie(cookie_name(request), path="/")
    return response


@app.post("/api/auth/reset")
async def api_reset(request: Request):
    data = await json_object(request)
    token, _ = session(request)
    auth = services()[1]
    try:
        result = auth.start_password_reset(token, email=str(data.get("email", "")))
        mail = auth.local_mail_for_session(token, purpose="password-reset")
    except Exception as exc:
        raise payload_error(exc)
    response = JSONResponse(
        {
            **result,
            "ok": True,
            "local_code": mail.get("verification_code") if mail else None,
        }
    )
    set_session(response, token, request)
    return response


@app.post("/api/auth/reset/complete")
async def api_reset_complete(request: Request):
    data = await json_object(request)
    token, _ = session(request)
    auth = services()[1]
    try:
        auth.verify_password_reset_code(token, str(data.get("code", "")))
        new_token = auth.complete_password_reset(
            token, new_password=str(data.get("password", ""))
        )
    except Exception as exc:
        raise payload_error(exc)
    response = JSONResponse({"ok": True, "message": "Password updated"})
    set_session(response, new_token, request)
    return response


@app.post("/api/workspaces")
async def api_create_workspace(request: Request):
    _, account = require_account(request)
    data = await request.json()
    try:
        with connection() as conn:
            result = biz.create_workspace(
                conn, owner_of(account), str(data.get("name", ""))
            )
    except Exception as exc:
        raise payload_error(exc)
    return {"ok": True, "workspace": result}


@app.post("/api/bases")
async def api_create_base(request: Request):
    _, account = require_account(request)
    data = await request.json()
    try:
        with connection() as conn:
            workspace_id = str(data.get("workspace_id") or "")
            require_workspace_capability(conn, account, workspace_id, "schema")
            result = biz.create_base(
                conn,
                owner_of(account),
                workspace_id,
                str(data.get("name", "")),
                str(data.get("template")) if data.get("template") else None,
            )
    except Exception as exc:
        raise payload_error(exc)
    return {"ok": True, "base": result, "redirect": f"/base/{result['id']}"}


@app.get("/api/bases/{base_id}")
def api_base(base_id: str, request: Request):
    _, account = require_account(request)
    with connection() as conn:
        require_resource_capability(conn, account, "base", base_id, "read")
        base = conn.execute(
            "SELECT * FROM at_bases WHERE id=? AND trashed=0", (base_id,)
        ).fetchone()
        if base is None:
            raise HTTPException(404, "Base not found")
        tables = [
            dict(r)
            for r in conn.execute(
                "SELECT * FROM at_tables WHERE base_id=? ORDER BY position", (base_id,)
            )
        ]
        for table in tables:
            table["fields"] = [
                dict(r)
                for r in conn.execute(
                    "SELECT * FROM at_fields WHERE table_id=? ORDER BY position",
                    (table["id"],),
                )
            ]
            table["views"] = [
                dict(r)
                for r in conn.execute(
                    "SELECT * FROM at_views WHERE table_id=?", (table["id"],)
                )
            ]
            table["records"] = biz.list_records(conn, table["id"])
    return {"ok": True, "base": dict(base), "tables": tables}


@app.post("/api/tables/{table_id}/records")
async def api_create_record(table_id: str, request: Request):
    _, account = require_account(request)
    data = await request.json()
    try:
        with connection() as conn:
            require_resource_capability(conn, account, "table", table_id, "data")
            result = biz.create_record(
                conn,
                owner_of(account),
                table_id,
                dict(data.get("values") or {}),
                status=str(data.get("status") or "Planned"),
                priority=str(data.get("priority") or "Medium"),
                assignee=data.get("assignee"),
                due_date=data.get("due_date"),
            )
    except Exception as exc:
        raise payload_error(exc)
    return {"ok": True, "record": result}


@app.patch("/api/records/{record_id}")
async def api_update_record(record_id: str, request: Request):
    _, account = require_account(request)
    data = await request.json()
    try:
        with connection() as conn:
            require_resource_capability(conn, account, "record", record_id, "data")
            result = biz.update_record(
                conn,
                owner_of(account),
                record_id,
                data,
                data.get("expected_updated_at"),
            )
    except Exception as exc:
        raise payload_error(exc)
    return {"ok": True, "record": result}


@app.delete("/api/records/{record_id}")
def api_delete_record(record_id: str, request: Request):
    _, account = require_account(request)
    with connection() as conn:
        require_resource_capability(conn, account, "record", record_id, "data")
        row = conn.execute(
            "SELECT table_id,values_json FROM at_records WHERE id=? AND trashed=0",
            (record_id,),
        ).fetchone()
        if row is None:
            raise HTTPException(404, "Record not found")
        changed = conn.execute(
            "UPDATE at_records SET trashed=1,updated_at=? WHERE id=? AND trashed=0",
            (biz.now(), record_id),
        )
        if changed.rowcount == 0:
            raise HTTPException(404, "Record not found")
        base_id = conn.execute(
            "SELECT base_id FROM at_tables WHERE id=?", (row["table_id"],)
        ).fetchone()[0]
        biz.log(
            conn,
            owner_of(account),
            "moved record to trash",
            base_id=base_id,
            entity_type="record",
            entity_id=record_id,
            snapshot=json.loads(row["values_json"]),
        )
    return {"ok": True, "state": "trashed"}


@app.post("/api/records/bulk")
async def api_bulk_records(request: Request):
    _, account = require_account(request)
    data = await request.json()
    ids = [str(x) for x in data.get("record_ids", [])]
    if not ids or len(ids) > 100:
        raise HTTPException(422, "Select 1 to 100 records")
    action = str(data.get("action", ""))
    placeholders = ",".join("?" for _ in ids)
    with connection() as conn:
        rows = conn.execute(
            f"SELECT id FROM at_records WHERE id IN ({placeholders})", ids
        ).fetchall()
        if len(rows) != len(set(ids)):
            raise HTTPException(404, "Record not found")
        workspace_ids = {
            workspace_id_for(conn, "record", record_id) for record_id in ids
        }
        if None in workspace_ids or len(workspace_ids) != 1:
            raise HTTPException(404, "Records not found")
        require_workspace_capability(
            conn, account, next(iter(workspace_ids)), "data"
        )
        if action == "confirm":
            conn.execute(
                f"UPDATE at_records SET status='Confirmed',updated_at=? WHERE id IN ({placeholders})",
                (biz.now(), *ids),
            )
        elif action == "archive":
            conn.execute(
                f"UPDATE at_records SET archived=1,updated_at=? WHERE id IN ({placeholders})",
                (biz.now(), *ids),
            )
        elif action == "trash":
            conn.execute(
                f"UPDATE at_records SET trashed=1,updated_at=? WHERE id IN ({placeholders})",
                (biz.now(), *ids),
            )
        else:
            raise HTTPException(422, "Unsupported bulk action")
        changed = conn.execute(
            f"SELECT COUNT(*) FROM at_records WHERE id IN ({placeholders})", ids
        ).fetchone()[0]
        biz.log(
            conn,
            owner_of(account),
            f"bulk {action}",
            entity_type="records",
            snapshot={"count": changed},
        )
    return {"ok": True, "changed": changed, "action": action}


@app.post("/api/tables/{table_id}/fields")
async def api_create_field(table_id: str, request: Request):
    _, account = require_account(request)
    data = await request.json()
    name = " ".join(str(data.get("name", "")).split())
    typ = str(data.get("type", "singleLineText"))
    allowed = {
        "singleLineText",
        "longText",
        "number",
        "singleSelect",
        "multipleSelect",
        "date",
        "checkbox",
        "email",
        "url",
        "attachment",
        "collaborator",
        "linkedRecord",
        "lookup",
        "rollup",
        "formula",
    }
    if not name or typ not in allowed:
        raise HTTPException(422, "Choose a valid field name and type")
    with connection() as conn:
        require_resource_capability(conn, account, "table", table_id, "schema")
        pos = conn.execute(
            "SELECT COALESCE(MAX(position),-1)+1 FROM at_fields WHERE table_id=?",
            (table_id,),
        ).fetchone()[0]
        fid = biz.token("fld")
        conn.execute(
            "INSERT INTO at_fields VALUES (?,?,?,?,?,?,0)",
            (fid, table_id, name, typ, json.dumps(data.get("options") or {}), pos),
        )
        base = conn.execute(
            "SELECT base_id FROM at_tables WHERE id=?", (table_id,)
        ).fetchone()
        if not base:
            raise HTTPException(404, "Table not found")
        biz.log(
            conn,
            owner_of(account),
            "created field",
            base_id=base[0],
            entity_type="field",
            entity_id=fid,
            snapshot={"name": name, "type": typ},
        )
    return {"ok": True, "field": {"id": fid, "name": name, "type": typ}}


@app.post("/api/tables/{table_id}/views")
async def api_create_view(table_id: str, request: Request):
    _, account = require_account(request)
    data = await request.json()
    typ = str(data.get("type", "grid"))
    name = str(data.get("name", f"{typ.title()} view"))
    if typ not in {"grid", "gallery", "kanban", "calendar", "form"}:
        raise HTTPException(422, "Unsupported view type")
    with connection() as conn:
        require_resource_capability(conn, account, "table", table_id, "schema")
        vid = biz.token("view")
        conn.execute(
            "INSERT INTO at_views VALUES (?,?,?,?,?,?)",
            (
                vid,
                table_id,
                name,
                typ,
                json.dumps(data.get("config") or {}),
                int(bool(data.get("favorite"))),
            ),
        )
    return {"ok": True, "view": {"id": vid, "name": name, "type": typ}}


@app.post("/api/records/{record_id}/comments")
async def api_comment(record_id: str, request: Request):
    _, account = require_account(request)
    data = await request.json()
    body = " ".join(str(data.get("body", "")).split())
    if not 1 <= len(body) <= 2000:
        raise HTTPException(422, "Comment must contain 1 to 2000 characters")
    with connection() as conn:
        require_resource_capability(conn, account, "record", record_id, "comment")
        if (
            conn.execute("SELECT 1 FROM at_records WHERE id=?", (record_id,)).fetchone()
            is None
        ):
            raise HTTPException(404, "Record not found")
        cid = biz.token("comment")
        conn.execute(
            "INSERT INTO at_comments VALUES (?,?,?,?,?)",
            (cid, record_id, owner_of(account), body, biz.now()),
        )
        if "@" in body:
            conn.execute(
                "INSERT INTO at_notifications VALUES (?,?,?,?,?)",
                (
                    biz.token("note"),
                    "seed:member",
                    f"Mention in a comment: {body[:120]}",
                    None,
                    biz.now(),
                ),
            )
    return {
        "ok": True,
        "comment": {"id": cid, "body": body},
        "mention_notified": "@" in body,
    }


@app.post("/api/workspaces/{workspace_id}/invite")
async def api_invite(workspace_id: str, request: Request):
    _, account = require_account(request)
    data = await request.json()
    email_value = str(data.get("email", "")).strip().casefold()
    role = str(data.get("role", "editor"))
    if "@" not in email_value or role not in {
        "owner",
        "creator",
        "editor",
        "commenter",
        "read_only",
    }:
        raise HTTPException(422, "Enter a valid email and role")
    with connection() as conn:
        actor_role = require_workspace_capability(
            conn, account, workspace_id, "manage"
        )
        if role == "owner" and actor_role != "owner":
            raise HTTPException(403, "Only the workspace owner can grant owner access")
        iid = biz.token("invite")
        try:
            conn.execute(
                "INSERT INTO at_collaborators VALUES (?,?,?,?,?,?)",
                (iid, workspace_id, email_value, role, "invited-local", biz.now()),
            )
        except sqlite3.IntegrityError:
            conn.execute(
                "UPDATE at_collaborators SET role=?,status='invited-local' WHERE workspace_id=? AND email=?",
                (role, workspace_id, email_value),
            )
        biz.log(
            conn,
            owner_of(account),
            "invited collaborator (local delivery)",
            entity_type="collaborator",
            entity_id=iid,
            snapshot={"role": role},
        )
    return {
        "ok": True,
        "status": "invited-local",
        "delivery": "local-outbox",
        "role": role,
    }


@app.post("/api/bases/{base_id}/share")
def api_share(base_id: str, request: Request):
    _, account = require_account(request)
    with connection() as conn:
        require_resource_capability(conn, account, "base", base_id, "manage")
        base = conn.execute(
            "SELECT * FROM at_bases WHERE id=?", (base_id,)
        ).fetchone()
        if base is None:
            raise HTTPException(403, "Base unavailable")
        share_token = base["share_token"] or biz.token("share")
        conn.execute(
            "UPDATE at_bases SET share_token=?,updated_at=? WHERE id=?",
            (share_token, biz.now(), base_id),
        )
    return {"ok": True, "share_url": f"/share/{share_token}", "read_only": True}


@app.post("/api/bases/{base_id}/automations")
async def api_automation(base_id: str, request: Request):
    _, account = require_account(request)
    data = await request.json()
    action = str(data.get("action", "create"))
    with connection() as conn:
        require_resource_capability(conn, account, "base", base_id, "manage")
        if action == "run":
            aid = str(data.get("automation_id") or "auto-confirm")
            row = conn.execute(
                "SELECT * FROM at_automations WHERE id=? AND base_id=?", (aid, base_id)
            ).fetchone()
            if row is None:
                raise HTTPException(404, "Automation not found")
            conn.execute(
                "UPDATE at_automations SET run_count=run_count+1,last_status='Succeeded locally' WHERE id=?",
                (aid,),
            )
            conn.execute(
                "INSERT INTO at_notifications VALUES (?,?,?,?,?)",
                (
                    biz.token("note"),
                    owner_of(account),
                    f"Automation '{row['name']}' completed locally",
                    None,
                    biz.now(),
                ),
            )
            result = {"id": aid, "status": "Succeeded locally"}
        else:
            name = str(data.get("name", "Untitled automation"))
            aid = biz.token("auto")
            conn.execute(
                "INSERT INTO at_automations VALUES (?,?,?,?,?,?,?,?)",
                (
                    aid,
                    base_id,
                    name,
                    str(data.get("trigger", "record_created")),
                    str(data.get("then", "create_notification")),
                    int(bool(data.get("enabled", True))),
                    0,
                    "Never run",
                ),
            )
            result = {
                "id": aid,
                "status": "enabled" if data.get("enabled", True) else "disabled",
            }
    return {"ok": True, "automation": result, "sandbox": True}


@app.post("/api/bases/{base_id}/integrations")
async def api_integration(base_id: str, request: Request):
    _, account = require_account(request)
    data = await request.json()
    provider = str(data.get("provider", "Local webhook"))
    with connection() as conn:
        require_resource_capability(conn, account, "base", base_id, "manage")
        iid = biz.token("int")
        conn.execute(
            "INSERT INTO at_integrations VALUES (?,?,?,?,?)",
            (iid, base_id, provider, 1, json.dumps({"mode": "offline-simulation"})),
        )
    return {
        "ok": True,
        "integration": {"id": iid, "provider": provider, "mode": "offline-simulation"},
    }


@app.post("/api/tables/{table_id}/import")
async def api_import(table_id: str, request: Request):
    _, account = require_account(request)
    text = (await request.body()).decode("utf-8", "replace")
    try:
        with connection() as conn:
            require_resource_capability(conn, account, "table", table_id, "data")
            result = biz.csv_import(conn, owner_of(account), table_id, text)
    except Exception as exc:
        raise payload_error(exc)
    return {"ok": True, **result}


@app.get("/api/tables/{table_id}/export")
def api_export(table_id: str, request: Request):
    _, account = require_account(request)
    with connection() as conn:
        require_resource_capability(conn, account, "table", table_id, "read")
        text = biz.csv_export(conn, table_id)
    return PlainTextResponse(
        text,
        media_type="text/csv",
        headers={"Content-Disposition": "attachment; filename=airtable-export.csv"},
    )


@app.post("/api/records/{record_id}/attachments")
async def api_attachment(
    record_id: str, request: Request, file: UploadFile = File(...)
):
    _, account = require_account(request)
    data = await file.read(5_000_001)
    if len(data) > 5_000_000:
        raise HTTPException(413, "Attachment exceeds the 5 MB offline limit")
    safe = (
        "".join(
            c for c in (file.filename or "attachment.bin") if c.isalnum() or c in ".-_ "
        )[:100]
        or "attachment.bin"
    )
    aid = biz.token("attachment")
    target = VOLUME_ROOT / "attachments" / f"{aid}-{safe}"
    target.parent.mkdir(parents=True, exist_ok=True)
    with connection() as conn:
        require_resource_capability(conn, account, "record", record_id, "data")
        target.write_bytes(data)
        conn.execute(
            "INSERT INTO at_attachments VALUES (?,?,?,?,?,?,?)",
            (
                aid,
                record_id,
                safe,
                file.content_type or "application/octet-stream",
                len(data),
                str(target),
                biz.now(),
            ),
        )
        biz.log(
            conn,
            owner_of(account),
            "attached file",
            entity_type="attachment",
            entity_id=aid,
            snapshot={"filename": safe, "size": len(data)},
        )
    return {
        "ok": True,
        "attachment": {
            "id": aid,
            "filename": safe,
            "size": len(data),
            "download": f"/api/attachments/{aid}",
        },
    }


@app.get("/api/attachments/{attachment_id}")
def api_attachment_download(attachment_id: str, request: Request):
    _, account = require_account(request)
    with connection() as conn:
        require_resource_capability(
            conn, account, "attachment", attachment_id, "read"
        )
        row = conn.execute(
            "SELECT * FROM at_attachments WHERE id=?", (attachment_id,)
        ).fetchone()
    if row is None or not Path(row["local_path"]).is_file():
        raise HTTPException(404, "Attachment unavailable")
    return FileResponse(
        row["local_path"], media_type=row["content_type"], filename=row["filename"]
    )


@app.post("/api/forms/{base_id}/submit")
async def api_form_submit(base_id: str, request: Request):
    data = await json_object(request)
    name = str(data.get("Speaker", "")).strip()
    email_value = str(data.get("Email", "")).strip()
    if not name or "@" not in email_value:
        raise HTTPException(422, "Speaker name and a valid email are required")
    with connection() as conn:
        if form_capability(conn, base_id) is None:
            raise HTTPException(404, "Form unavailable")
        table = conn.execute(
            "SELECT id FROM at_tables WHERE base_id=? LIMIT 1", (base_id,)
        ).fetchone()
        if table is None:
            raise HTTPException(404, "Form unavailable")
        sid = biz.token("submission")
        conn.execute(
            "INSERT INTO at_form_submissions VALUES (?,?,?,?)",
            (sid, base_id, json.dumps(data), biz.now()),
        )
        record = biz.create_record(
            conn, "public-form", table[0], data, status="Invited"
        )
    return {
        "ok": True,
        "submission_id": sid,
        "record_id": record["id"],
        "message": "Thanks — your response was submitted.",
    }


@app.get("/api/history/{base_id}")
def api_history(base_id: str, request: Request):
    _, account = require_account(request)
    with connection() as conn:
        require_resource_capability(conn, account, "base", base_id, "read")
        rows = [
            dict(r)
            for r in conn.execute(
                "SELECT * FROM at_history WHERE base_id=? ORDER BY id DESC LIMIT 50",
                (base_id,),
            )
        ]
    return {"ok": True, "history": rows}


@app.post("/api/history/{history_id}/undo")
def api_undo(history_id: int, request: Request):
    _, account = require_account(request)
    with connection() as conn:
        require_resource_capability(conn, account, "history", history_id, "data")
        event = conn.execute(
            "SELECT * FROM at_history WHERE id=?", (history_id,)
        ).fetchone()
        if event is None:
            raise HTTPException(404, "History entry not found")
        snapshot = json.loads(event["snapshot_json"])
        if event["entity_type"] == "record" and event["action"] in {
            "updated record",
            "moved record to trash",
        }:
            if event["action"] == "moved record to trash":
                conn.execute(
                    "UPDATE at_records SET trashed=0,updated_at=? WHERE id=?",
                    (biz.now(), event["entity_id"]),
                )
            else:
                conn.execute(
                    "UPDATE at_records SET values_json=?,status=?,priority=?,assignee=?,due_date=?,updated_at=? WHERE id=?",
                    (
                        snapshot["values_json"],
                        snapshot["status"],
                        snapshot["priority"],
                        snapshot["assignee"],
                        snapshot["due_date"],
                        biz.now(),
                        event["entity_id"],
                    ),
                )
        else:
            raise HTTPException(422, "This history entry cannot be undone")
        biz.log(
            conn,
            owner_of(account),
            "undo",
            base_id=event["base_id"],
            entity_type=event["entity_type"],
            entity_id=event["entity_id"],
            snapshot={"source_history_id": history_id},
        )
    return {"ok": True, "message": "Change undone"}


@app.post("/api/bases/{base_id}/lifecycle")
async def api_base_lifecycle(base_id: str, request: Request):
    _, account = require_account(request)
    data = await request.json()
    action = str(data.get("action", ""))
    states = {
        "archive": (1, 0),
        "restore": (0, 0),
        "trash": (0, 1),
        "restore-trash": (0, 0),
    }
    if action == "permanent-delete":
        with connection() as conn:
            require_resource_capability(conn, account, "base", base_id, "manage")
            base = conn.execute(
                "SELECT * FROM at_bases WHERE id=? AND trashed=1", (base_id,)
            ).fetchone()
            if base is None:
                raise HTTPException(
                    409, "Move the base to trash before permanent deletion"
                )
            conn.execute("DELETE FROM at_bases WHERE id=?", (base_id,))
        return {"ok": True, "state": "permanently-deleted"}
    if action not in states:
        raise HTTPException(422, "Unsupported lifecycle action")
    archived, trashed = states[action]
    with connection() as conn:
        require_resource_capability(conn, account, "base", base_id, "manage")
        changed = conn.execute(
            "UPDATE at_bases SET archived=?,trashed=?,updated_at=? WHERE id=?",
            (archived, trashed, biz.now(), base_id),
        ).rowcount
        if not changed:
            raise HTTPException(404, "Base not found")
        biz.log(
            conn,
            owner_of(account),
            action,
            base_id=base_id,
            entity_type="base",
            entity_id=base_id,
        )
    return {"ok": True, "state": action}


@app.get("/api/notifications")
def api_notifications(request: Request):
    _, account = require_account(request)
    with connection() as conn:
        rows = [
            dict(r)
            for r in conn.execute(
                "SELECT * FROM at_notifications WHERE owner=? ORDER BY created_at DESC",
                (owner_of(account),),
            )
        ]
    return {"ok": True, "notifications": rows}


@app.post("/api/preferences")
async def api_preferences(request: Request):
    _, account = require_account(request)
    data = await request.json()
    owner = owner_of(account)
    with connection() as conn:
        conn.execute(
            "INSERT INTO at_preferences VALUES (?,?,?) ON CONFLICT(owner) DO UPDATE SET values_json=excluded.values_json,updated_at=excluded.updated_at",
            (owner, json.dumps(data), biz.now()),
        )
    return {"ok": True, "preferences": data}


@app.post("/api/security/revoke-sessions")
def api_revoke_sessions(request: Request):
    token, account = require_account(request)
    auth = services()[1]
    with auth.connect() as conn:
        digest = auth._session_row(conn, token)["session_digest"]
        conn.execute(
            "UPDATE local_auth_sessions SET revoked_at=? WHERE account_id=? AND session_digest<>? AND revoked_at IS NULL",
            (biz.now(), account["account_id"], digest),
        )
        changed = conn.total_changes
    return {"ok": True, "revoked": changed, "current_session_preserved": True}


@app.delete("/api/account")
def api_delete_account(request: Request):
    token, account = require_account(request)
    owner = owner_of(account)
    auth = services()[1]
    with auth.connect() as conn:
        owned = conn.execute(
            "SELECT COUNT(*) FROM at_workspaces WHERE owner=? AND archived=0", (owner,)
        ).fetchone()[0]
        if owned:
            raise HTTPException(
                409, "Archive or transfer owned workspaces before deleting the account"
            )
        conn.execute(
            "DELETE FROM local_auth_accounts WHERE account_id=?",
            (account["account_id"],),
        )
    return {"ok": True, "state": "deleted"}


@app.get("/api/formula")
def api_formula(
    request: Request, expression: str, speaker: str = "Ada", company: str = "Northstar"
):
    require_account(request)
    try:
        value = biz.evaluate_formula(
            expression, {"Speaker": speaker, "Company": company, "Score": 9}
        )
    except Exception as exc:
        raise payload_error(exc)
    return {"ok": True, "value": value, "sandbox": True}


@app.exception_handler(HTTPException)
def http_error(request: Request, exc: HTTPException):
    if request.url.path.startswith("/api/"):
        return JSONResponse(
            {
                "ok": False,
                "error": exc.detail,
                "retryable": exc.status_code in {409, 429, 500, 503},
            },
            status_code=exc.status_code,
        )
    response = shell(
        "Something went wrong",
        f"<section class='error-page'><h1>{exc.status_code}</h1><h2>{html.escape(str(exc.detail))}</h2><p>Your prior local state has not been changed.</p><a class='primary' href='/app'>Return home</a><button class='secondary' onclick='location.reload()'>Retry</button></section>",
        app_mode=True,
    )
    response.status_code = exc.status_code
    return response