|
root / src / core
core Plain Text 6652 lines 212.9 KB
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: config.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Configuration file loading and access

******************************************************************************/

module core.config

import types
import io.file
import core.str
import encoding.toml
import core.result as res

export
    // Configuration structure
    type Config

    // Load configuration from file (with defaults if not found)
    fn load(): Config

    // Access functions for common settings
    fn get_arch(cfg: Config): string
    fn get_jobs(cfg: Config): int
    fn get_confirm(cfg: Config): bool
    fn get_color(cfg: Config): bool

    // Path accessors
    fn get_ports_dir(cfg: Config): string
    fn get_packages_dir(cfg: Config): string
    fn get_sources_dir(cfg: Config): string
    fn get_database_dir(cfg: Config): string
    fn get_build_dir(cfg: Config): string
    fn get_index_dir(cfg: Config): string
    // Legacy (for compatibility)
    fn get_work_dir(cfg: Config): string
    fn get_pkg_dir(cfg: Config): string

    // Root and prefix accessors
    fn get_root(cfg: Config): string
    fn get_prefix(cfg: Config): string
    fn get_sysconfdir(cfg: Config): string

    // Root-aware path accessors (prepend root to path)
    fn get_database_dir_rooted(cfg: Config): string
    fn get_install_prefix(cfg: Config): string

    // Apply command-line overrides to config
    fn apply_overrides(cfg: Config, root: string, prefix: string, no_chroot: bool): Config

    // Build settings
    fn get_cflags(cfg: Config): string
    fn get_cxxflags(cfg: Config): string
    fn get_makeflags(cfg: Config): string
    fn get_strip(cfg: Config): bool
    fn get_fallback_to_source(cfg: Config): bool
    fn get_compress_man(cfg: Config): bool
    fn get_clean_work(cfg: Config): bool
    fn get_clean_pkg(cfg: Config): bool
    fn get_logging(cfg: Config): bool
    fn get_quiet(cfg: Config): bool

    // Network settings
    fn get_timeout(cfg: Config): int
    fn get_retries(cfg: Config): int
    fn get_use_proxy(cfg: Config): bool

    // Sync settings
    fn get_auto_refresh(cfg: Config): bool

    // Cache settings
    fn get_keep_packages(cfg: Config): bool
    fn get_keep_sources(cfg: Config): bool

    // Security settings
    fn get_require_signed_repos(cfg: Config): bool
    fn get_require_signed_packages(cfg: Config): bool

    // Install settings
    fn get_chroot_scripts(cfg: Config): bool
end export

// Configuration structure
type Config = struct
    // [general]
    arch: string
    jobs: int
    confirm: bool
    color: bool

    // [paths]
    root: string
    prefix: string
    sysconfdir: string
    ports_dir: string
    packages_dir: string
    sources_dir: string
    database_dir: string
    build_dir: string
    index_dir: string
    // Legacy (kept for compatibility)
    work_dir: string
    pkg_dir: string

    // [build]
    cflags: string
    cxxflags: string
    makeflags: string
    strip: bool
    compress_man: bool
    fallback_to_source: bool
    clean_work: bool
    clean_pkg: bool
    logging: bool
    quiet: bool

    // [network]
    timeout: int
    retries: int
    use_proxy: bool

    // [sync]
    auto_refresh: bool

    // [cache]
    keep_packages: bool
    keep_sources: bool

    // [security]
    require_signed_repos: bool
    require_signed_packages: bool

    // [install]
    chroot_scripts: bool
end Config

// Create a default configuration
fn default_config(): Config
    return Config{
        // General
        arch: "amd64",
        jobs: 0,  // 0 = auto-detect
        confirm: true,
        color: true,

        // Paths (defaults from types)
        root: "",
        prefix: "/usr/local",
        sysconfdir: "/etc",
        ports_dir: types.get_ports_dir(),
        packages_dir: types.get_packages_dir(),
        sources_dir: types.get_sources_dir(),
        database_dir: types.get_db_dir(),
        build_dir: types.get_build_dir(),
        index_dir: types.get_index_dir(),
        // Legacy (for compatibility)
        work_dir: types.get_build_dir(),
        pkg_dir: types.get_build_dir(),

        // Build
        cflags: "-O2 -pipe",
        cxxflags: "-O2 -pipe",
        makeflags: "",
        strip: true,
        compress_man: true,
        fallback_to_source: true,
        clean_work: true,
        clean_pkg: true,
        logging: true,
        quiet: false,

        // Network
        timeout: 30,
        retries: 3,
        use_proxy: false,

        // Sync
        auto_refresh: false,

        // Cache
        keep_packages: true,
        keep_sources: true,

        // Security
        require_signed_repos: false,
        require_signed_packages: false,

        // Install
        chroot_scripts: true
    }
end default_config

// Load configuration from file
fn load(): Config
    mut cfg = default_config()

    // Check if config file exists
    if not file.fileExists(types.get_config_file())
        return cfg
    end if

    // Read config file
    let content = res.unwrap_or(file.readFile(types.get_config_file()), "")
    if str.length(content) == 0
        return cfg
    end if

    // Parse TOML
    let keys = toml.toml_alloc_keys()
    let vals = toml.toml_alloc_values()
    let entry_count = res.unwrap_or(toml.toml_parse(content, keys, vals), 0)

    if entry_count == 0
        return cfg
    end if

    // [general] section
    if toml.toml_has_key(keys, vals, entry_count, "general.arch")
        cfg.arch = toml.toml_get(keys, vals, entry_count, "general.arch")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "general.jobs")
        cfg.jobs = toml.toml_get_int(keys, vals, entry_count, "general.jobs")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "general.confirm")
        cfg.confirm = toml.toml_get_bool(keys, vals, entry_count, "general.confirm")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "general.color")
        cfg.color = toml.toml_get_bool(keys, vals, entry_count, "general.color")
    end if

    // [paths] section
    if toml.toml_has_key(keys, vals, entry_count, "paths.root")
        cfg.root = toml.toml_get(keys, vals, entry_count, "paths.root")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "paths.prefix")
        cfg.prefix = toml.toml_get(keys, vals, entry_count, "paths.prefix")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "paths.sysconfdir")
        cfg.sysconfdir = toml.toml_get(keys, vals, entry_count, "paths.sysconfdir")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "paths.ports")
        cfg.ports_dir = toml.toml_get(keys, vals, entry_count, "paths.ports")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "paths.packages")
        cfg.packages_dir = toml.toml_get(keys, vals, entry_count, "paths.packages")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "paths.sources")
        cfg.sources_dir = toml.toml_get(keys, vals, entry_count, "paths.sources")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "paths.database")
        cfg.database_dir = toml.toml_get(keys, vals, entry_count, "paths.database")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "paths.build")
        cfg.build_dir = toml.toml_get(keys, vals, entry_count, "paths.build")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "paths.index")
        cfg.index_dir = toml.toml_get(keys, vals, entry_count, "paths.index")
    end if
    // Legacy path support (maps to build_dir)
    if toml.toml_has_key(keys, vals, entry_count, "paths.work")
        cfg.work_dir = toml.toml_get(keys, vals, entry_count, "paths.work")
        cfg.build_dir = cfg.work_dir  // Also set new field
    end if
    if toml.toml_has_key(keys, vals, entry_count, "paths.pkg")
        cfg.pkg_dir = toml.toml_get(keys, vals, entry_count, "paths.pkg")
    end if

    // [build] section
    if toml.toml_has_key(keys, vals, entry_count, "build.cflags")
        cfg.cflags = toml.toml_get(keys, vals, entry_count, "build.cflags")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "build.cxxflags")
        cfg.cxxflags = toml.toml_get(keys, vals, entry_count, "build.cxxflags")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "build.makeflags")
        cfg.makeflags = toml.toml_get(keys, vals, entry_count, "build.makeflags")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "build.strip")
        cfg.strip = toml.toml_get_bool(keys, vals, entry_count, "build.strip")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "build.compress_man")
        cfg.compress_man = toml.toml_get_bool(keys, vals, entry_count, "build.compress_man")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "build.fallback_to_source")
        cfg.fallback_to_source = toml.toml_get_bool(keys, vals, entry_count, "build.fallback_to_source")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "build.clean_work")
        cfg.clean_work = toml.toml_get_bool(keys, vals, entry_count, "build.clean_work")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "build.clean_pkg")
        cfg.clean_pkg = toml.toml_get_bool(keys, vals, entry_count, "build.clean_pkg")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "build.logging")
        cfg.logging = toml.toml_get_bool(keys, vals, entry_count, "build.logging")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "build.quiet")
        cfg.quiet = toml.toml_get_bool(keys, vals, entry_count, "build.quiet")
    end if

    // [network] section
    if toml.toml_has_key(keys, vals, entry_count, "network.timeout")
        cfg.timeout = toml.toml_get_int(keys, vals, entry_count, "network.timeout")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "network.retries")
        cfg.retries = toml.toml_get_int(keys, vals, entry_count, "network.retries")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "network.use_proxy")
        cfg.use_proxy = toml.toml_get_bool(keys, vals, entry_count, "network.use_proxy")
    end if

    // [sync] section
    if toml.toml_has_key(keys, vals, entry_count, "sync.auto_refresh")
        cfg.auto_refresh = toml.toml_get_bool(keys, vals, entry_count, "sync.auto_refresh")
    end if

    // [cache] section
    if toml.toml_has_key(keys, vals, entry_count, "cache.keep_packages")
        cfg.keep_packages = toml.toml_get_bool(keys, vals, entry_count, "cache.keep_packages")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "cache.keep_sources")
        cfg.keep_sources = toml.toml_get_bool(keys, vals, entry_count, "cache.keep_sources")
    end if

    // [security] section
    if toml.toml_has_key(keys, vals, entry_count, "security.require_signed_repos")
        cfg.require_signed_repos = toml.toml_get_bool(keys, vals, entry_count, "security.require_signed_repos")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "security.require_signed_packages")
        cfg.require_signed_packages = toml.toml_get_bool(keys, vals, entry_count, "security.require_signed_packages")
    end if

    // [install] section
    if toml.toml_has_key(keys, vals, entry_count, "install.chroot_scripts")
        cfg.chroot_scripts = toml.toml_get_bool(keys, vals, entry_count, "install.chroot_scripts")
    end if

    return cfg
end load

// Accessor functions
fn get_arch(cfg: Config): string
    return cfg.arch
end get_arch

fn get_jobs(cfg: Config): int
    return cfg.jobs
end get_jobs

fn get_confirm(cfg: Config): bool
    return cfg.confirm
end get_confirm

fn get_color(cfg: Config): bool
    return cfg.color
end get_color

fn get_ports_dir(cfg: Config): string
    return cfg.ports_dir
end get_ports_dir

fn get_packages_dir(cfg: Config): string
    return cfg.packages_dir
end get_packages_dir

fn get_sources_dir(cfg: Config): string
    return cfg.sources_dir
end get_sources_dir

fn get_database_dir(cfg: Config): string
    return cfg.database_dir
end get_database_dir

fn get_build_dir(cfg: Config): string
    return cfg.build_dir
end get_build_dir

fn get_index_dir(cfg: Config): string
    return cfg.index_dir
end get_index_dir

// Legacy accessors (for compatibility)
fn get_work_dir(cfg: Config): string
    return cfg.build_dir
end get_work_dir

fn get_pkg_dir(cfg: Config): string
    return cfg.build_dir
end get_pkg_dir

fn get_cflags(cfg: Config): string
    return cfg.cflags
end get_cflags

fn get_cxxflags(cfg: Config): string
    return cfg.cxxflags
end get_cxxflags

fn get_makeflags(cfg: Config): string
    return cfg.makeflags
end get_makeflags

fn get_strip(cfg: Config): bool
    return cfg.strip
end get_strip

fn get_fallback_to_source(cfg: Config): bool
    return cfg.fallback_to_source
end get_fallback_to_source

fn get_compress_man(cfg: Config): bool
    return cfg.compress_man
end get_compress_man

fn get_clean_work(cfg: Config): bool
    return cfg.clean_work
end get_clean_work

fn get_clean_pkg(cfg: Config): bool
    return cfg.clean_pkg
end get_clean_pkg

fn get_logging(cfg: Config): bool
    return cfg.logging
end get_logging

fn get_quiet(cfg: Config): bool
    return cfg.quiet
end get_quiet

fn get_timeout(cfg: Config): int
    return cfg.timeout
end get_timeout

fn get_retries(cfg: Config): int
    return cfg.retries
end get_retries

fn get_use_proxy(cfg: Config): bool
    return cfg.use_proxy
end get_use_proxy

fn get_auto_refresh(cfg: Config): bool
    return cfg.auto_refresh
end get_auto_refresh

fn get_keep_packages(cfg: Config): bool
    return cfg.keep_packages
end get_keep_packages

fn get_keep_sources(cfg: Config): bool
    return cfg.keep_sources
end get_keep_sources

fn get_require_signed_repos(cfg: Config): bool
    return cfg.require_signed_repos
end get_require_signed_repos

fn get_require_signed_packages(cfg: Config): bool
    return cfg.require_signed_packages
end get_require_signed_packages

fn get_chroot_scripts(cfg: Config): bool
    return cfg.chroot_scripts
end get_chroot_scripts

// Get the alternate root path (empty string means /)
fn get_root(cfg: Config): string
    return cfg.root
end get_root

// Get the installation prefix (default /usr/local)
fn get_prefix(cfg: Config): string
    return cfg.prefix
end get_prefix

// Get the system configuration directory (default /etc)
fn get_sysconfdir(cfg: Config): string
    return cfg.sysconfdir
end get_sysconfdir

// Get database directory with root prepended
fn get_database_dir_rooted(cfg: Config): string
    if str.length(cfg.root) == 0
        return cfg.database_dir
    end if
    return cfg.root + cfg.database_dir
end get_database_dir_rooted

// Get the full install prefix (root + prefix)
// This is where package files should be installed
fn get_install_prefix(cfg: Config): string
    if str.length(cfg.root) == 0
        return cfg.prefix
    end if
    return cfg.root + cfg.prefix
end get_install_prefix

// Apply command-line overrides to config
// Call this after loading config to override with --root and --prefix flags
fn apply_overrides(cfg: Config, root: string, prefix: string, no_chroot: bool): Config
    mut result = cfg
    if str.length(root) > 0
        result.root = root
    end if
    if str.length(prefix) > 0
        result.prefix = prefix
    end if
    if no_chroot
        result.chroot_scripts = false
    end if
    return result
end apply_overrides

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: database.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Installed package database management

******************************************************************************/

module core.database

import types
import io.file
import io.dir
import io.path
import core.str
import encoding.toml
import util.mtree
import sys.process
import core.result as res

export
    // Check if a package is installed
    fn is_installed(name: string): bool

    // List all installed packages (returns count, fills names array)
    fn list_installed(names: [string], max_count: int): int

    // Get installed package details
    fn get_installed(name: string): types.InstalledPackage

    // Register a new installed package
    fn register_package(pkg: types.InstalledPackage): bool

    // Register package with file list copied from extract dir (more efficient)
    fn register_from_extract_dir(pkg: types.InstalledPackage, extract_dir: string): bool

    // Unregister (remove) a package from database
    fn unregister_package(name: string): bool

    // Get list of files owned by a package (returns count, fills files array)
    fn get_files(name: string, files: [string], max_count: int): int

    // Find which package owns a given file path
    fn find_owner(file_path: string): string

    // Find which package provides an alternative
    fn find_provider(alternative: string): string

    // Ensure database directories exist
    fn init_db(): bool

    // Scripts support
    fn get_scripts_dir(name: string): string
    fn store_scripts(name: string, extract_dir: string): bool
    fn has_stored_scripts(name: string): bool

    // Config files support
    fn store_config_files(name: string, extract_dir: string): bool
    fn get_config_files(name: string, config_files: [string], max_count: int): int

    // Manifest support
    fn get_manifest_path(name: string): string

    // Root-aware versions for alternate root installation
    fn init_db_rooted(root: string): bool
    fn register_from_extract_dir_rooted(pkg: types.InstalledPackage, extract_dir: string, root: string): bool
    fn store_scripts_rooted(name: string, extract_dir: string, root: string): bool
    fn store_config_files_rooted(name: string, extract_dir: string, root: string): bool
    fn is_installed_rooted(name: string, root: string): bool
    fn list_installed_rooted(names: [string], max_count: int, root: string): int
    fn get_installed_rooted(name: string, root: string): types.InstalledPackage
    fn get_files_rooted(name: string, files: [string], max_count: int, root: string): int
    fn find_owner_rooted(file_path: string, root: string): string
    fn unregister_package_rooted(name: string, root: string): bool
end export

// Get the package database directory for a specific package
fn pkg_db_dir(name: string): string
    return path.join_path(types.get_db_dir(), name)
end pkg_db_dir

// Get the pkg.toml path for a package
fn pkg_toml_path(name: string): string
    return path.join_path(pkg_db_dir(name), "pkg.toml")
end pkg_toml_path

// Get the files.txt path for a package
fn pkg_files_path(name: string): string
    return path.join_path(pkg_db_dir(name), "files.txt")
end pkg_files_path

// Get the manifest.mtree path for a package
fn get_manifest_path(name: string): string
    return path.join_path(pkg_db_dir(name), "manifest.mtree")
end get_manifest_path

// Initialize the database directory structure
fn init_db(): bool
    if not dir.dir_exists(types.get_db_dir())
        return res.is_ok(dir.create_dir_all(types.get_db_dir()))
    end if
    return true
end init_db

// Check if a package is installed by looking for its database entry
fn is_installed(name: string): bool
    let pkg_dir = pkg_db_dir(name)
    if not dir.dir_exists(pkg_dir)
        return false
    end if
    // Also verify pkg.toml exists
    return file.fileExists(pkg_toml_path(name))
end is_installed

// List all installed packages by scanning the database directory
fn list_installed(names: [string], max_count: int): int
    if not dir.dir_exists(types.get_db_dir())
        return 0
    end if

    let entries = res.unwrap_or(dir.list_dir(types.get_db_dir()), new [string](0))
    let entry_count = entries.length()

    mut count = 0
    mut i = 0
    while i < entry_count and count < max_count
        let entry = entries[i]
        // Skip hidden files
        if str.length(entry) > 0 and entry[0] != '.'
            // Verify it's a valid package (has pkg.toml)
            let toml_path = pkg_toml_path(entry)
            if file.fileExists(toml_path)
                names[count] = entry
                count = count + 1
            end if
        end if
        i = i + 1
    end while

    return count
end list_installed

// Create an empty InstalledPackage
fn new_installed_package(): types.InstalledPackage
    return types.new_installed_package()
end new_installed_package

// Get details of an installed package
fn get_installed(name: string): types.InstalledPackage
    if not is_installed(name)
        return new_installed_package()
    end if

    // Read pkg.toml
    let toml_path = pkg_toml_path(name)
    let content = res.unwrap_or(file.readFile(toml_path), "")
    if str.length(content) == 0
        return new_installed_package()
    end if

    // Parse TOML
    let keys = toml.toml_alloc_keys()
    let vals = toml.toml_alloc_values()
    let entry_count = res.unwrap_or(toml.toml_parse(content, keys, vals), 0)

    if entry_count == 0
        return new_installed_package()
    end if

    // Build package info
    mut pkg = new_installed_package()
    pkg.info.name = toml.toml_get(keys, vals, entry_count, "package.name")
    pkg.info.version = toml.toml_get(keys, vals, entry_count, "package.version")
    pkg.info.release = toml.toml_get_int(keys, vals, entry_count, "package.release")
    pkg.info.description = toml.toml_get(keys, vals, entry_count, "package.description")
    pkg.info.url = toml.toml_get(keys, vals, entry_count, "package.url")
    pkg.info.license = toml.toml_get(keys, vals, entry_count, "package.license")
    pkg.info.maintainer = toml.toml_get(keys, vals, entry_count, "package.maintainer")
    pkg.info.arch = toml.toml_get(keys, vals, entry_count, "package.arch")

    // Install metadata
    pkg.install_date = toml.toml_get(keys, vals, entry_count, "install.date")
    pkg.install_reason = toml.toml_get(keys, vals, entry_count, "install.reason")

    // Read files list
    let files_path = pkg_files_path(name)
    if file.fileExists(files_path)
        let files_content = res.unwrap_or(file.readFile(files_path), "")
        if str.length(files_content) > 0
            let alloc_size = count_newlines(files_content) + 16
            mut files_arr: [string] = new [string](alloc_size)
            let files_count = str.split(files_content, '\n', files_arr, alloc_size)
            // Filter out empty lines
            mut valid_count = 0
            mut j = 0
            while j < files_count
                if str.length(files_arr[j]) > 0
                    valid_count = valid_count + 1
                end if
                j = j + 1
            end while
            pkg.files = files_arr
            pkg.files_count = valid_count
        end if
    end if

    return pkg
end get_installed

// Generate TOML content for a package
fn generate_pkg_toml(pkg: types.InstalledPackage): string
    mut content = "[package]\n"
    content = content + "name = \"" + pkg.info.name + "\"\n"
    content = content + "version = \"" + pkg.info.version + "\"\n"
    content = content + "release = " + int_to_str(pkg.info.release) + "\n"
    content = content + "description = \"" + pkg.info.description + "\"\n"
    content = content + "url = \"" + pkg.info.url + "\"\n"
    content = content + "license = \"" + pkg.info.license + "\"\n"
    content = content + "maintainer = \"" + pkg.info.maintainer + "\"\n"
    content = content + "arch = \"" + pkg.info.arch + "\"\n"
    content = content + "\n"
    content = content + "[install]\n"
    content = content + "date = \"" + pkg.install_date + "\"\n"
    content = content + "reason = \"" + pkg.install_reason + "\"\n"
    return content
end generate_pkg_toml

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

// Register a newly installed package
fn register_package(pkg: types.InstalledPackage): bool
    // Ensure database directory exists
    if not init_db()
        return false
    end if

    // Create package directory
    let pkg_dir = pkg_db_dir(pkg.info.name)
    if not dir.dir_exists(pkg_dir)
        if not res.is_ok(dir.create_dir_all(pkg_dir))
            return false
        end if
    end if

    // Write pkg.toml
    let toml_content = generate_pkg_toml(pkg)
    let toml_path = pkg_toml_path(pkg.info.name)
    if not res.is_ok(file.writeFile(toml_path, toml_content))
        return false
    end if

    // Note: files.txt is written by register_from_extract_dir for performance
    return true
end register_package

// Count newline characters in a string to estimate line count
fn count_newlines(s: string): int
    let slen = str.length(s)
    mut count = 0
    mut i = 0
    while i < slen
        if s[i] == '\n'
            count = count + 1
        end if
        i = i + 1
    end while
    return count
end count_newlines

// Process a .FOOTPRINT file content: filter and normalize paths
// Uses str.join() for O(n) single-allocation string building
fn process_footprint(content: string): string
    let newline_count = count_newlines(content)
    let alloc_size = newline_count + 16

    mut lines: [string] = new [string](alloc_size)
    let line_count = str.split(content, '\n', lines, alloc_size)

    mut result_lines: [string] = new [string](alloc_size)
    mut result_count = 0

    mut i = 0
    while i < line_count
        mut line = str.trim_ws(lines[i])

        if str.length(line) == 0
            i = i + 1
            continue
        end if

        // Strip leading ./
        if str.starts_with(line, "./")
            line = str.substring(line, 2, str.length(line) - 2)
        end if

        // Skip metadata files
        if str.equals(line, ".PKGINFO") or str.equals(line, ".FOOTPRINT")
            i = i + 1
            continue
        end if
        if str.starts_with(line, ".SCRIPTS")
            i = i + 1
            continue
        end if
        if str.equals(line, ".CONFIG")
            i = i + 1
            continue
        end if

        // Skip directories (end with /)
        let len = str.length(line)
        if len > 0 and line[len - 1] == '/'
            i = i + 1
            continue
        end if

        result_lines[result_count] = line
        result_count = result_count + 1
        i = i + 1
    end while

    return str.join(result_lines, result_count, "\n")
end process_footprint

// Extract file paths from mtree manifest content for files.txt
// Parses manifest entries and returns a newline-joined list of relative paths
// (files and symlinks only, no directories, no metadata)
fn extract_paths_from_manifest(content: string): string
    mut entries: [mtree.ManifestEntry] = new [mtree.ManifestEntry](8192)
    let count = mtree.parse_manifest(content, entries, 8192)

    mut result_lines: [string] = new [string](8192)
    mut result_count = 0

    mut i = 0
    while i < count
        let etype = mtree.entry_type(entries[i])
        let epath = mtree.entry_path(entries[i])

        // Only include files and symlinks (matches legacy files.txt behavior)
        if str.equals(etype, "file") or str.equals(etype, "link")
            // Strip leading ./
            if str.starts_with(epath, "./")
                result_lines[result_count] = str.substring(epath, 2, str.length(epath) - 2)
            else
                result_lines[result_count] = epath
            end if
            result_count = result_count + 1
        end if

        i = i + 1
    end while

    return str.join(result_lines, result_count, "\n")
end extract_paths_from_manifest

// Register package and copy files list from extracted package directory
fn register_from_extract_dir(pkg: types.InstalledPackage, extract_dir: string): bool
    // Register the package metadata
    if not register_package(pkg)
        return false
    end if

    let files_path = pkg_files_path(pkg.info.name)

    // Try .MANIFEST first (v2 format), fall back to .FOOTPRINT (legacy)
    let manifest_path = path.join_path(extract_dir, ".MANIFEST")
    if file.fileExists(manifest_path)
        // Store the full manifest for future use (verify, manifest-based remove)
        let manifest_store = path.join_path(pkg_db_dir(pkg.info.name), "manifest.mtree")
        let manifest_content = res.unwrap_or(file.readFile(manifest_path), "")
        file.writeFile(manifest_store, manifest_content)

        // Also generate files.txt for backward compatibility
        let result = extract_paths_from_manifest(manifest_content)
        return res.is_ok(file.writeFile(files_path, result))
    end if

    // Legacy: .FOOTPRINT
    let footprint_path = path.join_path(extract_dir, ".FOOTPRINT")
    if not file.fileExists(footprint_path)
        file.writeFile(files_path, "")
        return true
    end if

    let content = res.unwrap_or(file.readFile(footprint_path), "")
    if str.length(content) == 0
        file.writeFile(files_path, "")
        return true
    end if

    let result = process_footprint(content)
    return res.is_ok(file.writeFile(files_path, result))
end register_from_extract_dir

// Helper to remove a file
fn remove_file(file_path: string): bool
    let cmd = "rm -f \"" + file_path + "\""
    let pid = process.process_spawn_shell(cmd)
    if pid < 0
        return false
    end if
    let exit_code = process.process_wait(pid)
    return exit_code == 0
end remove_file

// Unregister a package from the database
fn unregister_package(name: string): bool
    if not is_installed(name)
        return true  // Already not installed
    end if

    let pkg_dir = pkg_db_dir(name)

    // Remove pkg.toml
    let toml_path = pkg_toml_path(name)
    if file.fileExists(toml_path)
        if not remove_file(toml_path)
            return false
        end if
    end if

    // Remove files.txt
    let files_path = pkg_files_path(name)
    if file.fileExists(files_path)
        if not remove_file(files_path)
            return false
        end if
    end if

    // Remove manifest.mtree
    let manifest_path = get_manifest_path(name)
    if file.fileExists(manifest_path)
        remove_file(manifest_path)
    end if

    // Remove scripts directory if exists
    let scripts_dir = get_scripts_dir(name)
    if dir.dir_exists(scripts_dir)
        let cmd = "rm -rf \"" + scripts_dir + "\""
        let pid = process.process_spawn_shell(cmd)
        if pid > 0
            process.process_wait(pid)
        end if
    end if

    // Remove config.txt if exists
    let config_path = pkg_config_path(name)
    if file.fileExists(config_path)
        remove_file(config_path)
    end if

    // Remove the package directory
    return res.is_ok(dir.remove_dir(pkg_dir))
end unregister_package

// Get list of files owned by a package
fn get_files(name: string, files: [string], max_count: int): int
    if not is_installed(name)
        return 0
    end if

    let files_path = pkg_files_path(name)
    if not file.fileExists(files_path)
        return 0
    end if

    let content = res.unwrap_or(file.readFile(files_path), "")
    if str.length(content) == 0
        return 0
    end if

    // Split by newlines — size dynamically
    let alloc_size = count_newlines(content) + 16
    mut all_lines: [string] = new [string](alloc_size)
    let line_count = str.split(content, '\n', all_lines, alloc_size)

    // Copy non-empty lines to output
    mut count = 0
    mut i = 0
    while i < line_count and count < max_count
        let line = str.trim_ws(all_lines[i])
        if str.length(line) > 0
            files[count] = line
            count = count + 1
        end if
        i = i + 1
    end while

    return count
end get_files

// Find which package owns a given file
fn find_owner(file_path: string): string
    // Normalize the path - strip leading "/" if present
    mut search_path = file_path
    if str.length(search_path) > 0 and search_path[0] == '/'
        search_path = str.substring(search_path, 1, str.length(search_path) - 1)
    end if

    // Get list of all installed packages
    mut packages: [string] = new [string](256)
    let pkg_count = list_installed(packages, 256)

    mut i = 0
    while i < pkg_count
        let pkg_name = packages[i]

        // Get files for this package
        mut files: [string] = new [string](4096)
        let file_count = get_files(pkg_name, files, 4096)

        // Search for matching file
        mut j = 0
        while j < file_count
            if files[j] == search_path
                return pkg_name
            end if
            j = j + 1
        end while

        i = i + 1
    end while

    return ""  // No owner found
end find_owner

// Find which package provides an alternative
fn find_provider(alternative: string): string
    // Get list of all installed packages
    mut packages: [string] = new [string](256)
    let pkg_count = list_installed(packages, 256)

    mut i = 0
    while i < pkg_count
        let pkg_name = packages[i]
        let pkg = get_installed(pkg_name)

        // Check alternatives array
        // Note: We'd need to parse the alternatives array from pkg.toml
        // For now, check if this package provides the alternative
        let toml_path = pkg_toml_path(pkg_name)
        let content = res.unwrap_or(file.readFile(toml_path), "")
        if str.length(content) > 0
            let keys = toml.toml_alloc_keys()
            let vals = toml.toml_alloc_values()
            let entry_count = res.unwrap_or(toml.toml_parse(content, keys, vals), 0)

            if toml.toml_has_key(keys, vals, entry_count, "package.alternatives")
                let alts_val = toml.toml_get(keys, vals, entry_count, "package.alternatives")
                // Check if the alternative is in the array
                if str.contains(alts_val, alternative)
                    return pkg_name
                end if
            end if
        end if

        i = i + 1
    end while

    return ""  // No provider found
end find_provider

// Get the scripts directory path for a package in the database
fn get_scripts_dir(name: string): string
    return path.join_path(pkg_db_dir(name), "scripts")
end get_scripts_dir

// Check if a package has stored scripts in the database
fn has_stored_scripts(name: string): bool
    let scripts_path = get_scripts_dir(name)
    return dir.dir_exists(scripts_path)
end has_stored_scripts

// Store scripts from an extracted package to the database
fn store_scripts(name: string, extract_dir: string): bool
    let src_scripts = path.join_path(extract_dir, ".SCRIPTS")

    // Check if source has scripts
    if not dir.dir_exists(src_scripts)
        return true  // No scripts is not an error
    end if

    let dest_scripts = get_scripts_dir(name)

    // Create scripts directory in database
    if not dir.dir_exists(dest_scripts)
        if not res.is_ok(dir.create_dir_all(dest_scripts))
            return false
        end if
    end if

    // Copy all script files
    let cmd = "cp -r \"" + src_scripts + "/\"* \"" + dest_scripts + "/\" 2>/dev/null"
    let pid = process.process_spawn_shell(cmd)
    if pid < 0
        return false
    end if
    let exit_code = process.process_wait(pid)
    // Don't fail if cp fails (might be empty directory)
    return true
end store_scripts

// Get the config.txt path for a package
fn pkg_config_path(name: string): string
    return path.join_path(pkg_db_dir(name), "config.txt")
end pkg_config_path

// Store config files list from an extracted package to the database
fn store_config_files(name: string, extract_dir: string): bool
    let src_config = path.join_path(extract_dir, ".CONFIG")

    // Check if source has config files list
    if not file.fileExists(src_config)
        return true  // No config files is not an error
    end if

    let dest_config = pkg_config_path(name)

    // Copy the config files list
    let content = res.unwrap_or(file.readFile(src_config), "")
    if str.length(content) > 0
        return res.is_ok(file.writeFile(dest_config, content))
    end if

    return true
end store_config_files

// Get list of config files for a package
fn get_config_files(name: string, config_files: [string], max_count: int): int
    let config_path = pkg_config_path(name)
    if not file.fileExists(config_path)
        return 0
    end if

    let content = res.unwrap_or(file.readFile(config_path), "")
    if str.length(content) == 0
        return 0
    end if

    // Split by newlines
    mut lines: [string] = new [string](max_count)
    let line_count = str.split(content, '\n', lines, max_count)

    // Filter out empty lines and comments
    mut count = 0
    mut i = 0
    while i < line_count and count < max_count
        let line = str.trim_ws(lines[i])
        if str.length(line) > 0 and line[0] != '#'
            config_files[count] = line
            count = count + 1
        end if
        i = i + 1
    end while

    return count
end get_config_files

// ============================================================================
// Root-aware functions for alternate root installation
// ============================================================================

// Get the rooted database directory
fn get_db_dir_rooted(root: string): string
    if str.length(root) == 0
        return types.get_db_dir()
    end if
    return root + types.get_db_dir()
end get_db_dir_rooted

// Get the rooted package database directory
fn pkg_db_dir_rooted(name: string, root: string): string
    return path.join_path(get_db_dir_rooted(root), name)
end pkg_db_dir_rooted

// Get the rooted pkg.toml path
fn pkg_toml_path_rooted(name: string, root: string): string
    return path.join_path(pkg_db_dir_rooted(name, root), "pkg.toml")
end pkg_toml_path_rooted

// Get the rooted files.txt path
fn pkg_files_path_rooted(name: string, root: string): string
    return path.join_path(pkg_db_dir_rooted(name, root), "files.txt")
end pkg_files_path_rooted

// Initialize database with alternate root
fn init_db_rooted(root: string): bool
    let db_dir = get_db_dir_rooted(root)
    if not dir.dir_exists(db_dir)
        return res.is_ok(dir.create_dir_all(db_dir))
    end if
    return true
end init_db_rooted

// Check if package is installed in alternate root
fn is_installed_rooted(name: string, root: string): bool
    let pkg_dir = pkg_db_dir_rooted(name, root)
    if not dir.dir_exists(pkg_dir)
        return false
    end if
    return file.fileExists(pkg_toml_path_rooted(name, root))
end is_installed_rooted

// Register package with alternate root
fn register_package_rooted(pkg: types.InstalledPackage, root: string): bool
    // Ensure database directory exists
    if not init_db_rooted(root)
        return false
    end if

    // Create package directory
    let pkg_dir = pkg_db_dir_rooted(pkg.info.name, root)
    if not dir.dir_exists(pkg_dir)
        if not res.is_ok(dir.create_dir_all(pkg_dir))
            return false
        end if
    end if

    // Write pkg.toml
    let toml_content = generate_pkg_toml(pkg)
    let toml_path = pkg_toml_path_rooted(pkg.info.name, root)
    if not res.is_ok(file.writeFile(toml_path, toml_content))
        return false
    end if

    return true
end register_package_rooted

// Register package from extract dir with alternate root
fn register_from_extract_dir_rooted(pkg: types.InstalledPackage, extract_dir: string, root: string): bool
    // Register the package metadata
    if not register_package_rooted(pkg, root)
        return false
    end if

    let files_path = pkg_files_path_rooted(pkg.info.name, root)

    // Try .MANIFEST first (v2 format), fall back to .FOOTPRINT (legacy)
    let manifest_path = path.join_path(extract_dir, ".MANIFEST")
    if file.fileExists(manifest_path)
        // Store the full manifest
        let manifest_store = path.join_path(pkg_db_dir_rooted(pkg.info.name, root), "manifest.mtree")
        let manifest_content = res.unwrap_or(file.readFile(manifest_path), "")
        file.writeFile(manifest_store, manifest_content)

        // Also generate files.txt for backward compatibility
        let result = extract_paths_from_manifest(manifest_content)
        return res.is_ok(file.writeFile(files_path, result))
    end if

    // Legacy: .FOOTPRINT
    let footprint_path = path.join_path(extract_dir, ".FOOTPRINT")
    if not file.fileExists(footprint_path)
        file.writeFile(files_path, "")
        return true
    end if

    let content = res.unwrap_or(file.readFile(footprint_path), "")
    if str.length(content) == 0
        file.writeFile(files_path, "")
        return true
    end if

    let result = process_footprint(content)
    return res.is_ok(file.writeFile(files_path, result))
end register_from_extract_dir_rooted

// Get scripts directory with alternate root
fn get_scripts_dir_rooted(name: string, root: string): string
    return path.join_path(pkg_db_dir_rooted(name, root), "scripts")
end get_scripts_dir_rooted

// Store scripts with alternate root
fn store_scripts_rooted(name: string, extract_dir: string, root: string): bool
    let src_scripts = path.join_path(extract_dir, ".SCRIPTS")

    if not dir.dir_exists(src_scripts)
        return true
    end if

    let dest_scripts = get_scripts_dir_rooted(name, root)

    if not dir.dir_exists(dest_scripts)
        if not res.is_ok(dir.create_dir_all(dest_scripts))
            return false
        end if
    end if

    let cmd = "cp -r \"" + src_scripts + "/\"* \"" + dest_scripts + "/\" 2>/dev/null"
    let pid = process.process_spawn_shell(cmd)
    if pid < 0
        return false
    end if
    process.process_wait(pid)
    return true
end store_scripts_rooted

// Get config path with alternate root
fn pkg_config_path_rooted(name: string, root: string): string
    return path.join_path(pkg_db_dir_rooted(name, root), "config.txt")
end pkg_config_path_rooted

// Store config files with alternate root
fn store_config_files_rooted(name: string, extract_dir: string, root: string): bool
    let src_config = path.join_path(extract_dir, ".CONFIG")

    if not file.fileExists(src_config)
        return true
    end if

    let dest_config = pkg_config_path_rooted(name, root)

    let content = res.unwrap_or(file.readFile(src_config), "")
    if str.length(content) > 0
        return res.is_ok(file.writeFile(dest_config, content))
    end if

    return true
end store_config_files_rooted

// List all installed packages in alternate root
fn list_installed_rooted(names: [string], max_count: int, root: string): int
    let db_dir = get_db_dir_rooted(root)
    if not dir.dir_exists(db_dir)
        return 0
    end if

    let entries = res.unwrap_or(dir.list_dir(db_dir), new [string](0))
    let entry_count = entries.length()

    mut count = 0
    mut i = 0
    while i < entry_count and count < max_count
        let entry = entries[i]
        // Skip hidden files
        if str.length(entry) > 0 and entry[0] != '.'
            // Verify it's a valid package (has pkg.toml)
            let toml_path = pkg_toml_path_rooted(entry, root)
            if file.fileExists(toml_path)
                names[count] = entry
                count = count + 1
            end if
        end if
        i = i + 1
    end while

    return count
end list_installed_rooted

// Get details of an installed package in alternate root
fn get_installed_rooted(name: string, root: string): types.InstalledPackage
    if not is_installed_rooted(name, root)
        return new_installed_package()
    end if

    // Read pkg.toml
    let toml_path = pkg_toml_path_rooted(name, root)
    let content = res.unwrap_or(file.readFile(toml_path), "")
    if str.length(content) == 0
        return new_installed_package()
    end if

    // Parse TOML
    let keys = toml.toml_alloc_keys()
    let vals = toml.toml_alloc_values()
    let entry_count = res.unwrap_or(toml.toml_parse(content, keys, vals), 0)

    if entry_count == 0
        return new_installed_package()
    end if

    // Build package info
    mut pkg = new_installed_package()
    pkg.info.name = toml.toml_get(keys, vals, entry_count, "package.name")
    pkg.info.version = toml.toml_get(keys, vals, entry_count, "package.version")
    pkg.info.release = toml.toml_get_int(keys, vals, entry_count, "package.release")
    pkg.info.description = toml.toml_get(keys, vals, entry_count, "package.description")
    pkg.info.url = toml.toml_get(keys, vals, entry_count, "package.url")
    pkg.info.license = toml.toml_get(keys, vals, entry_count, "package.license")
    pkg.info.maintainer = toml.toml_get(keys, vals, entry_count, "package.maintainer")
    pkg.info.arch = toml.toml_get(keys, vals, entry_count, "package.arch")

    // Install metadata
    pkg.install_date = toml.toml_get(keys, vals, entry_count, "install.date")
    pkg.install_reason = toml.toml_get(keys, vals, entry_count, "install.reason")

    // Read files list
    let files_path = pkg_files_path_rooted(name, root)
    if file.fileExists(files_path)
        let files_content = res.unwrap_or(file.readFile(files_path), "")
        if str.length(files_content) > 0
            let alloc_size = count_newlines(files_content) + 16
            mut files_arr: [string] = new [string](alloc_size)
            let files_count = str.split(files_content, '\n', files_arr, alloc_size)
            // Filter out empty lines
            mut valid_count = 0
            mut j = 0
            while j < files_count
                if str.length(files_arr[j]) > 0
                    valid_count = valid_count + 1
                end if
                j = j + 1
            end while
            pkg.files = files_arr
            pkg.files_count = valid_count
        end if
    end if

    return pkg
end get_installed_rooted

// Get list of files owned by a package in alternate root
fn get_files_rooted(name: string, files: [string], max_count: int, root: string): int
    if not is_installed_rooted(name, root)
        return 0
    end if

    let files_path = pkg_files_path_rooted(name, root)
    if not file.fileExists(files_path)
        return 0
    end if

    let content = res.unwrap_or(file.readFile(files_path), "")
    if str.length(content) == 0
        return 0
    end if

    // Split by newlines — size dynamically
    let alloc_size = count_newlines(content) + 16
    mut all_lines: [string] = new [string](alloc_size)
    let line_count = str.split(content, '\n', all_lines, alloc_size)

    // Copy non-empty lines to output
    mut count = 0
    mut i = 0
    while i < line_count and count < max_count
        let line = str.trim_ws(all_lines[i])
        if str.length(line) > 0
            files[count] = line
            count = count + 1
        end if
        i = i + 1
    end while

    return count
end get_files_rooted

// Find which package owns a given file in alternate root
fn find_owner_rooted(file_path: string, root: string): string
    // Normalize the path - strip leading "/" if present
    mut search_path = file_path
    if str.length(search_path) > 0 and search_path[0] == '/'
        search_path = str.substring(search_path, 1, str.length(search_path) - 1)
    end if

    // Get list of all installed packages in this root
    mut packages: [string] = new [string](256)
    let pkg_count = list_installed_rooted(packages, 256, root)

    mut i = 0
    while i < pkg_count
        let pkg_name = packages[i]

        // Get files for this package
        mut files: [string] = new [string](4096)
        let file_count = get_files_rooted(pkg_name, files, 4096, root)

        // Search for matching file
        mut j = 0
        while j < file_count
            if files[j] == search_path
                return pkg_name
            end if
            j = j + 1
        end while

        i = i + 1
    end while

    return ""  // No owner found
end find_owner_rooted

// Unregister a package from the database in alternate root
fn unregister_package_rooted(name: string, root: string): bool
    if not is_installed_rooted(name, root)
        return true  // Already not installed
    end if

    let pkg_dir = pkg_db_dir_rooted(name, root)

    // Remove pkg.toml
    let toml_path = pkg_toml_path_rooted(name, root)
    if file.fileExists(toml_path)
        if not remove_file(toml_path)
            return false
        end if
    end if

    // Remove files.txt
    let files_path = pkg_files_path_rooted(name, root)
    if file.fileExists(files_path)
        if not remove_file(files_path)
            return false
        end if
    end if

    // Remove scripts directory if exists
    let scripts_dir = get_scripts_dir_rooted(name, root)
    if dir.dir_exists(scripts_dir)
        let cmd = "rm -rf \"" + scripts_dir + "\""
        let pid = process.process_spawn_shell(cmd)
        if pid > 0
            process.process_wait(pid)
        end if
    end if

    // Remove config.txt if exists
    let config_path = pkg_config_path_rooted(name, root)
    if file.fileExists(config_path)
        remove_file(config_path)
    end if

    // Remove the package directory
    return res.is_ok(dir.remove_dir(pkg_dir))
end unregister_package_rooted

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: groups.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Package groups support for Coral (@groupname)

******************************************************************************/

module core.groups

import core.str
import io.file
import io.dir
import io.path
import encoding.toml
import types
import core.result as res

export
    type GroupResult

    fn load_group(name: string): GroupResult
    fn list_groups(groups: [types.PackageGroup], max_count: int): int
    fn expand_group(name: string, packages: [string], max_count: int): int
    fn is_group(name: string): bool
end export

// Result for group loading
type GroupResult = struct
    success: bool
    group: types.PackageGroup
    error: string
end GroupResult

// Get the groups directory
fn get_groups_dir(): string
    return types.get_groups_dir()
end get_groups_dir

// Create empty group
fn new_group(): types.PackageGroup
    return types.new_package_group()
end new_group

// Create success result
fn success_result(g: types.PackageGroup): GroupResult
    return GroupResult{ success: true, group: g, error: "" }
end success_result

// Create error result
fn error_result(msg: string): GroupResult
    return GroupResult{ success: false, group: new_group(), error: msg }
end error_result

// Check if a package name is a group reference (starts with @)
fn is_group(name: string): bool
    if str.length(name) < 2
        return false
    end if
    return name[0] == '@'
end is_group

// Load a group definition from TOML file
fn load_group(name: string): GroupResult
    // Remove @ prefix if present
    mut group_name = name
    if name[0] == '@'
        group_name = str.substring(name, 1, str.length(name) - 1)
    end if

    let groups_dir = get_groups_dir()
    let group_file = path.join_path(groups_dir, group_name + ".toml")

    if not file.fileExists(group_file)
        return error_result("Group not found: " + group_name)
    end if

    let content = res.unwrap_or(file.readFile(group_file), "")
    if str.length(content) == 0
        return error_result("Failed to read group file")
    end if

    // Parse TOML using key/value arrays
    let keys = toml.toml_alloc_keys()
    let vals = toml.toml_alloc_values()
    let entry_count = res.unwrap_or(toml.toml_parse(content, keys, vals), 0)

    if entry_count == 0
        return error_result("Invalid group file format")
    end if

    mut group = new_group()
    group.name = group_name

    // Get description
    if toml.toml_has_key(keys, vals, entry_count, "group.description")
        group.description = toml.toml_get(keys, vals, entry_count, "group.description")
    end if

    // Get members list (packages array)
    if toml.toml_has_key(keys, vals, entry_count, "group.packages")
        let members_str = toml.toml_get(keys, vals, entry_count, "group.packages")
        group.members_count = parse_toml_array(members_str, group.members, 256)
    end if

    return success_result(group)
end load_group

// List all available groups
fn list_groups(groups: [types.PackageGroup], max_count: int): int
    let groups_dir = get_groups_dir()

    if not dir.dir_exists(groups_dir)
        return 0
    end if

    let entries = res.unwrap_or(dir.list_dir(groups_dir), new [string](0))
    let entry_count = entries.length()

    mut count = 0
    mut i = 0
    while i < entry_count and count < max_count
        let entry = entries[i]
        // Look for .toml files
        if str.ends_with(entry, ".toml")
            let name_len = str.length(entry) - 5
            let name = str.substring(entry, 0, name_len)

            let result = load_group(name)
            if result.success
                groups[count] = result.group
                count = count + 1
            end if
        end if
        i = i + 1
    end while

    return count
end list_groups

// Expand a group to its member packages
fn expand_group(name: string, packages: [string], max_count: int): int
    let result = load_group(name)

    if not result.success
        return 0
    end if

    let group = result.group
    mut count = 0

    while count < group.members_count and count < max_count
        packages[count] = group.members[count]
        count = count + 1
    end while

    return count
end expand_group

// Parse TOML array value into string array
// Format: ["item1", "item2", "item3"]
fn parse_toml_array(value: string, result: [string], max_items: int): int
    let len = str.length(value)
    if len < 2
        return 0
    end if

    // Check for array brackets
    if value[0] != '['
        return 0
    end if

    mut count = 0
    mut i = 1
    mut in_string = false
    mut item_start = 0

    while i < len and count < max_items
        let c = value[i]

        if c == '"' and not in_string
            in_string = true
            item_start = i + 1
        elif c == '"' and in_string
            // End of string item
            let item_len = i - item_start
            if item_len > 0
                result[count] = str.substring(value, item_start, item_len)
                count = count + 1
            end if
            in_string = false
        elif c == ']' and not in_string
            // End of array
            return count
        end if

        i = i + 1
    end while

    return count
end parse_toml_array

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: package.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Package archive handling - extract, read metadata, install files

******************************************************************************/

module core.package

import types
import io.file
import io.dir
import io.path
import core.str
import encoding.toml
import util.archive
import util.mtree
import util.checksum
import sys.process
import fs.stat
import fs.perm
import fs.link
import fs.ops
import core.result as res

export
    // Package extraction result
    type ExtractResult

    // Extract a package to a temporary directory
    fn extract_package(pkg_path: string, dest_dir: string): ExtractResult

    // Read package info from an extracted package or archive
    fn read_pkginfo(pkg_path: string): types.PackageInfo

    // Read file list from an extracted package (legacy .FOOTPRINT or .MANIFEST)
    fn read_footprint(pkg_path: string, files: [string], max_count: int): int

    // Read manifest entries from an extracted package
    fn read_manifest(pkg_dir: string, entries: [mtree.ManifestEntry], max_count: int): int

    // Install files from extracted package to root (manifest-driven)
    fn install_files(src_dir: string, root: string): bool

    // Remove files listed in footprint from root
    fn remove_files(files: [string], file_count: int, root: string): bool

    // Remove files using manifest entries (with explicit directory tracking)
    fn remove_files_manifest(entries: [mtree.ManifestEntry], entry_count: int, root: string): bool

    // Verify package integrity (check all files exist in extracted dir)
    fn verify_package(pkg_dir: string): bool

    // Install files with old manifest for upgrade config protection
    fn install_files_upgrade(src_dir: string, root: string, old_entries: [mtree.ManifestEntry], old_entry_count: int): bool

    // Script execution context (chroot-confined maintainer scripts)
    type ScriptCtx
    fn new_script_ctx(root: string, do_chroot: bool): ScriptCtx
    fn script_wants_chroot(root: string, chroot_scripts: bool): bool
    fn build_script_cmd(ctx: ScriptCtx, script_path: string, script_name: string, args: string, is_sh: bool): string
    fn resolve_script_ctx(root: string, chroot_scripts: bool, caller_is_root: bool): ScriptCtx

    // Install scripts support (version passed as $VERSION to scripts)
    fn has_scripts(pkg_dir: string): bool
    fn run_pre_install(ctx: ScriptCtx, pkg_dir: string, version: string): bool
    fn run_post_install(ctx: ScriptCtx, pkg_dir: string, version: string): bool
    fn run_pre_remove(ctx: ScriptCtx, pkg_dir: string, version: string): bool
    fn run_post_remove(ctx: ScriptCtx, pkg_dir: string, version: string): bool

    // Upgrade scripts ($OLD_VERSION $NEW_VERSION passed to scripts)
    fn run_pre_upgrade(ctx: ScriptCtx, pkg_dir: string, old_version: string, new_version: string): bool
    fn run_post_upgrade(ctx: ScriptCtx, pkg_dir: string, old_version: string, new_version: string): bool

    // Run scripts from a stored scripts directory (for remove/upgrade operations)
    fn run_stored_pre_remove(ctx: ScriptCtx, scripts_dir: string, version: string): bool
    fn run_stored_post_remove(ctx: ScriptCtx, scripts_dir: string, version: string): bool
    fn run_stored_pre_upgrade(ctx: ScriptCtx, scripts_dir: string, old_version: string, new_version: string): bool
    fn run_stored_post_upgrade(ctx: ScriptCtx, scripts_dir: string, old_version: string, new_version: string): bool

    // Config file protection
    fn read_config_files(pkg_dir: string, config_files: [string], max_count: int): int
    fn is_config_file(rel_path: string, config_files: [string], config_count: int): bool
    fn install_config_file(src_path: string, dest_path: string, manifest_sha256: string, stored_sha256: string): bool
end export

// Extraction result
type ExtractResult = struct
    success: bool
    extract_dir: string
    error: string
end ExtractResult

// Create a failed extraction result
fn extract_error(msg: string): ExtractResult
    return ExtractResult{ success: false, extract_dir: "", error: msg }
end extract_error

// Create a successful extraction result
fn extract_success(dir: string): ExtractResult
    return ExtractResult{ success: true, extract_dir: dir, error: "" }
end extract_success

// Extract a package archive to destination directory
fn extract_package(pkg_path: string, dest_dir: string): ExtractResult
    // Verify package exists
    if not file.fileExists(pkg_path)
        return extract_error("Package file not found: " + pkg_path)
    end if

    // Ensure destination directory exists
    if not dir.dir_exists(dest_dir)
        if not res.is_ok(dir.create_dir_all(dest_dir))
            return extract_error("Failed to create extraction directory: " + dest_dir)
        end if
    end if

    // Extract using archive module
    if not archive.extract(pkg_path, dest_dir)
        return extract_error("Failed to extract package: " + pkg_path)
    end if

    // Verify .PKGINFO exists
    let pkginfo_path = path.join_path(dest_dir, ".PKGINFO")
    if not file.fileExists(pkginfo_path)
        return extract_error("Invalid package: missing .PKGINFO")
    end if

    return extract_success(dest_dir)
end extract_package

// Read package info from .PKGINFO in an extracted package directory
fn read_pkginfo(pkg_dir: string): types.PackageInfo
    mut info = types.new_package_info()

    let pkginfo_path = path.join_path(pkg_dir, ".PKGINFO")
    if not file.fileExists(pkginfo_path)
        return info
    end if

    let content = res.unwrap_or(file.readFile(pkginfo_path), "")
    if str.length(content) == 0
        return info
    end if

    // Parse TOML
    let keys = toml.toml_alloc_keys()
    let vals = toml.toml_alloc_values()
    let entry_count = res.unwrap_or(toml.toml_parse(content, keys, vals), 0)

    if entry_count == 0
        return info
    end if

    // Extract fields
    info.name = toml.toml_get(keys, vals, entry_count, "package.name")
    info.version = toml.toml_get(keys, vals, entry_count, "package.version")
    info.release = toml.toml_get_int(keys, vals, entry_count, "package.release")
    info.description = toml.toml_get(keys, vals, entry_count, "package.description")
    info.url = toml.toml_get(keys, vals, entry_count, "package.url")
    info.license = toml.toml_get(keys, vals, entry_count, "package.license")
    info.maintainer = toml.toml_get(keys, vals, entry_count, "package.maintainer")
    info.arch = toml.toml_get(keys, vals, entry_count, "package.arch")

    // Parse [dependencies] section (optional — legacy packages won't have it)
    if toml.toml_has_key(keys, vals, entry_count, "dependencies.runtime")
        let rt_val = toml.toml_get(keys, vals, entry_count, "dependencies.runtime")
        info.runtime_deps_count = parse_toml_array(rt_val, info.runtime_deps, 64)
    end if

    if toml.toml_has_key(keys, vals, entry_count, "dependencies.build")
        let bd_val = toml.toml_get(keys, vals, entry_count, "dependencies.build")
        info.build_deps_count = parse_toml_array(bd_val, info.build_deps, 64)
    end if

    return info
end read_pkginfo

// Read file list from .MANIFEST (v2) or .FOOTPRINT (legacy)
// Returns a flat list of relative file paths (files and symlinks only)
fn read_footprint(pkg_dir: string, files: [string], max_count: int): int
    // Try .MANIFEST first (v2 format)
    let manifest_path = path.join_path(pkg_dir, ".MANIFEST")
    if file.fileExists(manifest_path)
        let content = res.unwrap_or(file.readFile(manifest_path), "")
        if str.length(content) > 0
            mut entries: [mtree.ManifestEntry] = new [mtree.ManifestEntry](max_count)
            let entry_count = mtree.parse_manifest(content, entries, max_count)

            mut count = 0
            mut i = 0
            while i < entry_count and count < max_count
                let etype = mtree.entry_type(entries[i])
                // Only include files and symlinks (matches legacy behavior)
                if str.equals(etype, "file") or str.equals(etype, "link")
                    let epath = mtree.entry_path(entries[i])
                    if str.starts_with(epath, "./")
                        files[count] = str.substring(epath, 2, str.length(epath) - 2)
                    else
                        files[count] = epath
                    end if
                    count = count + 1
                end if
                i = i + 1
            end while

            return count
        end if
    end if

    // Fallback: legacy .FOOTPRINT
    let footprint_path = path.join_path(pkg_dir, ".FOOTPRINT")
    if not file.fileExists(footprint_path)
        return 0
    end if

    let content = res.unwrap_or(file.readFile(footprint_path), "")
    if str.length(content) == 0
        return 0
    end if

    mut lines: [string] = new [string](max_count)
    let line_count = str.split(content, '\n', lines, max_count)

    mut count = 0
    mut i = 0
    while i < line_count and count < max_count
        let line = str.trim_ws(lines[i])

        if str.length(line) == 0
            i = i + 1
            continue
        end if

        if str.equals(line, "./.PKGINFO") or str.equals(line, "./.FOOTPRINT")
            i = i + 1
            continue
        end if
        if str.equals(line, ".PKGINFO") or str.equals(line, ".FOOTPRINT")
            i = i + 1
            continue
        end if

        let len = str.length(line)
        if len > 0 and line[len - 1] == '/'
            i = i + 1
            continue
        end if

        if str.starts_with(line, "./")
            files[count] = str.substring(line, 2, len - 2)
        else
            files[count] = line
        end if
        count = count + 1

        i = i + 1
    end while

    return count
end read_footprint

// Read manifest entries from .MANIFEST in an extracted package directory
fn read_manifest(pkg_dir: string, entries: [mtree.ManifestEntry], max_count: int): int
    let manifest_path = path.join_path(pkg_dir, ".MANIFEST")
    if not file.fileExists(manifest_path)
        return 0
    end if

    let content = res.unwrap_or(file.readFile(manifest_path), "")
    if str.length(content) == 0
        return 0
    end if

    return mtree.parse_manifest(content, entries, max_count)
end read_manifest

// Install files from extracted package to root directory using manifest
fn install_files(src_dir: string, root: string): bool
    // Read config file list for protection checks
    mut config_files: [string] = new [string](256)
    let config_count = read_config_files(src_dir, config_files, 256)

    // Parse .MANIFEST
    mut entries: [mtree.ManifestEntry] = new [mtree.ManifestEntry](8192)
    let entry_count = read_manifest(src_dir, entries, 8192)

    if entry_count == 0
        return false
    end if

    // Walk manifest entries in order (dirs before their contents)
    mut i = 0
    while i < entry_count
        let entry = entries[i]
        let etype = mtree.entry_type(entry)
        let epath = mtree.entry_path(entry)

        // Strip leading ./ from manifest path to get relative path
        mut rel_path = epath
        if str.starts_with(epath, "./")
            rel_path = str.substring(epath, 2, str.length(epath) - 2)
        end if

        let dest_path = path.join_path(root, rel_path)
        let src_path = path.join_path(src_dir, rel_path)
        let mode = mtree.entry_mode(entry)
        let uid = mtree.name_to_uid(mtree.entry_uname(entry))
        let gid = mtree.name_to_gid(mtree.entry_gname(entry))

        if str.equals(etype, "dir")
            // Create directory if it doesn't exist
            if not dir.dir_exists(dest_path)
                if not res.is_ok(dir.create_dir_all(dest_path))
                    return false
                end if
            end if
            perm.chmod(dest_path, mode)
            perm.chown(dest_path, uid, gid)

        elif str.equals(etype, "file")
            // Check if this is a config-protected file
            if is_config_file(rel_path, config_files, config_count)
                // Config file — use checksum-based protection
                let manifest_sha = mtree.entry_sha256(entry)
                install_config_file(src_path, dest_path, manifest_sha, "")
            else
                // Ensure parent directory exists
                let parent = path.dirname(dest_path)
                if str.length(parent) > 0 and not dir.dir_exists(parent)
                    dir.create_dir_all(parent)
                end if

                // Remove any conflicting target (symlink, file, or dir)
                if stat.is_symlink(dest_path)
                    ops.remove_file(dest_path)
                elif stat.exists(dest_path)
                    ops.remove_file(dest_path)
                end if

                // Copy file preserving permissions from source
                if not res.is_ok(ops.copy_file_preserve(src_path, dest_path))
                    return false
                end if

                // Set permissions and ownership from manifest
                perm.chmod(dest_path, mode)
                perm.chown(dest_path, uid, gid)

                // Verify sha256 after copy
                let manifest_sha = mtree.entry_sha256(entry)
                if str.length(manifest_sha) > 0
                    let installed_sha = checksum.sha256_file(dest_path)
                    if not str.equals(installed_sha, manifest_sha)
                        return false
                    end if
                end if
            end if

        elif str.equals(etype, "link")
            let link_target = mtree.entry_link(entry)

            // Remove any conflicting target
            if stat.is_symlink(dest_path) or stat.exists(dest_path)
                ops.remove_file(dest_path)
            end if

            // Ensure parent directory exists
            let parent = path.dirname(dest_path)
            if str.length(parent) > 0 and not dir.dir_exists(parent)
                dir.create_dir_all(parent)
            end if

            // Create symlink
            if not res.is_ok(link.symlink(link_target, dest_path))
                return false
            end if
        end if

        i = i + 1
    end while

    return true
end install_files

// Remove files from root directory based on flat file list (legacy)
fn remove_files(files: [string], file_count: int, root: string): bool
    // Remove files in reverse order
    mut i = file_count - 1
    while i >= 0
        let rel_path = files[i]
        let full_path = path.join_path(root, rel_path)

        if stat.is_symlink(full_path) or stat.exists(full_path)
            ops.remove_file(full_path)
        end if

        i = i - 1
    end while

    // Try to remove empty parent directories
    i = file_count - 1
    while i >= 0
        let rel_path = files[i]
        let full_path = path.join_path(root, rel_path)
        let parent = path.dirname(full_path)

        if str.length(parent) > 0 and dir.dir_exists(parent)
            dir.remove_dir(parent)
        end if

        i = i - 1
    end while

    return true
end remove_files

// Remove files using manifest entries (with explicit directory tracking)
// Processes in reverse order: files/symlinks first, then directories
fn remove_files_manifest(entries: [mtree.ManifestEntry], entry_count: int, root: string): bool
    mut all_success = true

    // First pass: remove files and symlinks in reverse order
    mut i = entry_count - 1
    while i >= 0
        let entry = entries[i]
        let etype = mtree.entry_type(entry)
        let epath = mtree.entry_path(entry)

        mut rel_path = epath
        if str.starts_with(epath, "./")
            rel_path = str.substring(epath, 2, str.length(epath) - 2)
        end if

        let full_path = path.join_path(root, rel_path)

        if str.equals(etype, "file") or str.equals(etype, "link")
            if stat.is_symlink(full_path) or stat.exists(full_path)
                if not res.is_ok(ops.remove_file(full_path))
                    all_success = false
                end if
            end if
        end if

        i = i - 1
    end while

    // Second pass: remove directories in reverse order (deepest first)
    i = entry_count - 1
    while i >= 0
        let entry = entries[i]
        let etype = mtree.entry_type(entry)
        let epath = mtree.entry_path(entry)

        if str.equals(etype, "dir")
            mut rel_path = epath
            if str.starts_with(epath, "./")
                rel_path = str.substring(epath, 2, str.length(epath) - 2)
            end if

            let full_path = path.join_path(root, rel_path)

            // Only remove empty directories (remove_dir fails on non-empty)
            if dir.dir_exists(full_path)
                dir.remove_dir(full_path)
            end if
        end if

        i = i - 1
    end while

    return all_success
end remove_files_manifest

// Verify package has required files
fn verify_package(pkg_dir: string): bool
    // Check for .PKGINFO
    let pkginfo_path = path.join_path(pkg_dir, ".PKGINFO")
    if not file.fileExists(pkginfo_path)
        return false
    end if

    // Check for .MANIFEST (or legacy .FOOTPRINT)
    let manifest_path = path.join_path(pkg_dir, ".MANIFEST")
    let footprint_path = path.join_path(pkg_dir, ".FOOTPRINT")
    if not file.fileExists(manifest_path) and not file.fileExists(footprint_path)
        return false
    end if

    // Verify we can read package info
    let info = read_pkginfo(pkg_dir)
    if str.length(info.name) == 0
        return false
    end if

    return true
end verify_package

// Check if package has install/remove scripts
fn has_scripts(pkg_dir: string): bool
    let scripts_dir = path.join_path(pkg_dir, ".SCRIPTS")
    return dir.dir_exists(scripts_dir)
end has_scripts

// Context describing where a package's maintainer scripts run.
// root == "/"  -> normal install on the live system
// do_chroot    -> confine scripts to root via chroot (root must be != "/")
type ScriptCtx = struct
    root: string
    do_chroot: bool
end ScriptCtx

// Construct a ScriptCtx.
fn new_script_ctx(root: string, do_chroot: bool): ScriptCtx
    return ScriptCtx{ root: root, do_chroot: do_chroot }
end new_script_ctx

// Pure predicate: should scripts be chrooted for this root + config?
fn script_wants_chroot(root: string, chroot_scripts: bool): bool
    if str.equals(root, "/")
        return false
    end if
    return chroot_scripts
end script_wants_chroot

// Resolve the script execution context for a command flow.
// want_chroot requires both a non-"/" root with chroot enabled AND a root caller;
// the caller is responsible for aborting first when chroot is wanted but caller_is_root
// is false (see resolve in the command flows).
fn resolve_script_ctx(root: string, chroot_scripts: bool, caller_is_root: bool): ScriptCtx
    mut want_chroot = script_wants_chroot(root, chroot_scripts)
    if not caller_is_root
        want_chroot = false
    end if
    return new_script_ctx(root, want_chroot)
end resolve_script_ctx

// The single place a maintainer-script shell command is assembled.
// is_sh true  -> run under zsh; false -> execute the file directly.
fn build_script_cmd(ctx: ScriptCtx, script_path: string, script_name: string, args: string, is_sh: bool): string
    mut cmd = ""
    if ctx.do_chroot
        // Confined: run inside <root>; from the script's view the target is "/".
        let in_root_path = "/.SCRIPTS/" + script_name
        mut body = ""
        if is_sh
            body = "zsh \"" + in_root_path + "\""
        else
            body = "\"" + in_root_path + "\""
        end if
        cmd = "chroot \"" + ctx.root + "\" env CORAL_ROOT=\"/\" " + body
    else
        // Host: normal install or --no-chroot-scripts. Export CORAL_ROOT=ctx.root.
        mut body = ""
        if is_sh
            body = "zsh \"" + script_path + "\""
        else
            body = "\"" + script_path + "\""
        end if
        cmd = "CORAL_ROOT=\"" + ctx.root + "\" " + body
    end if

    if str.length(args) > 0
        cmd = cmd + " " + args
    end if
    return cmd
end build_script_cmd

// Copy a package's .SCRIPTS dir into <root>/.SCRIPTS so it is reachable post-chroot.
fn stage_scripts_in_root(pkg_scripts_dir: string, root: string): bool
    let dest = path.join_path(root, ".SCRIPTS")
    // Clean any stale staging first.
    let rm_cmd = "rm -rf \"" + dest + "\""
    let rm_pid = process.process_spawn_shell(rm_cmd)
    process.process_wait(rm_pid)
    // Copy preserving perms/owner/symlinks.
    let cp_cmd = "cp -a \"" + pkg_scripts_dir + "\" \"" + dest + "\""
    let pid = process.process_spawn_shell(cp_cmd)
    if pid < 0
        return false
    end if
    let code = process.process_wait(pid)
    return code == 0
end stage_scripts_in_root

// Remove staged scripts from <root>/.SCRIPTS.
proc unstage_scripts_in_root(root: string)
    let dest = path.join_path(root, ".SCRIPTS")
    let cmd = "rm -rf \"" + dest + "\""
    let pid = process.process_spawn_shell(cmd)
    process.process_wait(pid)
end unstage_scripts_in_root

// Run a script from the .SCRIPTS directory
fn run_script(ctx: ScriptCtx, pkg_dir: string, script_name: string, script_args: string): bool
    let scripts_dir = path.join_path(pkg_dir, ".SCRIPTS")
    let script_path = path.join_path(scripts_dir, script_name)

    if not file.fileExists(script_path)
        return true
    end if

    if ctx.do_chroot
        if not stage_scripts_in_root(scripts_dir, ctx.root)
            // Staging may have left a partial <root>/.SCRIPTS; clean it before bailing.
            unstage_scripts_in_root(ctx.root)
            return false
        end if
    end if

    let is_sh = str.ends_with(script_name, ".sh")
    let cmd = build_script_cmd(ctx, script_path, script_name, script_args, is_sh)

    let pid = process.process_spawn_shell(cmd)
    mut ok = false
    if pid >= 0
        let exit_code = process.process_wait(pid)
        ok = exit_code == 0
    end if

    if ctx.do_chroot
        unstage_scripts_in_root(ctx.root)
    end if
    return ok
end run_script

// Run pre-install script (passes $VERSION)
fn run_pre_install(ctx: ScriptCtx, pkg_dir: string, version: string): bool
    if not has_scripts(pkg_dir)
        return true
    end if
    let args = "\"" + version + "\""
    let scripts_dir = path.join_path(pkg_dir, ".SCRIPTS")
    // Try .sh first, then bare executable
    let sh_path = path.join_path(scripts_dir, "pre-install.sh")
    if file.fileExists(sh_path)
        return run_script(ctx, pkg_dir, "pre-install.sh", args)
    end if
    return run_script(ctx, pkg_dir, "pre-install", args)
end run_pre_install

// Run post-install script (passes $VERSION)
fn run_post_install(ctx: ScriptCtx, pkg_dir: string, version: string): bool
    if not has_scripts(pkg_dir)
        return true
    end if
    let args = "\"" + version + "\""
    let scripts_dir = path.join_path(pkg_dir, ".SCRIPTS")
    let sh_path = path.join_path(scripts_dir, "post-install.sh")
    if file.fileExists(sh_path)
        return run_script(ctx, pkg_dir, "post-install.sh", args)
    end if
    return run_script(ctx, pkg_dir, "post-install", args)
end run_post_install

// Run pre-remove script (passes $VERSION)
fn run_pre_remove(ctx: ScriptCtx, pkg_dir: string, version: string): bool
    if not has_scripts(pkg_dir)
        return true
    end if
    let args = "\"" + version + "\""
    let scripts_dir = path.join_path(pkg_dir, ".SCRIPTS")
    let sh_path = path.join_path(scripts_dir, "pre-remove.sh")
    if file.fileExists(sh_path)
        return run_script(ctx, pkg_dir, "pre-remove.sh", args)
    end if
    return run_script(ctx, pkg_dir, "pre-remove", args)
end run_pre_remove

// Run post-remove script (passes $VERSION)
fn run_post_remove(ctx: ScriptCtx, pkg_dir: string, version: string): bool
    if not has_scripts(pkg_dir)
        return true
    end if
    let args = "\"" + version + "\""
    let scripts_dir = path.join_path(pkg_dir, ".SCRIPTS")
    let sh_path = path.join_path(scripts_dir, "post-remove.sh")
    if file.fileExists(sh_path)
        return run_script(ctx, pkg_dir, "post-remove.sh", args)
    end if
    return run_script(ctx, pkg_dir, "post-remove", args)
end run_post_remove

// Run pre-upgrade script (passes $OLD_VERSION $NEW_VERSION)
fn run_pre_upgrade(ctx: ScriptCtx, pkg_dir: string, old_version: string, new_version: string): bool
    if not has_scripts(pkg_dir)
        return true
    end if
    let args = "\"" + old_version + "\" \"" + new_version + "\""
    let scripts_dir = path.join_path(pkg_dir, ".SCRIPTS")
    let sh_path = path.join_path(scripts_dir, "pre-upgrade.sh")
    if file.fileExists(sh_path)
        return run_script(ctx, pkg_dir, "pre-upgrade.sh", args)
    end if
    return run_script(ctx, pkg_dir, "pre-upgrade", args)
end run_pre_upgrade

// Run post-upgrade script (passes $OLD_VERSION $NEW_VERSION)
fn run_post_upgrade(ctx: ScriptCtx, pkg_dir: string, old_version: string, new_version: string): bool
    if not has_scripts(pkg_dir)
        return true
    end if
    let args = "\"" + old_version + "\" \"" + new_version + "\""
    let scripts_dir = path.join_path(pkg_dir, ".SCRIPTS")
    let sh_path = path.join_path(scripts_dir, "post-upgrade.sh")
    if file.fileExists(sh_path)
        return run_script(ctx, pkg_dir, "post-upgrade.sh", args)
    end if
    return run_script(ctx, pkg_dir, "post-upgrade", args)
end run_post_upgrade

// Run a script directly from a stored scripts directory
fn run_stored_script(ctx: ScriptCtx, scripts_dir: string, script_name: string, script_args: string): bool
    let script_path = path.join_path(scripts_dir, script_name)

    if not file.fileExists(script_path)
        return true
    end if

    if ctx.do_chroot
        if not stage_scripts_in_root(scripts_dir, ctx.root)
            // Staging may have left a partial <root>/.SCRIPTS; clean it before bailing.
            unstage_scripts_in_root(ctx.root)
            return false
        end if
    end if

    let is_sh = str.ends_with(script_name, ".sh")
    let cmd = build_script_cmd(ctx, script_path, script_name, script_args, is_sh)

    let pid = process.process_spawn_shell(cmd)
    mut ok = false
    if pid >= 0
        let exit_code = process.process_wait(pid)
        ok = exit_code == 0
    end if

    if ctx.do_chroot
        unstage_scripts_in_root(ctx.root)
    end if
    return ok
end run_stored_script

// Run pre-remove script from stored scripts directory (passes $VERSION)
fn run_stored_pre_remove(ctx: ScriptCtx, scripts_dir: string, version: string): bool
    if not dir.dir_exists(scripts_dir)
        return true
    end if
    let args = "\"" + version + "\""
    let sh_path = path.join_path(scripts_dir, "pre-remove.sh")
    if file.fileExists(sh_path)
        return run_stored_script(ctx, scripts_dir, "pre-remove.sh", args)
    end if
    return run_stored_script(ctx, scripts_dir, "pre-remove", args)
end run_stored_pre_remove

// Run post-remove script from stored scripts directory (passes $VERSION)
fn run_stored_post_remove(ctx: ScriptCtx, scripts_dir: string, version: string): bool
    if not dir.dir_exists(scripts_dir)
        return true
    end if
    let args = "\"" + version + "\""
    let sh_path = path.join_path(scripts_dir, "post-remove.sh")
    if file.fileExists(sh_path)
        return run_stored_script(ctx, scripts_dir, "post-remove.sh", args)
    end if
    return run_stored_script(ctx, scripts_dir, "post-remove", args)
end run_stored_post_remove

// Run pre-upgrade script from stored scripts directory (passes $OLD_VERSION $NEW_VERSION)
fn run_stored_pre_upgrade(ctx: ScriptCtx, scripts_dir: string, old_version: string, new_version: string): bool
    if not dir.dir_exists(scripts_dir)
        return true
    end if
    let args = "\"" + old_version + "\" \"" + new_version + "\""
    let sh_path = path.join_path(scripts_dir, "pre-upgrade.sh")
    if file.fileExists(sh_path)
        return run_stored_script(ctx, scripts_dir, "pre-upgrade.sh", args)
    end if
    return run_stored_script(ctx, scripts_dir, "pre-upgrade", args)
end run_stored_pre_upgrade

// Run post-upgrade script from stored scripts directory (passes $OLD_VERSION $NEW_VERSION)
fn run_stored_post_upgrade(ctx: ScriptCtx, scripts_dir: string, old_version: string, new_version: string): bool
    if not dir.dir_exists(scripts_dir)
        return true
    end if
    let args = "\"" + old_version + "\" \"" + new_version + "\""
    let sh_path = path.join_path(scripts_dir, "post-upgrade.sh")
    if file.fileExists(sh_path)
        return run_stored_script(ctx, scripts_dir, "post-upgrade.sh", args)
    end if
    return run_stored_script(ctx, scripts_dir, "post-upgrade", args)
end run_stored_post_upgrade

// Read list of config files from .CONFIG file in extracted package
fn read_config_files(pkg_dir: string, config_files: [string], max_count: int): int
    let config_path = path.join_path(pkg_dir, ".CONFIG")
    if not file.fileExists(config_path)
        return 0
    end if

    let content = res.unwrap_or(file.readFile(config_path), "")
    if str.length(content) == 0
        return 0
    end if

    // Split by newlines
    mut lines: [string] = new [string](max_count)
    let line_count = str.split(content, '\n', lines, max_count)

    // Filter out empty lines
    mut count = 0
    mut i = 0
    while i < line_count and count < max_count
        let line = str.trim_ws(lines[i])
        if str.length(line) > 0 and line[0] != '#'
            // Normalize path (remove leading ./)
            if str.starts_with(line, "./")
                config_files[count] = str.substring(line, 2, str.length(line) - 2)
            else
                config_files[count] = line
            end if
            count = count + 1
        end if
        i = i + 1
    end while

    return count
end read_config_files

// Check if a file path is in the config files list
fn is_config_file(rel_path: string, config_files: [string], config_count: int): bool
    mut i = 0
    while i < config_count
        if str.equals(rel_path, config_files[i])
            return true
        end if
        i = i + 1
    end while
    return false
end is_config_file

// Install a config file with checksum-based protection.
// manifest_sha256: checksum of the new package's config file
// stored_sha256: checksum from the previously installed package version (empty on fresh install)
fn install_config_file(src_path: string, dest_path: string, manifest_sha256: string, stored_sha256: string): bool
    if not stat.exists(dest_path)
        // Fresh install — file doesn't exist yet
        // Create parent directory if needed
        let dest_dir = path.dirname(dest_path)
        if str.length(dest_dir) > 0 and not dir.dir_exists(dest_dir)
            dir.create_dir_all(dest_dir)
        end if

        return res.is_ok(ops.copy_file_preserve(src_path, dest_path))
    end if

    // File exists — check if user has modified it
    if str.length(stored_sha256) == 0
        // No stored checksum (fresh install over existing file or legacy package)
        // Be safe: install as .pkg-new, preserve user's file
        let new_path = dest_path + ".pkg-new"
        return res.is_ok(ops.copy_file_preserve(src_path, new_path))
    end if

    let installed_sha = checksum.sha256_file(dest_path)

    if str.equals(installed_sha, stored_sha256)
        // User has not modified the config — safe to overwrite
        return res.is_ok(ops.copy_file_preserve(src_path, dest_path))
    else
        // User has modified the config — preserve their version
        let new_path = dest_path + ".pkg-new"
        return res.is_ok(ops.copy_file_preserve(src_path, new_path))
    end if
end install_config_file

// Look up sha256 for a path in manifest entries
fn find_manifest_sha256(rel_path: string, entries: [mtree.ManifestEntry], count: int): string
    mut i = 0
    while i < count
        let epath = mtree.entry_path(entries[i])
        mut entry_rel = epath
        if str.starts_with(epath, "./")
            entry_rel = str.substring(epath, 2, str.length(epath) - 2)
        end if
        if str.equals(entry_rel, rel_path)
            return mtree.entry_sha256(entries[i])
        end if
        i = i + 1
    end while
    return ""
end find_manifest_sha256

// Install files from extracted package with old manifest for upgrade config protection
fn install_files_upgrade(src_dir: string, root: string, old_entries: [mtree.ManifestEntry], old_entry_count: int): bool
    mut config_files: [string] = new [string](256)
    let config_count = read_config_files(src_dir, config_files, 256)

    mut entries: [mtree.ManifestEntry] = new [mtree.ManifestEntry](8192)
    let entry_count = read_manifest(src_dir, entries, 8192)

    if entry_count == 0
        return false
    end if

    mut i = 0
    while i < entry_count
        let entry = entries[i]
        let etype = mtree.entry_type(entry)
        let epath = mtree.entry_path(entry)

        mut rel_path = epath
        if str.starts_with(epath, "./")
            rel_path = str.substring(epath, 2, str.length(epath) - 2)
        end if

        let dest_path = path.join_path(root, rel_path)
        let src_path = path.join_path(src_dir, rel_path)
        let mode = mtree.entry_mode(entry)
        let uid = mtree.name_to_uid(mtree.entry_uname(entry))
        let gid = mtree.name_to_gid(mtree.entry_gname(entry))

        if str.equals(etype, "dir")
            if not dir.dir_exists(dest_path)
                if not res.is_ok(dir.create_dir_all(dest_path))
                    return false
                end if
            end if
            perm.chmod(dest_path, mode)
            perm.chown(dest_path, uid, gid)

        elif str.equals(etype, "file")
            if is_config_file(rel_path, config_files, config_count)
                let manifest_sha = mtree.entry_sha256(entry)
                // Look up old sha256 from previous version's manifest
                let stored_sha = find_manifest_sha256(rel_path, old_entries, old_entry_count)
                install_config_file(src_path, dest_path, manifest_sha, stored_sha)
            else
                let parent = path.dirname(dest_path)
                if str.length(parent) > 0 and not dir.dir_exists(parent)
                    dir.create_dir_all(parent)
                end if

                if stat.is_symlink(dest_path)
                    ops.remove_file(dest_path)
                elif stat.exists(dest_path)
                    ops.remove_file(dest_path)
                end if

                if not res.is_ok(ops.copy_file_preserve(src_path, dest_path))
                    return false
                end if

                perm.chmod(dest_path, mode)
                perm.chown(dest_path, uid, gid)

                let manifest_sha = mtree.entry_sha256(entry)
                if str.length(manifest_sha) > 0
                    let installed_sha = checksum.sha256_file(dest_path)
                    if not str.equals(installed_sha, manifest_sha)
                        return false
                    end if
                end if
            end if

        elif str.equals(etype, "link")
            let link_target = mtree.entry_link(entry)

            if stat.is_symlink(dest_path) or stat.exists(dest_path)
                ops.remove_file(dest_path)
            end if

            let parent = path.dirname(dest_path)
            if str.length(parent) > 0 and not dir.dir_exists(parent)
                dir.create_dir_all(parent)
            end if

            if not res.is_ok(link.symlink(link_target, dest_path))
                return false
            end if
        end if

        i = i + 1
    end while

    return true
end install_files_upgrade

// Parse a TOML inline array string like ["foo", "bar"] into a string array
fn parse_toml_array(value: string, result: [string], max_items: int): int
    let len = str.length(value)
    if len < 2
        return 0
    end if

    if value[0] != '['
        if len > 0
            result[0] = value
            return 1
        end if
        return 0
    end if

    mut pos = 1
    mut count = 0

    while pos < len and count < max_items
        while pos < len and (value[pos] == ' ' or value[pos] == '\t' or value[pos] == '\n')
            pos = pos + 1
        end while

        if pos >= len or value[pos] == ']'
            break
        end if

        if value[pos] == '"'
            pos = pos + 1
            mut item_start = pos
            while pos < len and value[pos] != '"'
                pos = pos + 1
            end while
            if pos > item_start
                result[count] = str.substring(value, item_start, pos - item_start)
                count = count + 1
            end if
            pos = pos + 1
        elif value[pos] != ']' and value[pos] != ','
            mut item_start = pos
            while pos < len and value[pos] != ',' and value[pos] != ']' and value[pos] != ' '
                pos = pos + 1
            end while
            if pos > item_start
                result[count] = str.substring(value, item_start, pos - item_start)
                count = count + 1
            end if
        end if

        while pos < len and (value[pos] == ',' or value[pos] == ' ' or value[pos] == '\t' or value[pos] == '\n')
            pos = pos + 1
        end while
    end while

    return count
end parse_toml_array

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: pkgdb.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: MsgPack-based package database for fast lookups

    The package database provides fast indexed access to:
    - Installed packages (packages.db)
    - File ownership (files.db)

    Source of truth remains in /var/lib/coral/installed/<pkg>/pkg.toml
    These indexes can be rebuilt with 'coral db rebuild'

    Index files are stored as Base64-encoded MsgPack data for compatibility
    with Reef's string-based file I/O.

******************************************************************************/

module core.pkgdb

import types
import io.file
import io.dir
import io.path
import core.str
import core.database
import encoding.msgpack
import encoding.base64
import core.result as res

export
    // Package index entry (for packages.db)
    type PkgIndexEntry

    // Initialize/ensure db directory exists
    fn init_db(): bool

    // Check if indexes exist and are valid
    fn indexes_exist(): bool

    // Get package count from index (fast)
    fn get_package_count(): int

    // List all packages from index (fast)
    fn list_packages(names: [string], versions: [string], max_count: int): int

    // Check if package is in index
    fn is_indexed(name: string): bool

    // Get package info from index
    fn get_indexed_package(name: string): PkgIndexEntry

    // Find file owner from index (fast)
    fn find_file_owner(file_path: string): string

    // Update index when package is installed
    fn index_add_package(name: string, version: string, release: int, description: string): bool

    // Update index when package is removed
    fn index_remove_package(name: string): bool

    // Add files to file index
    fn index_add_files(pkg_name: string, files: [string], file_count: int): bool

    // Remove files from file index
    fn index_remove_files(pkg_name: string): bool

    // Rebuild all indexes from installed packages (source of truth)
    fn rebuild_indexes(): bool

    // Get index statistics
    fn get_index_stats(): IndexStats

    // Root-aware versions for alternate root
    fn init_db_rooted(root: string): bool
    fn indexes_exist_rooted(root: string): bool
    fn rebuild_indexes_rooted(root: string): bool
    fn get_index_stats_rooted(root: string): IndexStats
    fn find_file_owner_rooted(file_path: string, root: string): string

    // Debug: dump files index contents
    fn dump_files_index_rooted(root: string, paths: [string], owners: [string], max_count: int): int

    type IndexStats
end export

// ============================================================================
// Types
// ============================================================================

type PkgIndexEntry = struct
    name: string
    version: string
    release: int
    description: string
    installed_date: string
    file_count: int
    found: bool
end PkgIndexEntry

type IndexStats = struct
    package_count: int
    file_count: int
    packages_db_size: int
    files_db_size: int
    last_updated: string
end IndexStats

// Loaded packages index (deserialized from packages.db)
type PackagesIndex = struct
    version: int
    generated: string
    package_count: int
    entries: [PkgIndexEntry]
    loaded: bool
end PackagesIndex

// Loaded files index (deserialized from files.db)
// Uses parallel arrays for binary search capability
type FilesIndex = struct
    version: int
    generated: string
    file_count: int
    file_paths: [string]    // Sorted alphabetically for binary search
    owners: [string]        // Package name at same index as file_paths
    loaded: bool
end FilesIndex

// ============================================================================
// Constants
// ============================================================================

const INDEX_VERSION: int = 1
const MAX_PACKAGES: int = 2048
const MAX_FILES: int = 131072  // 128K files max

// ============================================================================
// Path Constants
// ============================================================================

fn db_dir(): string
    return types.get_index_dir()
end db_dir

fn packages_db_path(): string
    return types.get_index_dir() + "/packages.db"
end packages_db_path

fn files_db_path(): string
    return types.get_index_dir() + "/files.db"
end files_db_path

// ============================================================================
// Buffer Size Estimation Helpers
// ============================================================================

// Estimate buffer size needed for packages.db
fn estimate_packages_buffer_size(pkg_count: int): int
    // Header overhead: ~100 bytes
    // Per package: ~200 bytes (name, version, description, dates)
    return 100 + (pkg_count * 200)
end estimate_packages_buffer_size

// Estimate buffer size needed for files.db
fn estimate_files_buffer_size(file_count: int): int
    // Header overhead: ~100 bytes
    // Per file: ~100 bytes (path + package name)
    return 100 + (file_count * 100)
end estimate_files_buffer_size

// Get current timestamp as string
fn get_timestamp(): string
    // Simple timestamp - just use a placeholder for now
    // In production would use sys.time module
    return "2026-01-29"
end get_timestamp

// ============================================================================
// Empty/Default Constructors
// ============================================================================

fn empty_packages_index(): PackagesIndex
    return PackagesIndex{
        version: 0,
        generated: "",
        package_count: 0,
        entries: new [PkgIndexEntry](MAX_PACKAGES),
        loaded: false
    }
end empty_packages_index

fn empty_files_index(): FilesIndex
    return FilesIndex{
        version: 0,
        generated: "",
        file_count: 0,
        file_paths: new [string](MAX_FILES),
        owners: new [string](MAX_FILES),
        loaded: false
    }
end empty_files_index

fn empty_pkg_entry(): PkgIndexEntry
    return PkgIndexEntry{
        name: "",
        version: "",
        release: 0,
        description: "",
        installed_date: "",
        file_count: 0,
        found: false
    }
end empty_pkg_entry

// Get just the header size for a map (not the entire map contents)
fn map_header_size(buf: [int], offset: int): int
    let b = buf[offset] & 255
    // Fixmap (0x80-0x8F): 1 byte header
    if (b & 0xF0) == 0x80
        return 1
    // map16 (0xDE): 3 byte header
    elif b == 0xDE
        return 3
    // map32 (0xDF): 5 byte header
    elif b == 0xDF
        return 5
    end if
    return 1  // Default
end map_header_size

// Get just the header size for an array (not the entire array contents)
fn array_header_size(buf: [int], offset: int): int
    let b = buf[offset] & 255
    // Fixarray (0x90-0x9F): 1 byte header
    if (b & 0xF0) == 0x90
        return 1
    // array16 (0xDC): 3 byte header
    elif b == 0xDC
        return 3
    // array32 (0xDD): 5 byte header
    elif b == 0xDD
        return 5
    end if
    return 1  // Default
end array_header_size

// ============================================================================
// MsgPack Deserialization
// ============================================================================

// Load packages index from disk
fn load_packages_index_rooted(root: string): PackagesIndex
    mut index = empty_packages_index()

    // Check if file exists
    let db_path = packages_db_path_rooted(root)
    if not file.fileExists(db_path)
        return index
    end if

    // Read base64-encoded content
    let encoded = res.unwrap_or(file.readFile(db_path), "")
    if str.length(encoded) == 0
        return index
    end if

    // Decode base64 to buffer
    let buf_size = str.length(encoded)  // Decoded will be smaller
    mut buf: [int] = new [int](buf_size)
    let buf_len = res.unwrap_or(base64.base64_decode_bytes(encoded, buf, buf_size), 0)

    if buf_len == 0
        return index
    end if

    // Parse MsgPack structure
    mut offset = 0

    // Expect map header
    if not msgpack.msgpack_is_map(buf, offset)
        return index
    end if

    let map_len = res.unwrap_or(msgpack.msgpack_unpack_map_len(buf, offset), 0)
    offset = offset + map_header_size(buf, offset)

    // Iterate through map entries
    mut entry_idx = 0
    while entry_idx < map_len and offset < buf_len
        // Get key
        let key = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
        offset = offset + msgpack.msgpack_value_size(buf, offset)

        if str.equals(key, "version")
            index.version = res.unwrap_or(msgpack.msgpack_unpack_int(buf, offset), 0)
            offset = offset + msgpack.msgpack_value_size(buf, offset)
        elif str.equals(key, "generated")
            index.generated = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
            offset = offset + msgpack.msgpack_value_size(buf, offset)
        elif str.equals(key, "package_count")
            index.package_count = res.unwrap_or(msgpack.msgpack_unpack_int(buf, offset), 0)
            offset = offset + msgpack.msgpack_value_size(buf, offset)
        elif str.equals(key, "packages")
            // Parse packages array
            let arr_len = res.unwrap_or(msgpack.msgpack_unpack_array_len(buf, offset), 0)
            offset = offset + array_header_size(buf, offset)

            mut pkg_idx = 0
            while pkg_idx < arr_len and pkg_idx < MAX_PACKAGES and offset < buf_len
                // Each package is a map
                let pkg_map_len = res.unwrap_or(msgpack.msgpack_unpack_map_len(buf, offset), 0)
                offset = offset + map_header_size(buf, offset)

                mut entry = empty_pkg_entry()
                entry.found = true

                mut pkg_field = 0
                while pkg_field < pkg_map_len and offset < buf_len
                    let field_key = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
                    offset = offset + msgpack.msgpack_value_size(buf, offset)

                    if str.equals(field_key, "name")
                        entry.name = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
                    elif str.equals(field_key, "version")
                        entry.version = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
                    elif str.equals(field_key, "release")
                        entry.release = res.unwrap_or(msgpack.msgpack_unpack_int(buf, offset), 0)
                    elif str.equals(field_key, "description")
                        entry.description = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
                    elif str.equals(field_key, "installed_date")
                        entry.installed_date = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
                    elif str.equals(field_key, "file_count")
                        entry.file_count = res.unwrap_or(msgpack.msgpack_unpack_int(buf, offset), 0)
                    end if
                    offset = offset + msgpack.msgpack_value_size(buf, offset)

                    pkg_field = pkg_field + 1
                end while

                index.entries[pkg_idx] = entry
                pkg_idx = pkg_idx + 1
            end while
        else
            // Skip unknown key's value
            offset = offset + msgpack.msgpack_value_size(buf, offset)
        end if

        entry_idx = entry_idx + 1
    end while

    index.loaded = true
    return index
end load_packages_index_rooted

// Load files index from disk
fn load_files_index_rooted(root: string): FilesIndex
    mut index = empty_files_index()

    // Check if file exists
    let db_path = files_db_path_rooted(root)
    if not file.fileExists(db_path)
        return index
    end if

    // Read base64-encoded content
    let encoded = res.unwrap_or(file.readFile(db_path), "")
    let encoded_len = str.length(encoded)
    if encoded_len == 0
        return index
    end if

    // Decode base64 to buffer
    let buf_size = encoded_len  // Decoded will be smaller
    mut buf: [int] = new [int](buf_size)
    let buf_len = res.unwrap_or(base64.base64_decode_bytes(encoded, buf, buf_size), 0)

    if buf_len <= 0
        return index
    end if

    // Parse MsgPack structure
    mut offset = 0

    // Expect map header
    if not msgpack.msgpack_is_map(buf, offset)
        return index
    end if

    let map_len = res.unwrap_or(msgpack.msgpack_unpack_map_len(buf, offset), 0)
    offset = offset + map_header_size(buf, offset)

    // Iterate through map entries
    mut entry_idx = 0
    while entry_idx < map_len and offset < buf_len
        // Get key
        let key = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
        offset = offset + msgpack.msgpack_value_size(buf, offset)

        if str.equals(key, "version")
            index.version = res.unwrap_or(msgpack.msgpack_unpack_int(buf, offset), 0)
            offset = offset + msgpack.msgpack_value_size(buf, offset)
        elif str.equals(key, "generated")
            index.generated = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
            offset = offset + msgpack.msgpack_value_size(buf, offset)
        elif str.equals(key, "file_count")
            index.file_count = res.unwrap_or(msgpack.msgpack_unpack_int(buf, offset), 0)
            offset = offset + msgpack.msgpack_value_size(buf, offset)
        elif str.equals(key, "files")
            // Parse files map
            let files_map_len = res.unwrap_or(msgpack.msgpack_unpack_map_len(buf, offset), 0)
            offset = offset + map_header_size(buf, offset)

            mut file_idx = 0
            while file_idx < files_map_len and file_idx < MAX_FILES and offset < buf_len
                // Key is file path, value is owner
                let file_path = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
                offset = offset + msgpack.msgpack_value_size(buf, offset)

                let owner = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
                offset = offset + msgpack.msgpack_value_size(buf, offset)

                index.file_paths[file_idx] = file_path
                index.owners[file_idx] = owner
                file_idx = file_idx + 1
            end while

            index.file_count = file_idx
        else
            // Skip unknown key's value
            offset = offset + msgpack.msgpack_value_size(buf, offset)
        end if

        entry_idx = entry_idx + 1
    end while

    index.loaded = true
    return index
end load_files_index_rooted

// Binary search for file owner in sorted files index
// Returns package name or empty string if not found
fn binary_search_file_owner(index: FilesIndex, path: string): string
    if not index.loaded or index.file_count == 0
        return ""
    end if

    mut low = 0
    mut high = index.file_count - 1

    while low <= high
        let mid = (low + high) / 2
        let cmp = str.compare(path, index.file_paths[mid])

        if cmp == 0
            return index.owners[mid]
        elif cmp < 0
            high = mid - 1
        else
            low = mid + 1
        end if
    end while

    return ""  // Not found
end binary_search_file_owner

// Normalize file path for lookup (strip leading /)
fn normalize_path(path: string): string
    let len = str.length(path)
    if len > 0 and path[0] == '/'
        return str.substring(path, 1, len - 1)
    end if
    return path
end normalize_path

// Linear search fallback for file owner (when binary search fails)
fn linear_search_file_owner(index: FilesIndex, path: string): string
    if not index.loaded or index.file_count == 0
        return ""
    end if

    mut i = 0
    while i < index.file_count
        if str.equals(path, index.file_paths[i])
            return index.owners[i]
        end if
        i = i + 1
    end while

    return ""
end linear_search_file_owner

// ============================================================================
// Initialization
// ============================================================================

fn init_db(): bool
    let db = db_dir()
    if not dir.dir_exists(db)
        return res.is_ok(dir.create_dir_all(db))
    end if
    return true
end init_db

fn indexes_exist(): bool
    return file.fileExists(packages_db_path()) and file.fileExists(files_db_path())
end indexes_exist

// ============================================================================
// Package Index Operations - Uses MsgPack index with fallback
// ============================================================================

fn get_package_count(): int
    // Try index first
    let index = load_packages_index_rooted("")
    if index.loaded
        return index.package_count
    end if

    // Fall back to database scan
    mut names: [string] = new [string](1024)
    return database.list_installed(names, 1024)
end get_package_count

fn list_packages(names: [string], versions: [string], max_count: int): int
    // Try index first
    let index = load_packages_index_rooted("")
    if index.loaded
        mut count = 0
        while count < index.package_count and count < max_count
            names[count] = index.entries[count].name
            versions[count] = index.entries[count].version
            count = count + 1
        end while
        return count
    end if

    // Fall back to database scan
    let count = database.list_installed(names, max_count)

    // Fill in versions
    mut i = 0
    while i < count
        let pkg = database.get_installed(names[i])
        versions[i] = pkg.info.version
        i = i + 1
    end while

    return count
end list_packages

fn is_indexed(name: string): bool
    // Try index first
    let index = load_packages_index_rooted("")
    if index.loaded
        mut i = 0
        while i < index.package_count
            if str.equals(index.entries[i].name, name)
                return true
            end if
            i = i + 1
        end while
        return false
    end if

    // Fall back to database check
    return database.is_installed(name)
end is_indexed

fn get_indexed_package(name: string): PkgIndexEntry
    // Try index first
    let index = load_packages_index_rooted("")
    if index.loaded
        mut i = 0
        while i < index.package_count
            if str.equals(index.entries[i].name, name)
                return index.entries[i]
            end if
            i = i + 1
        end while
        return empty_pkg_entry()
    end if

    // Fall back to database
    mut entry = empty_pkg_entry()

    if not database.is_installed(name)
        return entry
    end if

    let pkg = database.get_installed(name)
    entry.name = pkg.info.name
    entry.version = pkg.info.version
    entry.release = pkg.info.release
    entry.description = pkg.info.description
    entry.installed_date = pkg.install_date
    entry.file_count = pkg.files_count
    entry.found = true

    return entry
end get_indexed_package

// ============================================================================
// File Index Operations - Uses MsgPack index with fallback
// ============================================================================

fn find_file_owner(file_path: string): string
    return find_file_owner_rooted(file_path, "")
end find_file_owner

fn find_file_owner_rooted(file_path: string, root: string): string
    // Try index first (O(log N) binary search)
    let index = load_files_index_rooted(root)
    if index.loaded
        let normalized = normalize_path(file_path)
        let owner = binary_search_file_owner(index, normalized)
        if str.length(owner) > 0
            return owner
        end if
        // Binary search failed - try linear search as fallback
        // This helps diagnose if the index isn't sorted correctly
        let linear_owner = linear_search_file_owner(index, normalized)
        if str.length(linear_owner) > 0
            return linear_owner
        end if
        // File not in index - either not owned or index out of date
        return ""
    end if

    // Fall back to database scan (O(N*M))
    if str.length(root) > 0
        return database.find_owner_rooted(file_path, root)
    end if
    return database.find_owner(file_path)
end find_file_owner_rooted

// ============================================================================
// Index Modification (stub - no-op for now)
// ============================================================================

fn index_add_package(name: string, version: string, release: int, description: string): bool
    // Stub - no indexing yet
    return true
end index_add_package

fn index_remove_package(name: string): bool
    // Stub - no indexing yet
    return true
end index_remove_package

fn index_add_files(pkg_name: string, files: [string], file_count: int): bool
    // Stub - no indexing yet
    return true
end index_add_files

fn index_remove_files(pkg_name: string): bool
    // Stub - triggers full rebuild
    return true
end index_remove_files

// ============================================================================
// MsgPack Serialization
// ============================================================================

// Serialize packages index to MsgPack format
// Returns buffer and sets length via out parameter simulation (length stored at buf[0])
fn serialize_packages_db_rooted(root: string, buf: [int], max_size: int): int
    // Get list of installed packages
    mut names: [string] = new [string](MAX_PACKAGES)
    let pkg_count = database.list_installed_rooted(names, MAX_PACKAGES, root)

    mut pos = 0

    // Pack map header (4 keys: version, generated, package_count, packages)
    pos = pos + msgpack.msgpack_pack_map_header(4, buf, pos)

    // Pack "version" -> INDEX_VERSION
    pos = pos + msgpack.msgpack_pack_string("version", buf, pos)
    pos = pos + msgpack.msgpack_pack_int(INDEX_VERSION, buf, pos)

    // Pack "generated" -> timestamp
    pos = pos + msgpack.msgpack_pack_string("generated", buf, pos)
    pos = pos + msgpack.msgpack_pack_string(get_timestamp(), buf, pos)

    // Pack "package_count" -> count
    pos = pos + msgpack.msgpack_pack_string("package_count", buf, pos)
    pos = pos + msgpack.msgpack_pack_int(pkg_count, buf, pos)

    // Pack "packages" -> array of package entries
    pos = pos + msgpack.msgpack_pack_string("packages", buf, pos)
    pos = pos + msgpack.msgpack_pack_array_header(pkg_count, buf, pos)

    // Pack each package entry
    mut i = 0
    while i < pkg_count and pos < max_size - 1000
        let pkg = database.get_installed_rooted(names[i], root)

        // Each package is a map with 6 keys
        pos = pos + msgpack.msgpack_pack_map_header(6, buf, pos)

        // name
        pos = pos + msgpack.msgpack_pack_string("name", buf, pos)
        pos = pos + msgpack.msgpack_pack_string(pkg.info.name, buf, pos)

        // version
        pos = pos + msgpack.msgpack_pack_string("version", buf, pos)
        pos = pos + msgpack.msgpack_pack_string(pkg.info.version, buf, pos)

        // release
        pos = pos + msgpack.msgpack_pack_string("release", buf, pos)
        pos = pos + msgpack.msgpack_pack_int(pkg.info.release, buf, pos)

        // description
        pos = pos + msgpack.msgpack_pack_string("description", buf, pos)
        pos = pos + msgpack.msgpack_pack_string(pkg.info.description, buf, pos)

        // installed_date
        pos = pos + msgpack.msgpack_pack_string("installed_date", buf, pos)
        pos = pos + msgpack.msgpack_pack_string(pkg.install_date, buf, pos)

        // file_count
        pos = pos + msgpack.msgpack_pack_string("file_count", buf, pos)
        pos = pos + msgpack.msgpack_pack_int(pkg.files_count, buf, pos)

        i = i + 1
    end while

    return pos
end serialize_packages_db_rooted

// Count total installed files across all packages (cheap — no file content read)
fn count_total_files_rooted(root: string): int
    mut pkg_names: [string] = new [string](MAX_PACKAGES)
    let pkg_count = database.list_installed_rooted(pkg_names, MAX_PACKAGES, root)

    mut total = 0
    mut i = 0
    while i < pkg_count
        mut pkg_files: [string] = new [string](8192)
        let file_count = database.get_files_rooted(pkg_names[i], pkg_files, 8192, root)
        total = total + file_count
        i = i + 1
    end while

    return total
end count_total_files_rooted

// Serialize files index to MsgPack format
// Creates a map of file_path -> package_name for fast ownership lookup
fn serialize_files_db_rooted(root: string, buf: [int], max_size: int, alloc_size: int): int
    // Get all installed packages
    mut pkg_names: [string] = new [string](MAX_PACKAGES)
    let pkg_count = database.list_installed_rooted(pkg_names, MAX_PACKAGES, root)

    // Collect all files with their owners — sized to actual count + margin
    mut all_files: [string] = new [string](alloc_size)
    mut all_owners: [string] = new [string](alloc_size)
    mut total_files = 0

    mut i = 0
    while i < pkg_count and total_files < alloc_size - 256
        mut pkg_files: [string] = new [string](8192)
        let file_count = database.get_files_rooted(pkg_names[i], pkg_files, 8192, root)

        mut j = 0
        while j < file_count and total_files < alloc_size
            all_files[total_files] = pkg_files[j]
            all_owners[total_files] = pkg_names[i]
            total_files = total_files + 1
            j = j + 1
        end while

        i = i + 1
    end while

    // Sort files alphabetically for binary search (simple bubble sort for now)
    sort_file_index(all_files, all_owners, total_files)

    mut pos = 0

    // Pack map header (4 keys: version, generated, file_count, files)
    pos = pos + msgpack.msgpack_pack_map_header(4, buf, pos)

    // Pack "version" -> INDEX_VERSION
    pos = pos + msgpack.msgpack_pack_string("version", buf, pos)
    pos = pos + msgpack.msgpack_pack_int(INDEX_VERSION, buf, pos)

    // Pack "generated" -> timestamp
    pos = pos + msgpack.msgpack_pack_string("generated", buf, pos)
    pos = pos + msgpack.msgpack_pack_string(get_timestamp(), buf, pos)

    // Pack "file_count" -> count
    pos = pos + msgpack.msgpack_pack_string("file_count", buf, pos)
    pos = pos + msgpack.msgpack_pack_int(total_files, buf, pos)

    // Pack "files" -> map of path -> owner
    pos = pos + msgpack.msgpack_pack_string("files", buf, pos)
    pos = pos + msgpack.msgpack_pack_map_header(total_files, buf, pos)

    // Pack each file -> owner pair
    i = 0
    while i < total_files and pos < max_size - 500
        pos = pos + msgpack.msgpack_pack_string(all_files[i], buf, pos)
        pos = pos + msgpack.msgpack_pack_string(all_owners[i], buf, pos)
        i = i + 1
    end while

    return pos
end serialize_files_db_rooted

// Sort parallel arrays of files and owners alphabetically by file path
// Uses merge sort for O(n log n) performance on large file counts
proc sort_file_index(files: [string], owners: [string], count: int)
    if count <= 1
        return
    end if

    // Allocate temporary arrays for merge operations
    mut tmp_files: [string] = new [string](count)
    mut tmp_owners: [string] = new [string](count)

    merge_sort(files, owners, tmp_files, tmp_owners, 0, count - 1)
end sort_file_index

proc merge_sort(files: [string], owners: [string], tmp_files: [string], tmp_owners: [string], left: int, right: int)
    if left >= right
        return
    end if

    let mid = left + (right - left) / 2
    merge_sort(files, owners, tmp_files, tmp_owners, left, mid)
    merge_sort(files, owners, tmp_files, tmp_owners, mid + 1, right)
    merge(files, owners, tmp_files, tmp_owners, left, mid, right)
end merge_sort

proc merge(files: [string], owners: [string], tmp_files: [string], tmp_owners: [string], left: int, mid: int, right: int)
    // Copy both halves into temp arrays
    mut i = left
    while i <= right
        tmp_files[i] = files[i]
        tmp_owners[i] = owners[i]
        i = i + 1
    end while

    // Merge back from temp into original
    mut l = left
    mut r = mid + 1
    mut k = left

    while l <= mid and r <= right
        if str.compare(tmp_files[l], tmp_files[r]) <= 0
            files[k] = tmp_files[l]
            owners[k] = tmp_owners[l]
            l = l + 1
        else
            files[k] = tmp_files[r]
            owners[k] = tmp_owners[r]
            r = r + 1
        end if
        k = k + 1
    end while

    // Copy remaining left half
    while l <= mid
        files[k] = tmp_files[l]
        owners[k] = tmp_owners[l]
        l = l + 1
        k = k + 1
    end while

    // Right half remaining elements are already in place
end merge

// ============================================================================
// Index Rebuild
// ============================================================================

fn rebuild_indexes(): bool
    return rebuild_indexes_rooted("")
end rebuild_indexes

// ============================================================================
// Index Statistics
// ============================================================================

fn get_index_stats(): IndexStats
    mut stats = IndexStats{
        package_count: 0,
        file_count: 0,
        packages_db_size: 0,
        files_db_size: 0,
        last_updated: ""
    }

    // Get package count from source of truth
    mut names: [string] = new [string](1024)
    stats.package_count = database.list_installed(names, 1024)

    // Count files across all packages
    mut i = 0
    while i < stats.package_count
        mut files: [string] = new [string](4096)
        let file_count = database.get_files(names[i], files, 4096)
        stats.file_count = stats.file_count + file_count
        i = i + 1
    end while

    return stats
end get_index_stats

// ============================================================================
// Root-aware versions for alternate root
// ============================================================================

fn db_dir_rooted(root: string): string
    if str.length(root) == 0
        return types.get_index_dir()
    end if
    return root + types.get_index_dir()
end db_dir_rooted

fn packages_db_path_rooted(root: string): string
    return db_dir_rooted(root) + "/packages.db"
end packages_db_path_rooted

fn files_db_path_rooted(root: string): string
    return db_dir_rooted(root) + "/files.db"
end files_db_path_rooted

fn init_db_rooted(root: string): bool
    let db = db_dir_rooted(root)
    if not dir.dir_exists(db)
        return res.is_ok(dir.create_dir_all(db))
    end if
    return true
end init_db_rooted

fn indexes_exist_rooted(root: string): bool
    return file.fileExists(packages_db_path_rooted(root)) and file.fileExists(files_db_path_rooted(root))
end indexes_exist_rooted

fn rebuild_indexes_rooted(root: string): bool
    if not init_db_rooted(root)
        return false
    end if

    // Serialize packages.db
    let pkg_buf_size = estimate_packages_buffer_size(MAX_PACKAGES)
    mut pkg_buf: [int] = new [int](pkg_buf_size)
    let pkg_len = serialize_packages_db_rooted(root, pkg_buf, pkg_buf_size)

    if pkg_len > 0
        // Encode to base64 and write
        let pkg_encoded = base64.base64_encode_bytes(pkg_buf, pkg_len)
        if not res.is_ok(file.writeFile(packages_db_path_rooted(root), pkg_encoded))
            return false
        end if
    end if

    // Serialize files.db — count actual files first to avoid massive over-allocation
    let actual_file_count = count_total_files_rooted(root)
    let alloc_size = actual_file_count + 1024
    let files_buf_size = estimate_files_buffer_size(alloc_size)
    mut files_buf: [int] = new [int](files_buf_size)
    let files_len = serialize_files_db_rooted(root, files_buf, files_buf_size, alloc_size)

    if files_len > 0
        // Encode to base64 and write
        let files_encoded = base64.base64_encode_bytes(files_buf, files_len)
        if not res.is_ok(file.writeFile(files_db_path_rooted(root), files_encoded))
            return false
        end if
    end if

    return true
end rebuild_indexes_rooted

fn get_index_stats_rooted(root: string): IndexStats
    mut stats = IndexStats{
        package_count: 0,
        file_count: 0,
        packages_db_size: 0,
        files_db_size: 0,
        last_updated: ""
    }

    // Get package count from source of truth in alternate root
    mut names: [string] = new [string](1024)
    stats.package_count = database.list_installed_rooted(names, 1024, root)

    // Count files across all packages
    mut i = 0
    while i < stats.package_count
        mut files: [string] = new [string](4096)
        let file_count = database.get_files_rooted(names[i], files, 4096, root)
        stats.file_count = stats.file_count + file_count
        i = i + 1
    end while

    return stats
end get_index_stats_rooted

// Debug: dump files index contents to arrays
fn dump_files_index_rooted(root: string, paths: [string], owners: [string], max_count: int): int
    let index = load_files_index_rooted(root)
    if not index.loaded
        return 0
    end if

    mut count = 0
    while count < index.file_count and count < max_count
        paths[count] = index.file_paths[count]
        owners[count] = index.owners[count]
        count = count + 1
    end while

    return count
end dump_files_index_rooted

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: port.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Port loading and parsing from package.toml

******************************************************************************/

module core.port

import types
import io.file
import io.dir
import io.path
import core.str
import core.config
import encoding.toml
import core.result as res

export
    // Load a port from a directory path, returns PortResult
    fn load(port_path: string): types.PortResult

    // Find a port by name, searches all categories
    fn find(name: string): types.PortResult

    // List all ports in a category
    fn list_category(category: string, names: [string], max_count: int): int

    // Get all categories
    fn get_categories(cats: [string], max_count: int): int
end export

// Dynamically discover categories by scanning the ports directory
// Excludes hidden dirs, infrastructure dirs (pkgs/, groups/), and config-aware paths
fn get_categories(cats: [string], max_count: int): int
    let cfg = config.load()
    let ports_dir = config.get_ports_dir(cfg)

    if not dir.dir_exists(ports_dir)
        return 0
    end if

    let packages_path = config.get_packages_dir(cfg)
    let sources_path = config.get_sources_dir(cfg)
    let build_path = config.get_build_dir(cfg)

    // Extract first path component relative to ports_dir for each configured path
    let skip1 = get_relative_top_dir(ports_dir, packages_path)
    let skip2 = get_relative_top_dir(ports_dir, sources_path)
    let skip3 = get_relative_top_dir(ports_dir, build_path)

    // Also skip the groups directory
    let groups_dir = types.get_groups_dir()
    let skip_groups = get_relative_top_dir(ports_dir, groups_dir)

    let entries = res.unwrap_or(dir.list_dir(ports_dir), new [string](0))
    let entry_count = entries.length()

    mut count = 0
    mut i = 0
    while i < entry_count and count < max_count
        let entry = entries[i]
        let elen = str.length(entry)

        // Skip hidden directories
        if elen == 0 or entry[0] == '.'
            i = i + 1
            continue
        end if

        // Skip infrastructure directories
        if str.equals(entry, skip1) or str.equals(entry, skip2) or str.equals(entry, skip3) or str.equals(entry, skip_groups)
            i = i + 1
            continue
        end if

        // Verify it's actually a directory
        let entry_path = path.join_path(ports_dir, entry)
        if dir.dir_exists(entry_path)
            cats[count] = entry
            count = count + 1
        end if

        i = i + 1
    end while

    return count
end get_categories

// Extract the first path component of `child` relative to `parent`
// e.g. parent="/usr/zports", child="/usr/zports/pkgs/packages" -> "pkgs"
// Returns empty string if child is not under parent
fn get_relative_top_dir(parent: string, child: string): string
    let parent_len = str.length(parent)
    let child_len = str.length(child)

    if child_len <= parent_len
        return ""
    end if

    // Check that child starts with parent
    let prefix = str.substring(child, 0, parent_len)
    if not str.equals(prefix, parent)
        return ""
    end if

    // Skip the separator
    mut start = parent_len
    if child[start] == '/'
        start = start + 1
    end if

    // Find the next slash or end of string
    mut end_pos = start
    while end_pos < child_len
        if child[end_pos] == '/'
            break
        end if
        end_pos = end_pos + 1
    end while

    if end_pos > start
        return str.substring(child, start, end_pos - start)
    end if

    return ""
end get_relative_top_dir

// Parse a TOML array value like ["item1", "item2"] into a string array
// Returns the number of items parsed
fn parse_toml_array(value: string, result: [string], max_items: int): int
    let len = str.length(value)
    if len < 2
        return 0
    end if

    // Check for array brackets
    if value[0] != '['
        // Single value, not an array
        if len > 0
            result[0] = value
            return 1
        end if
        return 0
    end if

    // Skip the opening bracket
    mut pos = 1
    mut count = 0

    while pos < len and count < max_items
        // Skip whitespace
        while pos < len and (value[pos] == ' ' or value[pos] == '\t' or value[pos] == '\n')
            pos = pos + 1
        end while

        if pos >= len or value[pos] == ']'
            break
        end if

        // Check for quoted string
        if value[pos] == '"'
            pos = pos + 1
            mut item_start = pos
            // Find closing quote
            while pos < len and value[pos] != '"'
                pos = pos + 1
            end while
            if pos > item_start
                result[count] = str.substring(value, item_start, pos - item_start)
                count = count + 1
            end if
            pos = pos + 1  // Skip closing quote
        elif value[pos] != ']' and value[pos] != ','
            // Unquoted value
            mut item_start = pos
            while pos < len and value[pos] != ',' and value[pos] != ']' and value[pos] != ' '
                pos = pos + 1
            end while
            if pos > item_start
                result[count] = str.substring(value, item_start, pos - item_start)
                count = count + 1
            end if
        end if

        // Skip comma and whitespace
        while pos < len and (value[pos] == ',' or value[pos] == ' ' or value[pos] == '\t' or value[pos] == '\n')
            pos = pos + 1
        end while
    end while

    return count
end parse_toml_array

// Create an empty/default Port structure (delegate to types module)
fn new_port(): types.Port
    return types.new_port()
end new_port

// Helper to create error result
fn error_result(msg: string): types.PortResult
    return types.new_port_result(false, new_port(), msg)
end error_result

// Helper to create success result
fn success_result(p: types.Port): types.PortResult
    return types.new_port_result(true, p, "")
end success_result

// Extract filename from URL
fn extract_filename_from_url(url: string): string
    let len = str.length(url)
    if len == 0
        return ""
    end if

    // Find last slash
    mut last_slash = -1
    mut i = len - 1
    while i >= 0
        if url[i] == '/'
            last_slash = i
            break
        end if
        i = i - 1
    end while

    if last_slash < 0
        return url
    end if

    let filename = str.substring(url, last_slash + 1, len - last_slash - 1)

    // Remove query string if present
    let query_len = str.length(filename)
    mut query_pos = -1
    i = 0
    while i < query_len
        if filename[i] == '?'
            query_pos = i
            break
        end if
        i = i + 1
    end while

    if query_pos > 0
        return str.substring(filename, 0, query_pos)
    end if

    return filename
end extract_filename_from_url

// Parse sources from TOML - supports both new [[source]] and legacy [sources] format
fn parse_sources(keys: [string], vals: [string], entry_count: int): types.SourceInfo
    mut info = types.new_source_info()

    // Try new [[source]] format first (source.0.file, source.1.file, etc.)
    mut source_idx = 0
    mut found_new_format = false

    while source_idx < 16
        let prefix = "source." + int_to_str(source_idx)
        let file_key = prefix + ".file"

        if not toml.toml_has_key(keys, vals, entry_count, file_key)
            break
        end if

        found_new_format = true

        mut src = types.new_source()

        // Get file name
        src.file = toml.toml_get(keys, vals, entry_count, file_key)

        // Get URLs array
        let urls_key = prefix + ".urls"
        if toml.toml_has_key(keys, vals, entry_count, urls_key)
            let urls_val = toml.toml_get(keys, vals, entry_count, urls_key)
            mut urls_arr: [string] = new [string](16)
            let urls_count = parse_toml_array(urls_val, urls_arr, 16)
            src.urls = urls_arr
            src.url_count = urls_count
        end if

        // Get checksum (single value)
        let checksum_key = prefix + ".checksum"
        if toml.toml_has_key(keys, vals, entry_count, checksum_key)
            src.checksum = toml.toml_get(keys, vals, entry_count, checksum_key)
        end if

        // Get extract flag (default: true)
        let extract_key = prefix + ".extract"
        if toml.toml_has_key(keys, vals, entry_count, extract_key)
            src.extract = toml.toml_get_bool(keys, vals, entry_count, extract_key)
        end if

        info.sources[source_idx] = src
        source_idx = source_idx + 1
    end while

    if found_new_format
        info.count = source_idx
        return info
    end if

    // Fall back to legacy [sources] format
    if toml.toml_has_key(keys, vals, entry_count, "sources.urls")
        let urls_val = toml.toml_get(keys, vals, entry_count, "sources.urls")
        mut urls_arr: [string] = new [string](16)
        let urls_count = parse_toml_array(urls_val, urls_arr, 16)

        // Parse checksums
        mut checksums_arr: [string] = new [string](16)
        if toml.toml_has_key(keys, vals, entry_count, "sources.checksums")
            let cksum_val = toml.toml_get(keys, vals, entry_count, "sources.checksums")
            parse_toml_array(cksum_val, checksums_arr, 16)
        end if

        // Convert legacy format to new Source structs
        mut i = 0
        while i < urls_count
            mut src = types.new_source()
            src.file = extract_filename_from_url(urls_arr[i])
            src.urls[0] = urls_arr[i]
            src.url_count = 1
            if str.length(checksums_arr[i]) > 0
                src.checksum = checksums_arr[i]
            end if
            src.extract = true
            info.sources[i] = src
            i = i + 1
        end while
        info.count = urls_count
    end if

    return info
end parse_sources

// Helper: convert int to string (for source index keys)
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut result = ""
    mut value = n
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    return result
end int_to_str

// Load a port from a directory containing package.toml
fn load(port_path: string): types.PortResult
    // Check if directory exists
    if not dir.dir_exists(port_path)
        return error_result("Port directory does not exist: " + port_path)
    end if

    // Check for package.toml
    let toml_path = path.join_path(port_path, "package.toml")
    if not file.fileExists(toml_path)
        return error_result("package.toml not found in: " + port_path)
    end if

    // Read the TOML file
    let content = res.unwrap_or(file.readFile(toml_path), "")
    if str.length(content) == 0
        return error_result("Failed to read package.toml or file is empty")
    end if

    // Parse TOML
    let keys = toml.toml_alloc_keys()
    let vals = toml.toml_alloc_values()
    let entry_count = res.unwrap_or(toml.toml_parse(content, keys, vals), 0)

    if entry_count == 0
        return error_result("Failed to parse package.toml")
    end if

    // Build the Port structure
    mut port = new_port()
    port.port_dir = port_path

    // Extract category from path (e.g., /usr/zports/base/vim -> base)
    let parent_dir = path.dirname(port_path)
    port.category = path.basename(parent_dir)

    // Parse [package] section
    port.info.name = toml.toml_get(keys, vals, entry_count, "package.name")
    port.info.version = toml.toml_get(keys, vals, entry_count, "package.version")
    port.info.release = toml.toml_get_int(keys, vals, entry_count, "package.release")
    port.info.description = toml.toml_get(keys, vals, entry_count, "package.description")
    port.info.url = toml.toml_get(keys, vals, entry_count, "package.url")
    port.info.license = toml.toml_get(keys, vals, entry_count, "package.license")
    port.info.maintainer = toml.toml_get(keys, vals, entry_count, "package.maintainer")

    // Architecture (default to x86_64 if not specified)
    let arch_val = toml.toml_get(keys, vals, entry_count, "package.arch")
    if str.length(arch_val) > 0
        port.info.arch = arch_val
    end if

    // Parse alternatives array
    if toml.toml_has_key(keys, vals, entry_count, "package.alternatives")
        let alt_val = toml.toml_get(keys, vals, entry_count, "package.alternatives")
        mut alt_arr: [string] = new [string](32)
        let alt_count = parse_toml_array(alt_val, alt_arr, 32)
        port.info.alternatives = alt_arr
        port.info.alternatives_count = alt_count
    end if

    // Parse conflicts array
    if toml.toml_has_key(keys, vals, entry_count, "package.conflicts")
        let conf_val = toml.toml_get(keys, vals, entry_count, "package.conflicts")
        mut conf_arr: [string] = new [string](32)
        let conf_count = parse_toml_array(conf_val, conf_arr, 32)
        port.info.conflicts = conf_arr
        port.info.conflicts_count = conf_count
    end if

    // Parse [dependencies] section
    if toml.toml_has_key(keys, vals, entry_count, "dependencies.runtime")
        let rt_val = toml.toml_get(keys, vals, entry_count, "dependencies.runtime")
        mut rt_arr: [string] = new [string](64)
        let rt_count = parse_toml_array(rt_val, rt_arr, 64)
        port.deps.runtime = rt_arr
        port.deps.runtime_count = rt_count
    end if

    if toml.toml_has_key(keys, vals, entry_count, "dependencies.build")
        let bd_val = toml.toml_get(keys, vals, entry_count, "dependencies.build")
        mut bd_arr: [string] = new [string](64)
        let bd_count = parse_toml_array(bd_val, bd_arr, 64)
        port.deps.build = bd_arr
        port.deps.build_count = bd_count
    end if

    // Parse sources - try new [[source]] format first, fall back to legacy [sources]
    port.sources = parse_sources(keys, vals, entry_count)

    // Parse [patches] section
    if toml.toml_has_key(keys, vals, entry_count, "patches.files")
        let patch_val = toml.toml_get(keys, vals, entry_count, "patches.files")
        mut patch_arr: [string] = new [string](32)
        let patch_count = parse_toml_array(patch_val, patch_arr, 32)
        port.patches.files = patch_arr
        port.patches.count = patch_count
    end if

    if toml.toml_has_key(keys, vals, entry_count, "patches.strip")
        port.patches.strip = toml.toml_get_int(keys, vals, entry_count, "patches.strip")
    end if

    // Parse [config] section
    if toml.toml_has_key(keys, vals, entry_count, "config.files")
        let cfg_val = toml.toml_get(keys, vals, entry_count, "config.files")
        mut cfg_arr: [string] = new [string](32)
        let cfg_count = parse_toml_array(cfg_val, cfg_arr, 32)
        port.config.files = cfg_arr
        port.config.count = cfg_count
    end if

    // Parse [scripts] section
    if toml.toml_has_key(keys, vals, entry_count, "scripts.pre_install")
        port.scripts.pre_install = toml.toml_get(keys, vals, entry_count, "scripts.pre_install")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "scripts.post_install")
        port.scripts.post_install = toml.toml_get(keys, vals, entry_count, "scripts.post_install")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "scripts.pre_remove")
        port.scripts.pre_remove = toml.toml_get(keys, vals, entry_count, "scripts.pre_remove")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "scripts.post_remove")
        port.scripts.post_remove = toml.toml_get(keys, vals, entry_count, "scripts.post_remove")
    end if

    // Parse [paths] section (per-package overrides)
    if toml.toml_has_key(keys, vals, entry_count, "paths.prefix")
        port.prefix = toml.toml_get(keys, vals, entry_count, "paths.prefix")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "paths.sysconfdir")
        port.sysconfdir = toml.toml_get(keys, vals, entry_count, "paths.sysconfdir")
    end if

    // Parse [build] section
    if toml.toml_has_key(keys, vals, entry_count, "build.parallel")
        port.build_cfg.parallel = toml.toml_get_bool(keys, vals, entry_count, "build.parallel")
    end if
    if toml.toml_has_key(keys, vals, entry_count, "build.jobs")
        port.build_cfg.jobs = toml.toml_get_int(keys, vals, entry_count, "build.jobs")
    end if

    // Validate required fields
    if str.length(port.info.name) == 0
        return types.new_port_result(false, port, "package.name is required")
    end if

    if str.length(port.info.version) == 0
        return types.new_port_result(false, port, "package.version is required")
    end if

    return success_result(port)
end load

// Find a port by name, searching all categories
// Accepts both "kernel" (searches all categories) and "hammerhead/kernel" (direct category/name)
fn find(name: string): types.PortResult
    let cfg = config.load()
    let ports_dir = config.get_ports_dir(cfg)

    // Check if ports directory exists
    if not dir.dir_exists(ports_dir)
        return error_result("Ports directory not found: " + ports_dir + " (check /etc/coral/coral.conf)")
    end if

    // Check if name contains a slash (category/name format)
    let slash_idx = str.index_of(name, "/")
    if slash_idx >= 0
        let port_path = path.join_path(ports_dir, name)
        if dir.dir_exists(port_path)
            return load(port_path)
        end if
        return error_result("Port not found: " + name + " (searched " + ports_dir + "/" + name + ")")
    end if

    // Search all categories for the name
    mut cats: [string] = new [string](32)
    let cat_count = get_categories(cats, 32)

    mut i = 0
    while i < cat_count
        let port_path = path.join_path(ports_dir, path.join_path(cats[i], name))
        if dir.dir_exists(port_path)
            return load(port_path)
        end if
        i = i + 1
    end while

    return error_result("Port not found: " + name + " (searched " + ports_dir + ")")
end find

// List all ports in a given category
fn list_category(category: string, names: [string], max_count: int): int
    let cfg = config.load()
    let cat_path = path.join_path(config.get_ports_dir(cfg), category)

    if not dir.dir_exists(cat_path)
        return 0
    end if

    let entries = res.unwrap_or(dir.list_dir(cat_path), new [string](0))
    let entry_count = entries.length()

    mut count = 0
    mut i = 0
    while i < entry_count and count < max_count
        let entry = entries[i]
        // Skip hidden files and non-directories
        if str.length(entry) > 0 and entry[0] != '.'
            let entry_path = path.join_path(cat_path, entry)
            // Check if it's a valid port (has package.toml)
            let toml_path = path.join_path(entry_path, "package.toml")
            if file.fileExists(toml_path)
                names[count] = entry
                count = count + 1
            end if
        end if
        i = i + 1
    end while

    return count
end list_category

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: portindex.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Ports index for fast port lookups

    The ports index provides fast indexed access to port metadata
    without parsing individual package.toml files from disk.

    Index file: /var/lib/coral/db/ports.db
    Format: Base64-encoded MsgPack (same as packages.db, files.db)

    Rebuild triggers: coral sync, coral db rebuild, coral db init
    Manual: coral ports cache rebuild

******************************************************************************/

module core.portindex

import types
import io.file
import io.dir
import io.path
import core.str
import core.port
import core.config
import encoding.msgpack
import encoding.base64
import core.result as res

export
    type PortIndexEntry
    type PortsIndex

    // Rebuild the ports index from the ports tree
    fn rebuild_port_index(): bool

    // Check if ports.db exists
    fn port_index_exists(): bool

    // Load the ports index from disk
    fn load_port_index(): PortsIndex

    // Find a single port by name or category/name
    fn find_port(name: string): PortIndexEntry

    // Search ports by substring match on name + description
    fn search_ports(term: string, results: [PortIndexEntry], max_count: int): int

    // List all indexed ports
    fn list_all_ports(entries: [PortIndexEntry], max_count: int): int

    // Get count of indexed ports
    fn get_port_count(): int

    // Find ports that depend on a given package name
    fn find_reverse_deps(name: string, results: [PortIndexEntry], max_count: int): int
end export

// ============================================================================
// Types
// ============================================================================

type PortIndexEntry = struct
    name: string
    category: string
    version: string
    release: int
    description: string
    port_dir: string
    runtime_deps: [string]
    runtime_dep_count: int
    found: bool
end PortIndexEntry

type PortsIndex = struct
    version: int
    generated: string
    port_count: int
    entries: [PortIndexEntry]
    loaded: bool
end PortsIndex

// ============================================================================
// Constants
// ============================================================================

const PORT_INDEX_VERSION: int = 1
const MAX_PORTS: int = 4096

// ============================================================================
// Path helpers
// ============================================================================

fn ports_db_path(): string
    return types.get_index_dir() + "/ports.db"
end ports_db_path

// Get current timestamp as string
fn get_timestamp(): string
    return "2026-02-19"
end get_timestamp

// ============================================================================
// Empty constructors
// ============================================================================

fn empty_port_index(): PortsIndex
    return PortsIndex{
        version: 0,
        generated: "",
        port_count: 0,
        entries: new [PortIndexEntry](MAX_PORTS),
        loaded: false
    }
end empty_port_index

fn empty_port_entry(): PortIndexEntry
    return PortIndexEntry{
        name: "",
        category: "",
        version: "",
        release: 0,
        description: "",
        port_dir: "",
        runtime_deps: new [string](64),
        runtime_dep_count: 0,
        found: false
    }
end empty_port_entry

// ============================================================================
// Buffer size estimation
// ============================================================================

fn estimate_buffer_size(port_count: int): int
    // Header: ~100 bytes
    // Per port: ~300 bytes (name, category, version, description, port_dir, deps)
    return 100 + (port_count * 300)
end estimate_buffer_size

// ============================================================================
// MsgPack header size helpers (same as pkgdb.reef)
// ============================================================================

fn map_header_size(buf: [int], offset: int): int
    let b = buf[offset] & 255
    if (b & 0xF0) == 0x80
        return 1
    elif b == 0xDE
        return 3
    elif b == 0xDF
        return 5
    end if
    return 1
end map_header_size

fn array_header_size(buf: [int], offset: int): int
    let b = buf[offset] & 255
    if (b & 0xF0) == 0x90
        return 1
    elif b == 0xDC
        return 3
    elif b == 0xDD
        return 5
    end if
    return 1
end array_header_size

// ============================================================================
// Index existence check
// ============================================================================

fn port_index_exists(): bool
    return file.fileExists(ports_db_path())
end port_index_exists

// ============================================================================
// Rebuild: scan all ports, serialize to ports.db
// ============================================================================

fn rebuild_port_index(): bool
    // Ensure db directory exists
    let db_dir = types.get_index_dir()
    if not dir.dir_exists(db_dir)
        dir.create_dir_all(db_dir)
    end if

    // Get all categories dynamically
    mut cats: [string] = new [string](32)
    let cat_count = port.get_categories(cats, 32)

    // Collect all port entries
    mut entries: [PortIndexEntry] = new [PortIndexEntry](MAX_PORTS)
    mut total = 0

    mut i = 0
    while i < cat_count and total < MAX_PORTS
        let category = cats[i]
        mut port_names: [string] = new [string](256)
        let port_count = port.list_category(category, port_names, 256)

        mut j = 0
        while j < port_count and total < MAX_PORTS
            let result = port.load(get_port_path(category, port_names[j]))
            if result.success
                let p = result.port
                mut entry = empty_port_entry()
                entry.name = p.info.name
                entry.category = p.category
                entry.version = p.info.version
                entry.release = p.info.release
                entry.description = p.info.description
                entry.port_dir = p.port_dir
                entry.found = true

                // Copy runtime deps
                mut k = 0
                while k < p.deps.runtime_count and k < 64
                    entry.runtime_deps[k] = p.deps.runtime[k]
                    k = k + 1
                end while
                entry.runtime_dep_count = p.deps.runtime_count

                entries[total] = entry
                total = total + 1
            end if
            j = j + 1
        end while

        i = i + 1
    end while

    // Serialize to MsgPack
    let buf_size = estimate_buffer_size(total)
    mut buf: [int] = new [int](buf_size)
    let buf_len = serialize_port_index(entries, total, buf, buf_size)

    if buf_len == 0
        return false
    end if

    // Encode to base64 and write
    let encoded = base64.base64_encode_bytes(buf, buf_len)
    return res.is_ok(file.writeFile(ports_db_path(), encoded))
end rebuild_port_index

// Build a port path from category and name
fn get_port_path(category: string, name: string): string
    let cfg = config.load()
    let ports_dir = config.get_ports_dir(cfg)
    return path.join_path(ports_dir, path.join_path(category, name))
end get_port_path

// ============================================================================
// Serialization
// ============================================================================

fn serialize_port_index(entries: [PortIndexEntry], count: int, buf: [int], max_size: int): int
    mut pos = 0

    // Pack map header (4 keys: version, generated, port_count, ports)
    pos = pos + msgpack.msgpack_pack_map_header(4, buf, pos)

    // version
    pos = pos + msgpack.msgpack_pack_string("version", buf, pos)
    pos = pos + msgpack.msgpack_pack_int(PORT_INDEX_VERSION, buf, pos)

    // generated
    pos = pos + msgpack.msgpack_pack_string("generated", buf, pos)
    pos = pos + msgpack.msgpack_pack_string(get_timestamp(), buf, pos)

    // port_count
    pos = pos + msgpack.msgpack_pack_string("port_count", buf, pos)
    pos = pos + msgpack.msgpack_pack_int(count, buf, pos)

    // ports array
    pos = pos + msgpack.msgpack_pack_string("ports", buf, pos)
    pos = pos + msgpack.msgpack_pack_array_header(count, buf, pos)

    mut i = 0
    while i < count and pos < max_size - 2000
        let entry = entries[i]

        // Each port is a map with 7 keys
        pos = pos + msgpack.msgpack_pack_map_header(7, buf, pos)

        // name
        pos = pos + msgpack.msgpack_pack_string("name", buf, pos)
        pos = pos + msgpack.msgpack_pack_string(entry.name, buf, pos)

        // category
        pos = pos + msgpack.msgpack_pack_string("category", buf, pos)
        pos = pos + msgpack.msgpack_pack_string(entry.category, buf, pos)

        // version
        pos = pos + msgpack.msgpack_pack_string("version", buf, pos)
        pos = pos + msgpack.msgpack_pack_string(entry.version, buf, pos)

        // release
        pos = pos + msgpack.msgpack_pack_string("release", buf, pos)
        pos = pos + msgpack.msgpack_pack_int(entry.release, buf, pos)

        // description
        pos = pos + msgpack.msgpack_pack_string("description", buf, pos)
        pos = pos + msgpack.msgpack_pack_string(entry.description, buf, pos)

        // port_dir
        pos = pos + msgpack.msgpack_pack_string("port_dir", buf, pos)
        pos = pos + msgpack.msgpack_pack_string(entry.port_dir, buf, pos)

        // runtime_deps (array of strings)
        pos = pos + msgpack.msgpack_pack_string("runtime_deps", buf, pos)
        pos = pos + msgpack.msgpack_pack_array_header(entry.runtime_dep_count, buf, pos)

        mut d = 0
        while d < entry.runtime_dep_count
            pos = pos + msgpack.msgpack_pack_string(entry.runtime_deps[d], buf, pos)
            d = d + 1
        end while

        i = i + 1
    end while

    return pos
end serialize_port_index

// ============================================================================
// Deserialization
// ============================================================================

fn load_port_index(): PortsIndex
    mut index = empty_port_index()

    let db_path = ports_db_path()
    if not file.fileExists(db_path)
        return index
    end if

    let encoded = res.unwrap_or(file.readFile(db_path), "")
    if str.length(encoded) == 0
        return index
    end if

    let buf_size = str.length(encoded)
    mut buf: [int] = new [int](buf_size)
    let buf_len = res.unwrap_or(base64.base64_decode_bytes(encoded, buf, buf_size), 0)

    if buf_len == 0
        return index
    end if

    mut offset = 0

    // Expect map header
    if not msgpack.msgpack_is_map(buf, offset)
        return index
    end if

    let map_len = res.unwrap_or(msgpack.msgpack_unpack_map_len(buf, offset), 0)
    offset = offset + map_header_size(buf, offset)

    mut entry_idx = 0
    while entry_idx < map_len and offset < buf_len
        let key = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
        offset = offset + msgpack.msgpack_value_size(buf, offset)

        if str.equals(key, "version")
            index.version = res.unwrap_or(msgpack.msgpack_unpack_int(buf, offset), 0)
            offset = offset + msgpack.msgpack_value_size(buf, offset)
        elif str.equals(key, "generated")
            index.generated = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
            offset = offset + msgpack.msgpack_value_size(buf, offset)
        elif str.equals(key, "port_count")
            index.port_count = res.unwrap_or(msgpack.msgpack_unpack_int(buf, offset), 0)
            offset = offset + msgpack.msgpack_value_size(buf, offset)
        elif str.equals(key, "ports")
            // Parse ports array
            let arr_len = res.unwrap_or(msgpack.msgpack_unpack_array_len(buf, offset), 0)
            offset = offset + array_header_size(buf, offset)

            mut port_idx = 0
            while port_idx < arr_len and port_idx < MAX_PORTS and offset < buf_len
                let port_map_len = res.unwrap_or(msgpack.msgpack_unpack_map_len(buf, offset), 0)
                offset = offset + map_header_size(buf, offset)

                mut entry = empty_port_entry()
                entry.found = true

                mut port_field = 0
                while port_field < port_map_len and offset < buf_len
                    let field_key = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
                    offset = offset + msgpack.msgpack_value_size(buf, offset)

                    if str.equals(field_key, "name")
                        entry.name = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
                        offset = offset + msgpack.msgpack_value_size(buf, offset)
                    elif str.equals(field_key, "category")
                        entry.category = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
                        offset = offset + msgpack.msgpack_value_size(buf, offset)
                    elif str.equals(field_key, "version")
                        entry.version = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
                        offset = offset + msgpack.msgpack_value_size(buf, offset)
                    elif str.equals(field_key, "release")
                        entry.release = res.unwrap_or(msgpack.msgpack_unpack_int(buf, offset), 0)
                        offset = offset + msgpack.msgpack_value_size(buf, offset)
                    elif str.equals(field_key, "description")
                        entry.description = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
                        offset = offset + msgpack.msgpack_value_size(buf, offset)
                    elif str.equals(field_key, "port_dir")
                        entry.port_dir = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
                        offset = offset + msgpack.msgpack_value_size(buf, offset)
                    elif str.equals(field_key, "runtime_deps")
                        // Parse deps array
                        let deps_len = res.unwrap_or(msgpack.msgpack_unpack_array_len(buf, offset), 0)
                        offset = offset + array_header_size(buf, offset)

                        mut dep_idx = 0
                        while dep_idx < deps_len and dep_idx < 64 and offset < buf_len
                            entry.runtime_deps[dep_idx] = res.unwrap_or(msgpack.msgpack_unpack_string(buf, offset), "")
                            offset = offset + msgpack.msgpack_value_size(buf, offset)
                            dep_idx = dep_idx + 1
                        end while
                        entry.runtime_dep_count = dep_idx
                    else
                        offset = offset + msgpack.msgpack_value_size(buf, offset)
                    end if

                    port_field = port_field + 1
                end while

                index.entries[port_idx] = entry
                port_idx = port_idx + 1
            end while
        else
            offset = offset + msgpack.msgpack_value_size(buf, offset)
        end if

        entry_idx = entry_idx + 1
    end while

    index.loaded = true
    return index
end load_port_index

// ============================================================================
// Query functions
// ============================================================================

// Find a single port by name or category/name
fn find_port(name: string): PortIndexEntry
    let index = load_port_index()
    if not index.loaded
        return empty_port_entry()
    end if

    // Check if name contains a slash (category/name format)
    let slash_idx = str.index_of(name, "/")

    mut i = 0
    while i < index.port_count
        let entry = index.entries[i]

        if slash_idx >= 0
            // Match category/name format
            let full_name = entry.category + "/" + entry.name
            // Also check directory-based name (category/dirname)
            let dir_name = path.basename(entry.port_dir)
            let full_dir_name = entry.category + "/" + dir_name
            if str.equals(full_name, name) or str.equals(full_dir_name, name)
                return entry
            end if
        else
            // Match just the name
            if str.equals(entry.name, name)
                return entry
            end if
        end if

        i = i + 1
    end while

    return empty_port_entry()
end find_port

// Search ports by substring match on name + description
fn search_ports(term: string, results: [PortIndexEntry], max_count: int): int
    let index = load_port_index()
    if not index.loaded
        return 0
    end if

    let lower_term = str.to_lower(term)
    mut count = 0

    mut i = 0
    while i < index.port_count and count < max_count
        let entry = index.entries[i]
        let lower_name = str.to_lower(entry.name)
        let lower_desc = str.to_lower(entry.description)

        if str.contains(lower_name, lower_term) or str.contains(lower_desc, lower_term)
            results[count] = entry
            count = count + 1
        end if

        i = i + 1
    end while

    return count
end search_ports

// List all indexed ports
fn list_all_ports(entries: [PortIndexEntry], max_count: int): int
    let index = load_port_index()
    if not index.loaded
        return 0
    end if

    mut count = 0
    while count < index.port_count and count < max_count
        entries[count] = index.entries[count]
        count = count + 1
    end while

    return count
end list_all_ports

// Get count of indexed ports
fn get_port_count(): int
    let index = load_port_index()
    if index.loaded
        return index.port_count
    end if
    return 0
end get_port_count

// Find ports that have `name` in their runtime dependencies
fn find_reverse_deps(name: string, results: [PortIndexEntry], max_count: int): int
    let index = load_port_index()
    if not index.loaded
        return 0
    end if

    mut count = 0

    mut i = 0
    while i < index.port_count and count < max_count
        let entry = index.entries[i]

        mut j = 0
        while j < entry.runtime_dep_count
            if str.equals(entry.runtime_deps[j], name)
                results[count] = entry
                count = count + 1
                break
            end if
            j = j + 1
        end while

        i = i + 1
    end while

    return count
end find_reverse_deps

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: repository.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Repository manifest handling for binary package distribution

******************************************************************************/

module core.repository

import core.str
import io.file
import io.dir
import io.path
import encoding.toml
import util.http as uhttp
import util.color
import types
import core.result as res

export
    type Repository
    type RepoResult
    type RemotePackage
    type RemotePackageResult

    fn load_repo(repo_path: string): RepoResult
    fn list_repos(repos: [Repository], max_count: int): int

    // Remote package operations
    fn refresh_repo(repo: Repository): bool
    fn find_remote_package(name: string): RemotePackageResult
    fn download_package(pkg: RemotePackage): string
    fn get_cached_manifest(repo: Repository): string
end export

// Repository definition
type Repository = struct
    name: string
    url: string
    priority: int
    enabled: bool
    is_signed: bool
    keyid: string
end Repository

// Result type for repository operations
type RepoResult = struct
    success: bool
    repo: Repository
    error: string
end RepoResult

// Remote package from repository manifest
type RemotePackage = struct
    name: string
    version: string
    release: int
    description: string
    license: string
    category: string
    depends: [string]
    depends_count: int
    size: int
    compressed: int
    filename: string
    sha256: string
    signature: string
    repo_name: string
    repo_url: string
end RemotePackage

// Result type for remote package search
type RemotePackageResult = struct
    success: bool
    pkg: RemotePackage
    error: string
end RemotePackageResult

// Create empty repository
fn new_repository(): Repository
    return Repository{ name: "", url: "", priority: 100, enabled: true, is_signed: false, keyid: "" }
end new_repository

// Create empty remote package
fn new_remote_package(): RemotePackage
    return RemotePackage{
        name: "",
        version: "",
        release: 0,
        description: "",
        license: "",
        category: "",
        depends: new [string](64),
        depends_count: 0,
        size: 0,
        compressed: 0,
        filename: "",
        sha256: "",
        signature: "",
        repo_name: "",
        repo_url: ""
    }
end new_remote_package

// Create error result
fn error_result(msg: string): RepoResult
    return RepoResult{ success: false, repo: new_repository(), error: msg }
end error_result

// Create package error result
fn pkg_error_result(msg: string): RemotePackageResult
    return RemotePackageResult{ success: false, pkg: new_remote_package(), error: msg }
end pkg_error_result

// Create package success result
fn pkg_success_result(pkg: RemotePackage): RemotePackageResult
    return RemotePackageResult{ success: true, pkg: pkg, error: "" }
end pkg_success_result

// Load a repository from a .repo file
fn load_repo(repo_path: string): RepoResult
    if not file.fileExists(repo_path)
        return error_result("Repository file not found: " + repo_path)
    end if

    let content = res.unwrap_or(file.readFile(repo_path), "")
    if str.length(content) == 0
        return error_result("Empty repository file: " + repo_path)
    end if

    // Parse TOML
    let keys = toml.toml_alloc_keys()
    let vals = toml.toml_alloc_values()
    let entry_count = res.unwrap_or(toml.toml_parse(content, keys, vals), 0)

    if entry_count == 0
        return error_result("Failed to parse repository file: " + repo_path)
    end if

    mut repo = new_repository()

    // Read repository metadata
    repo.name = toml.toml_get(keys, vals, entry_count, "repository.name")
    repo.url = toml.toml_get(keys, vals, entry_count, "repository.url")

    if toml.toml_has_key(keys, vals, entry_count, "repository.priority")
        repo.priority = toml.toml_get_int(keys, vals, entry_count, "repository.priority")
    end if

    if toml.toml_has_key(keys, vals, entry_count, "repository.enabled")
        repo.enabled = toml.toml_get_bool(keys, vals, entry_count, "repository.enabled")
    end if

    if toml.toml_has_key(keys, vals, entry_count, "repository.signed")
        repo.is_signed = toml.toml_get_bool(keys, vals, entry_count, "repository.signed")
    end if

    if toml.toml_has_key(keys, vals, entry_count, "repository.keyid")
        repo.keyid = toml.toml_get(keys, vals, entry_count, "repository.keyid")
    end if

    return RepoResult{ success: true, repo: repo, error: "" }
end load_repo

// List all configured repositories
fn list_repos(repos: [Repository], max_count: int): int
    let repos_dir = "/etc/coral/repos.d"

    if not dir.dir_exists(repos_dir)
        return 0
    end if

    let entries = res.unwrap_or(dir.list_dir(repos_dir), new [string](0))
    let entry_count = entries.length()

    mut count = 0
    mut i = 0
    while i < entry_count and count < max_count
        let entry = entries[i]

        // Check for .repo extension
        if str.ends_with(entry, ".repo")
            let repo_path = path.join_path(repos_dir, entry)
            let result = load_repo(repo_path)
            if result.success
                repos[count] = result.repo
                count = count + 1
            end if
        end if

        i = i + 1
    end while

    return count
end list_repos

// Get the path to cached manifest for a repository
fn get_cached_manifest(repo: Repository): string
    let cache_dir = "/var/lib/coral/repos"
    return path.join_path(cache_dir, repo.name + ".toml")
end get_cached_manifest

// Refresh repository metadata from remote
fn refresh_repo(repo: Repository): bool
    if not repo.enabled
        return false
    end if

    if str.length(repo.url) == 0
        return false
    end if

    // Build URL to repo.toml
    mut manifest_url = repo.url
    if not str.ends_with(manifest_url, "/")
        manifest_url = manifest_url + "/"
    end if
    manifest_url = manifest_url + "repo.toml"

    // Ensure cache directory exists
    let cache_dir = "/var/lib/coral/repos"
    if not dir.dir_exists(cache_dir)
        if not res.is_ok(dir.create_dir_all(cache_dir))
            return false
        end if
    end if

    // Download manifest
    let cache_path = get_cached_manifest(repo)
    return uhttp.download(manifest_url, cache_path)
end refresh_repo

// Find a package in all enabled repositories
fn find_remote_package(name: string): RemotePackageResult
    // Get list of repositories
    mut repos: [Repository] = new [Repository](16)
    let repo_count = list_repos(repos, 16)

    if repo_count == 0
        return pkg_error_result("No repositories configured")
    end if

    // Search in each repository (by priority)
    // TODO: Sort by priority
    mut i = 0
    while i < repo_count
        let repo = repos[i]

        if not repo.enabled
            i = i + 1
            continue
        end if

        let result = find_package_in_repo(name, repo)
        if result.success
            return result
        end if

        i = i + 1
    end while

    return pkg_error_result("Package not found in any repository: " + name)
end find_remote_package

// Find a package in a specific repository
fn find_package_in_repo(name: string, repo: Repository): RemotePackageResult
    let cache_path = get_cached_manifest(repo)

    // Check if we have cached manifest
    if not file.fileExists(cache_path)
        // Try to refresh
        if not refresh_repo(repo)
            return pkg_error_result("Failed to fetch repository manifest")
        end if
    end if

    // Read cached manifest
    let content = res.unwrap_or(file.readFile(cache_path), "")
    if str.length(content) == 0
        return pkg_error_result("Empty repository manifest")
    end if

    // Parse TOML to find the package
    let keys = toml.toml_alloc_keys()
    let vals = toml.toml_alloc_values()
    let entry_count = res.unwrap_or(toml.toml_parse(content, keys, vals), 0)

    if entry_count == 0
        return pkg_error_result("Failed to parse repository manifest")
    end if

    // Look for package entry: packages.<name>
    let pkg_key = "packages." + name
    if not toml.toml_has_key(keys, vals, entry_count, pkg_key + ".version")
        return pkg_error_result("Package not found: " + name)
    end if

    // Build RemotePackage
    mut pkg = new_remote_package()
    pkg.name = name
    pkg.repo_name = repo.name
    pkg.repo_url = repo.url

    pkg.version = toml.toml_get(keys, vals, entry_count, pkg_key + ".version")
    pkg.release = toml.toml_get_int(keys, vals, entry_count, pkg_key + ".release")
    pkg.description = toml.toml_get(keys, vals, entry_count, pkg_key + ".description")
    pkg.license = toml.toml_get(keys, vals, entry_count, pkg_key + ".license")
    pkg.category = toml.toml_get(keys, vals, entry_count, pkg_key + ".category")
    pkg.filename = toml.toml_get(keys, vals, entry_count, pkg_key + ".file")
    pkg.sha256 = toml.toml_get(keys, vals, entry_count, pkg_key + ".sha256")
    pkg.signature = toml.toml_get(keys, vals, entry_count, pkg_key + ".signature")

    if toml.toml_has_key(keys, vals, entry_count, pkg_key + ".size")
        pkg.size = toml.toml_get_int(keys, vals, entry_count, pkg_key + ".size")
    end if

    if toml.toml_has_key(keys, vals, entry_count, pkg_key + ".compressed")
        pkg.compressed = toml.toml_get_int(keys, vals, entry_count, pkg_key + ".compressed")
    end if

    // Parse depends array if present
    if toml.toml_has_key(keys, vals, entry_count, pkg_key + ".depends")
        let deps_str = toml.toml_get(keys, vals, entry_count, pkg_key + ".depends")
        pkg.depends_count = parse_toml_array(deps_str, pkg.depends, 64)
    end if

    // If filename is empty, construct it
    if str.length(pkg.filename) == 0
        pkg.filename = name + "-" + pkg.version + "-" + int_to_str(pkg.release) + ".x86_64.pkg.tar.xz"
    end if

    return pkg_success_result(pkg)
end find_package_in_repo

// Download a package to local cache
fn download_package(pkg: RemotePackage): string
    if str.length(pkg.filename) == 0
        color.print_error("Package has no filename")
        return ""
    end if

    // Build download URL
    mut base_url = pkg.repo_url
    if not str.ends_with(base_url, "/")
        base_url = base_url + "/"
    end if
    let pkg_url = base_url + "packages/" + pkg.filename

    // Ensure packages cache directory exists
    let cache_dir = types.get_packages_dir()
    if not dir.dir_exists(cache_dir)
        if not res.is_ok(dir.create_dir_all(cache_dir))
            color.print_error("Failed to create packages cache directory")
            return ""
        end if
    end if

    // Download to cache
    let dest_path = path.join_path(cache_dir, pkg.filename)

    // Check if already cached
    if file.fileExists(dest_path)
        color.print_info("Using cached: " + pkg.filename)
        return dest_path
    end if

    // Download
    color.print_info("Downloading: " + pkg.filename)
    if not uhttp.download(pkg_url, dest_path)
        return ""
    end if

    return dest_path
end download_package

// Parse TOML array value into string array
fn parse_toml_array(value: string, result: [string], max_items: int): int
    let len = str.length(value)
    if len < 2
        return 0
    end if

    if value[0] != '['
        return 0
    end if

    mut count = 0
    mut i = 1
    mut in_string = false
    mut item_start = 0

    while i < len and count < max_items
        let c = value[i]

        if c == '"' and not in_string
            in_string = true
            item_start = i + 1
        elif c == '"' and in_string
            let item_len = i - item_start
            if item_len > 0
                result[count] = str.substring(value, item_start, item_len)
                count = count + 1
            end if
            in_string = false
        elif c == ']' and not in_string
            return count
        end if

        i = i + 1
    end while

    return count
end parse_toml_array

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: resolver.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Dependency resolution for package installation

******************************************************************************/

module core.resolver

import core.str
import io.file
import io.path
import types
import core.port
import core.database
import util.version as ver

export
    type ResolveResult

    fn resolve(name: string): ResolveResult
    fn get_install_order(names: [string], name_count: int, result: [string], max_count: int): int
    fn get_dep_tree(name: string, deps: [string], max_count: int): int

    // Build dependency resolver (resolves both runtime + build deps recursively from source)
    fn resolve_build_deps(name: string): ResolveResult

    // Root-aware version for alternate root installation
    fn get_install_order_rooted(names: [string], name_count: int, result: [string], max_count: int, root: string): int
end export

// Result for alternative resolution
type AlternativeChoice = struct
    satisfied: bool       // True if an alternative is already installed
    provider: string      // The installed provider (if satisfied)
    options: [string]     // Available options to choose from
    option_count: int
    base_dep: string      // The base dependency name
end AlternativeChoice

// Resolution result
type ResolveResult = struct
    success: bool
    packages: [string]
    count: int
    error: string
end ResolveResult

// Create an empty result
fn new_result(): ResolveResult
    mut packages: [string] = new [string](256)
    return ResolveResult{ success: false, packages: packages, count: 0, error: "" }
end new_result

// Resolve dependencies for a package
// Returns ordered list of packages to install (dependencies first)
fn resolve(name: string): ResolveResult
    mut result = new_result()

    // Track visited to detect cycles
    mut visited: [string] = new [string](256)
    mut visited_count = 0

    // Track resolution order
    mut order: [string] = new [string](256)
    mut order_count = 0

    // Resolve recursively
    let ok = resolve_recursive(name, visited, visited_count, order, order_count)

    if not ok.success
        result.error = ok.error
        return result
    end if

    result.success = true
    result.packages = ok.packages
    result.count = ok.count
    return result
end resolve

// Internal result for recursive resolution
type RecurseResult = struct
    success: bool
    packages: [string]
    count: int
    error: string
end RecurseResult

fn new_recurse_result(): RecurseResult
    mut packages: [string] = new [string](256)
    return RecurseResult{ success: true, packages: packages, count: 0, error: "" }
end new_recurse_result

fn resolve_recursive(name: string, visited: [string], visited_count: int, order: [string], order_count: int): RecurseResult
    mut result = new_recurse_result()
    result.packages = order
    result.count = order_count

    // Check for cycle
    if array_contains(visited, visited_count, name)
        // Already visited - skip
        result.success = true
        return result
    end if

    // Mark as visited
    visited[visited_count] = name
    let new_visited_count = visited_count + 1

    // Find the port
    let port_result = port.find(name)
    if not port_result.success
        // Check if already installed
        if database.is_installed(name)
            result.success = true
            return result
        end if

        // Check if an alternative provider exists
        let provider = database.find_provider(name)
        if str.length(provider) > 0
            // Alternative already installed
            result.success = true
            return result
        end if

        result.success = false
        result.error = "Port not found: " + name
        return result
    end if

    let p = port_result.port
    let pkg_name = p.info.name

    // Resolve runtime dependencies first
    mut i = 0
    while i < p.deps.runtime_count
        let dep = p.deps.runtime[i]

        // Check if this is an alternative dependency
        if is_alternative_dep(dep)
            let alt_choice = resolve_alternative(dep)

            if alt_choice.satisfied
                // An alternative is already installed, skip
                i = i + 1
                continue
            end if

            // No alternative installed - pick the first option
            // In a full implementation, we'd prompt the user here
            if alt_choice.option_count > 0
                let chosen = alt_choice.options[0]
                if not array_contains(result.packages, result.count, chosen)
                    let dep_result = resolve_recursive(chosen, visited, new_visited_count, result.packages, result.count)
                    if not dep_result.success
                        return dep_result
                    end if
                    result.packages = dep_result.packages
                    result.count = dep_result.count
                end if
            end if
        else
            // Regular dependency — may include version constraint (e.g., "libfoo>=1.0")
            let constraint = ver.parse_dep_constraint(dep)
            let dep_name = ver.constraint_name(constraint)

            if database.is_installed(dep_name)
                // Installed — check version constraint if present
                if ver.has_constraint(constraint)
                    let installed_pkg = database.get_installed(dep_name)
                    if not ver.check_version_constraint(installed_pkg.info.version, ver.constraint_op(constraint), ver.constraint_version(constraint))
                        // Installed version doesn't satisfy constraint — needs upgrade
                        if not array_contains(result.packages, result.count, dep_name)
                            let dep_result = resolve_recursive(dep_name, visited, new_visited_count, result.packages, result.count)
                            if not dep_result.success
                                return dep_result
                            end if
                            result.packages = dep_result.packages
                            result.count = dep_result.count
                        end if
                    end if
                end if
                // No constraint or constraint satisfied — skip
            else
                // Not installed — resolve it
                if not array_contains(result.packages, result.count, dep_name)
                    let dep_result = resolve_recursive(dep_name, visited, new_visited_count, result.packages, result.count)
                    if not dep_result.success
                        return dep_result
                    end if
                    result.packages = dep_result.packages
                    result.count = dep_result.count
                end if
            end if
        end if

        i = i + 1
    end while

    // Add this package to order (after its dependencies)
    // Use canonical name from package.toml, not the raw search argument
    if not array_contains(result.packages, result.count, pkg_name)
        // Skip if already installed
        if not database.is_installed(pkg_name)
            result.packages[result.count] = pkg_name
            result.count = result.count + 1
        end if
    end if

    result.success = true
    return result
end resolve_recursive

// Get install order for multiple packages
fn get_install_order(names: [string], name_count: int, result: [string], max_count: int): int
    mut order_count = 0

    mut i = 0
    while i < name_count
        let name = names[i]
        let resolve_result = resolve(name)

        if resolve_result.success
            // Add resolved packages to result
            mut j = 0
            while j < resolve_result.count and order_count < max_count
                let pkg = resolve_result.packages[j]
                // Avoid duplicates
                if not array_contains(result, order_count, pkg)
                    result[order_count] = pkg
                    order_count = order_count + 1
                end if
                j = j + 1
            end while
        end if

        i = i + 1
    end while

    return order_count
end get_install_order

// Get dependency tree for display (with indentation info)
fn get_dep_tree(name: string, deps: [string], max_count: int): int
    mut count = 0
    collect_deps(name, deps, count, 0, max_count)
    return count
end get_dep_tree

// Collect dependencies recursively
fn collect_deps(name: string, deps: [string], count: int, depth: int, max_count: int): int
    if depth > 20 or count >= max_count
        return count
    end if

    let result = port.find(name)
    if not result.success
        return count
    end if

    let p = result.port
    mut current_count = count

    mut i = 0
    while i < p.deps.runtime_count and current_count < max_count
        let dep = p.deps.runtime[i]

        // Add with depth prefix (number of spaces = depth * 2)
        let indent = make_indent(depth)
        deps[current_count] = indent + dep
        current_count = current_count + 1

        // Recurse
        current_count = collect_deps(dep, deps, current_count, depth + 1, max_count)

        i = i + 1
    end while

    return current_count
end collect_deps

// Create indentation string
fn make_indent(depth: int): string
    if depth == 0
        return ""
    end if

    mut result = ""
    mut i = 0
    while i < depth
        result = result + "  "
        i = i + 1
    end while
    return result
end make_indent

// Check if array contains a string
fn array_contains(arr: [string], count: int, s: string): bool
    mut i = 0
    while i < count
        if arr[i] == s
            return true
        end if
        i = i + 1
    end while
    return false
end array_contains

// Check if a dependency string represents alternatives (format: dep:opt1,opt2,opt3)
fn is_alternative_dep(dep: string): bool
    return str.contains(dep, ":")
end is_alternative_dep

// Parse alternative options from a dependency string
// Format: base_dep:alt1,alt2,alt3
// Returns number of alternatives parsed, fills alternatives array
fn parse_alternatives(dep: string, alternatives: [string], max_count: int): int
    let colon_pos = str.index_of_char(dep, ':')
    if colon_pos < 0
        // Not an alternative, return the single dependency
        alternatives[0] = dep
        return 1
    end if

    // Get the alternatives part after the colon
    let alts_part = str.substring(dep, colon_pos + 1, str.length(dep) - colon_pos - 1)

    // Split by comma
    return str.split(alts_part, ',', alternatives, max_count)
end parse_alternatives

// Get the base dependency name from an alternative string
fn get_base_dep(dep: string): string
    let colon_pos = str.index_of_char(dep, ':')
    if colon_pos < 0
        return dep
    end if
    return str.substring(dep, 0, colon_pos)
end get_base_dep

// Create empty AlternativeChoice
fn new_alternative_choice(): AlternativeChoice
    return AlternativeChoice{
        satisfied: false,
        provider: "",
        options: new [string](16),
        option_count: 0,
        base_dep: ""
    }
end new_alternative_choice

// Resolve an alternative dependency
// Returns satisfied=true if any option is already installed
// Otherwise returns the list of available options
fn resolve_alternative(dep: string): AlternativeChoice
    mut choice = new_alternative_choice()

    if not is_alternative_dep(dep)
        // Regular dependency
        choice.base_dep = dep
        choice.options[0] = dep
        choice.option_count = 1

        // Check if installed
        if database.is_installed(dep)
            choice.satisfied = true
            choice.provider = dep
        end if
        return choice
    end if

    // Parse the alternatives
    choice.base_dep = get_base_dep(dep)
    choice.option_count = parse_alternatives(dep, choice.options, 16)

    // Check if any alternative is already installed
    mut i = 0
    while i < choice.option_count
        let opt = choice.options[i]
        if database.is_installed(opt)
            choice.satisfied = true
            choice.provider = opt
            return choice
        end if
        i = i + 1
    end while

    // Check if any provides this via alternatives
    let provider = database.find_provider(choice.base_dep)
    if str.length(provider) > 0
        choice.satisfied = true
        choice.provider = provider
        return choice
    end if

    return choice
end resolve_alternative

// ============================================================================
// Build dependency resolver (resolves both runtime + build deps from source)
// ============================================================================

// Resolve all dependencies needed to build a package from source.
// Returns topological order: dependencies first, target package last.
// Resolves both runtime and build deps recursively.
// Uses proper cycle detection with separate visited/in_stack arrays.
fn resolve_build_deps(name: string): ResolveResult
    mut result = new_result()

    // Permanent marks: fully resolved packages
    mut visited: [string] = new [string](256)
    mut visited_count = 0

    // Temporary marks: packages on the current DFS stack (for cycle detection)
    mut in_stack: [string] = new [string](256)
    mut stack_count = 0

    // Topological build order
    mut order: [string] = new [string](256)
    mut order_count = 0

    let ok = resolve_build_recursive(name, visited, visited_count, in_stack, stack_count, order, order_count)

    if not ok.success
        result.error = ok.error
        return result
    end if

    result.success = true
    result.packages = ok.packages
    result.count = ok.count
    return result
end resolve_build_deps

fn resolve_build_recursive(name: string, visited: [string], visited_count: int,
                           in_stack: [string], stack_count: int,
                           order: [string], order_count: int): RecurseResult
    mut result = new_recurse_result()
    result.packages = order
    result.count = order_count

    // Permanent mark: already fully resolved, skip
    if array_contains(visited, visited_count, name)
        result.success = true
        return result
    end if

    // Temporary mark: cycle detected
    if array_contains(in_stack, stack_count, name)
        result.success = false
        result.error = "Circular dependency detected: " + name
        return result
    end if

    // If already installed, mark visited and skip (don't need to build)
    if database.is_installed(name)
        visited[visited_count] = name
        result.success = true
        return result
    end if

    // Find the port (must exist to build from source)
    let port_result = port.find(name)
    if not port_result.success
        // Check if a provider is already installed
        let provider = database.find_provider(name)
        if str.length(provider) > 0
            visited[visited_count] = name
            result.success = true
            return result
        end if

        result.success = false
        result.error = "Port not found: " + name
        return result
    end if

    let p = port_result.port
    let pkg_name = p.info.name

    // Push onto DFS stack (temporary mark)
    in_stack[stack_count] = name
    let new_stack_count = stack_count + 1

    // Mark as visited (permanent mark)
    visited[visited_count] = name
    let new_visited_count = visited_count + 1

    // Recurse into RUNTIME deps
    mut i = 0
    while i < p.deps.runtime_count
        let dep = p.deps.runtime[i]

        if is_alternative_dep(dep)
            let alt_choice = resolve_alternative(dep)
            if not alt_choice.satisfied and alt_choice.option_count > 0
                let chosen = alt_choice.options[0]
                let dep_result = resolve_build_recursive(chosen, visited, new_visited_count, in_stack, new_stack_count, result.packages, result.count)
                if not dep_result.success
                    return dep_result
                end if
                result.packages = dep_result.packages
                result.count = dep_result.count
            end if
        else
            let constraint = ver.parse_dep_constraint(dep)
            let dep_name = ver.constraint_name(constraint)

            mut needs_build = false
            if database.is_installed(dep_name)
                // Check version constraint
                if ver.has_constraint(constraint)
                    let installed_pkg = database.get_installed(dep_name)
                    if not ver.check_version_constraint(installed_pkg.info.version, ver.constraint_op(constraint), ver.constraint_version(constraint))
                        needs_build = true
                    end if
                end if
            else
                needs_build = true
            end if

            if needs_build
                let dep_result = resolve_build_recursive(dep_name, visited, new_visited_count, in_stack, new_stack_count, result.packages, result.count)
                if not dep_result.success
                    return dep_result
                end if
                result.packages = dep_result.packages
                result.count = dep_result.count
            end if
        end if

        i = i + 1
    end while

    // Recurse into BUILD deps
    i = 0
    while i < p.deps.build_count
        let dep = p.deps.build[i]

        if is_alternative_dep(dep)
            let alt_choice = resolve_alternative(dep)
            if not alt_choice.satisfied and alt_choice.option_count > 0
                let chosen = alt_choice.options[0]
                let dep_result = resolve_build_recursive(chosen, visited, new_visited_count, in_stack, new_stack_count, result.packages, result.count)
                if not dep_result.success
                    return dep_result
                end if
                result.packages = dep_result.packages
                result.count = dep_result.count
            end if
        else
            let constraint = ver.parse_dep_constraint(dep)
            let dep_name = ver.constraint_name(constraint)

            mut needs_build = false
            if database.is_installed(dep_name)
                if ver.has_constraint(constraint)
                    let installed_pkg = database.get_installed(dep_name)
                    if not ver.check_version_constraint(installed_pkg.info.version, ver.constraint_op(constraint), ver.constraint_version(constraint))
                        needs_build = true
                    end if
                end if
            else
                needs_build = true
            end if

            if needs_build
                let dep_result = resolve_build_recursive(dep_name, visited, new_visited_count, in_stack, new_stack_count, result.packages, result.count)
                if not dep_result.success
                    return dep_result
                end if
                result.packages = dep_result.packages
                result.count = dep_result.count
            end if
        end if

        i = i + 1
    end while

    // Post-order: add this package AFTER all its deps (topological sort)
    if not array_contains(result.packages, result.count, pkg_name)
        result.packages[result.count] = pkg_name
        result.count = result.count + 1
    end if

    result.success = true
    return result
end resolve_build_recursive

// ============================================================================
// Root-aware resolver functions for alternate root installation
// ============================================================================

// Internal result for rooted recursive resolution
type RootedRecurseResult = struct
    success: bool
    packages: [string]
    count: int
    error: string
end RootedRecurseResult

fn new_rooted_recurse_result(): RootedRecurseResult
    mut packages: [string] = new [string](256)
    return RootedRecurseResult{ success: true, packages: packages, count: 0, error: "" }
end new_rooted_recurse_result

// Resolve dependencies checking against a specific root
fn resolve_recursive_rooted(name: string, visited: [string], visited_count: int, order: [string], order_count: int, root: string): RootedRecurseResult
    mut result = new_rooted_recurse_result()
    result.packages = order
    result.count = order_count

    // Check for cycle
    if array_contains(visited, visited_count, name)
        result.success = true
        return result
    end if

    // Mark as visited
    visited[visited_count] = name
    let new_visited_count = visited_count + 1

    // Find the port
    let port_result = port.find(name)
    if not port_result.success
        // Check if already installed in target root
        if database.is_installed_rooted(name, root)
            result.success = true
            return result
        end if

        // Check if an alternative provider exists in target root
        // Note: find_provider doesn't have rooted version yet, skip for now
        result.success = false
        result.error = "Port not found: " + name
        return result
    end if

    let p = port_result.port
    let pkg_name = p.info.name

    // Resolve runtime dependencies first
    mut i = 0
    while i < p.deps.runtime_count
        let dep = p.deps.runtime[i]

        // Skip alternative deps for now (simplification)
        if not is_alternative_dep(dep)
            // Parse version constraint if present
            let constraint = ver.parse_dep_constraint(dep)
            let dep_name = ver.constraint_name(constraint)

            if database.is_installed_rooted(dep_name, root)
                // Check version constraint if present
                if ver.has_constraint(constraint)
                    let installed_pkg = database.get_installed_rooted(dep_name, root)
                    if not ver.check_version_constraint(installed_pkg.info.version, ver.constraint_op(constraint), ver.constraint_version(constraint))
                        // Needs upgrade
                        let dep_result = resolve_recursive_rooted(dep_name, visited, new_visited_count, result.packages, result.count, root)
                        if not dep_result.success
                            return dep_result
                        end if
                        result.packages = dep_result.packages
                        result.count = dep_result.count
                    end if
                end if
            else
                let dep_result = resolve_recursive_rooted(dep_name, visited, new_visited_count, result.packages, result.count, root)
                if not dep_result.success
                    return dep_result
                end if
                result.packages = dep_result.packages
                result.count = dep_result.count
            end if
        end if

        i = i + 1
    end while

    // Add this package to order (after its dependencies)
    // Use canonical name from package.toml, not the raw search argument
    if not array_contains(result.packages, result.count, pkg_name)
        // Skip if already installed in target root
        if not database.is_installed_rooted(pkg_name, root)
            result.packages[result.count] = pkg_name
            result.count = result.count + 1
        end if
    end if

    result.success = true
    return result
end resolve_recursive_rooted

// Resolve for a single package with root support
fn resolve_rooted(name: string, root: string): ResolveResult
    mut result = new_result()

    mut visited: [string] = new [string](256)
    mut visited_count = 0

    mut order: [string] = new [string](256)
    mut order_count = 0

    let ok = resolve_recursive_rooted(name, visited, visited_count, order, order_count, root)

    if not ok.success
        result.error = ok.error
        return result
    end if

    result.success = true
    result.packages = ok.packages
    result.count = ok.count
    return result
end resolve_rooted

// Get install order for multiple packages, checking against target root
fn get_install_order_rooted(names: [string], name_count: int, result: [string], max_count: int, root: string): int
    mut order_count = 0

    mut i = 0
    while i < name_count
        let name = names[i]
        let resolve_result = resolve_rooted(name, root)

        if resolve_result.success
            mut j = 0
            while j < resolve_result.count and order_count < max_count
                let pkg = resolve_result.packages[j]
                if not array_contains(result, order_count, pkg)
                    result[order_count] = pkg
                    order_count = order_count + 1
                end if
                j = j + 1
            end while
        end if

        i = i + 1
    end while

    return order_count
end get_install_order_rooted

end module
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: signing.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Ed25519 signing and verification for packages and repositories

******************************************************************************/

module core.signing

import core.str
import io.file
import io.dir
import io.path
import sys.process
import core.result as res

export
    type KeyPair
    type SignResult
    type VerifyResult

    fn generate_keypair(name: string): SignResult
    fn sign_file(file_path: string, key_path: string): SignResult
    fn verify_file(file_path: string, sig_path: string, key_path: string): VerifyResult
    fn import_key(key_data: string, name: string): SignResult
    fn list_keys(keys: [KeyPair], max_count: int): int
    fn get_keyring_dir(): string
    fn get_trusted_keys_dir(): string

    // High-level verification functions
    fn verify_package(pkg_path: string, sig_path: string): VerifyResult
    fn verify_manifest(manifest_path: string): VerifyResult
    fn is_key_trusted(keyid: string): bool
end export

// Key pair information
type KeyPair = struct
    name: string
    keyid: string
    public_key: string
    private_key: string
    created: string
    trusted: bool
end KeyPair

// Result for signing operations
type SignResult = struct
    success: bool
    signature: string
    error: string
end SignResult

// Result for verification
type VerifyResult = struct
    success: bool
    valid: bool
    keyid: string
    error: string
end VerifyResult

// Get the keyring directory
fn get_keyring_dir(): string
    return "/etc/coral/keys"
end get_keyring_dir

// Create empty keypair
fn new_keypair(): KeyPair
    return KeyPair{ name: "", keyid: "", public_key: "", private_key: "", created: "", trusted: false }
end new_keypair

// Create error result
fn error_sign_result(msg: string): SignResult
    return SignResult{ success: false, signature: "", error: msg }
end error_sign_result

fn error_verify_result(msg: string): VerifyResult
    return VerifyResult{ success: false, valid: false, keyid: "", error: msg }
end error_verify_result

// Generate a new Ed25519 keypair
// Note: This requires an external tool (openssl or signify)
fn generate_keypair(name: string): SignResult
    let keyring = get_keyring_dir()

    // Ensure keyring directory exists
    if not dir.dir_exists(keyring)
        if not res.is_ok(dir.create_dir_all(keyring))
            return error_sign_result("Failed to create keyring directory")
        end if
    end if

    let private_path = path.join_path(keyring, name + ".key")
    let public_path = path.join_path(keyring, name + ".pub")

    // Check if key already exists
    if file.fileExists(private_path)
        return error_sign_result("Key already exists: " + name)
    end if

    // Generate key using openssl
    let cmd = "openssl genpkey -algorithm ed25519 -out \"" + private_path + "\" && " +
              "openssl pkey -in \"" + private_path + "\" -pubout -out \"" + public_path + "\""

    let pid = process.process_spawn_shell(cmd)
    if pid < 0
        return error_sign_result("Failed to start key generation")
    end if

    let exit_code = process.process_wait(pid)
    if exit_code != 0
        return error_sign_result("Key generation failed")
    end if

    return SignResult{ success: true, signature: "", error: "" }
end generate_keypair

// Sign a file with Ed25519
fn sign_file(file_path: string, key_path: string): SignResult
    if not file.fileExists(file_path)
        return error_sign_result("File not found: " + file_path)
    end if

    if not file.fileExists(key_path)
        return error_sign_result("Key not found: " + key_path)
    end if

    let sig_path = file_path + ".sig"

    // Sign using openssl
    let cmd = "openssl pkeyutl -sign -inkey \"" + key_path + "\" -in \"" + file_path + "\" -out \"" + sig_path + "\""

    let pid = process.process_spawn_shell(cmd)
    if pid < 0
        return error_sign_result("Failed to start signing")
    end if

    let exit_code = process.process_wait(pid)
    if exit_code != 0
        return error_sign_result("Signing failed")
    end if

    return SignResult{ success: true, signature: sig_path, error: "" }
end sign_file

// Verify a file signature
fn verify_file(file_path: string, sig_path: string, key_path: string): VerifyResult
    if not file.fileExists(file_path)
        return error_verify_result("File not found: " + file_path)
    end if

    if not file.fileExists(sig_path)
        return error_verify_result("Signature not found: " + sig_path)
    end if

    if not file.fileExists(key_path)
        return error_verify_result("Key not found: " + key_path)
    end if

    // Verify using openssl
    let cmd = "openssl pkeyutl -verify -pubin -inkey \"" + key_path + "\" -in \"" + file_path + "\" -sigfile \"" + sig_path + "\""

    let pid = process.process_spawn_shell(cmd)
    if pid < 0
        return error_verify_result("Failed to start verification")
    end if

    let exit_code = process.process_wait(pid)

    if exit_code == 0
        return VerifyResult{ success: true, valid: true, keyid: "", error: "" }
    else
        return VerifyResult{ success: true, valid: false, keyid: "", error: "Signature verification failed" }
    end if
end verify_file

// Import a public key
fn import_key(key_data: string, name: string): SignResult
    let keyring = get_keyring_dir()

    if not dir.dir_exists(keyring)
        if not res.is_ok(dir.create_dir_all(keyring))
            return error_sign_result("Failed to create keyring directory")
        end if
    end if

    let key_path = path.join_path(keyring, name + ".pub")

    if file.fileExists(key_path)
        return error_sign_result("Key already exists: " + name)
    end if

    if not res.is_ok(file.writeFile(key_path, key_data))
        return error_sign_result("Failed to write key file")
    end if

    return SignResult{ success: true, signature: "", error: "" }
end import_key

// List all keys in keyring
fn list_keys(keys: [KeyPair], max_count: int): int
    let keyring = get_keyring_dir()

    if not dir.dir_exists(keyring)
        return 0
    end if

    let entries = res.unwrap_or(dir.list_dir(keyring), new [string](0))
    let entry_count = entries.length()

    mut count = 0
    mut i = 0
    while i < entry_count and count < max_count
        let entry = entries[i]

        // Look for .pub files
        if str.ends_with(entry, ".pub")
            let name_len = str.length(entry) - 4
            let name = str.substring(entry, 0, name_len)

            mut kp = new_keypair()
            kp.name = name
            kp.trusted = true  // Local keys are trusted

            // Read public key
            let pub_path = path.join_path(keyring, entry)
            kp.public_key = res.unwrap_or(file.readFile(pub_path), "")

            // Check for private key
            let priv_path = path.join_path(keyring, name + ".key")
            if file.fileExists(priv_path)
                kp.private_key = "(present)"
            end if

            keys[count] = kp
            count = count + 1
        end if

        i = i + 1
    end while

    return count
end list_keys

// Get the trusted keys directory
fn get_trusted_keys_dir(): string
    return "/var/lib/coral/trusted-keys"
end get_trusted_keys_dir

// Check if a key is in the trusted keys list
fn is_key_trusted(keyid: string): bool
    let trusted_dir = get_trusted_keys_dir()

    if not dir.dir_exists(trusted_dir)
        return false
    end if

    // Look for key file by keyid
    let key_path = path.join_path(trusted_dir, keyid + ".pub")
    if file.fileExists(key_path)
        return true
    end if

    // Also check the main keyring
    let keyring_path = path.join_path(get_keyring_dir(), keyid + ".pub")
    return file.fileExists(keyring_path)
end is_key_trusted

// Get path to a trusted key by keyid
fn get_trusted_key_path(keyid: string): string
    // Try trusted-keys directory first
    let trusted_dir = get_trusted_keys_dir()
    let trusted_path = path.join_path(trusted_dir, keyid + ".pub")
    if file.fileExists(trusted_path)
        return trusted_path
    end if

    // Fall back to main keyring
    let keyring_path = path.join_path(get_keyring_dir(), keyid + ".pub")
    if file.fileExists(keyring_path)
        return keyring_path
    end if

    return ""
end get_trusted_key_path

// Verify a package with any trusted key
fn verify_package(pkg_path: string, sig_path: string): VerifyResult
    if not file.fileExists(pkg_path)
        return error_verify_result("Package not found: " + pkg_path)
    end if

    if not file.fileExists(sig_path)
        return error_verify_result("Signature not found: " + sig_path)
    end if

    // Try to verify with each trusted key
    let trusted_dir = get_trusted_keys_dir()
    let keyring_dir = get_keyring_dir()

    // Collect all public keys from both directories
    mut all_keys: [string] = new [string](64)
    mut key_count = 0

    // Get keys from trusted-keys directory
    if dir.dir_exists(trusted_dir)
        let entries = res.unwrap_or(dir.list_dir(trusted_dir), new [string](0))
        let entry_count = entries.length()

        mut i = 0
        while i < entry_count and key_count < 64
            if str.ends_with(entries[i], ".pub")
                all_keys[key_count] = path.join_path(trusted_dir, entries[i])
                key_count = key_count + 1
            end if
            i = i + 1
        end while
    end if

    // Get keys from keyring directory
    if dir.dir_exists(keyring_dir)
        let entries = res.unwrap_or(dir.list_dir(keyring_dir), new [string](0))
        let entry_count = entries.length()

        mut i = 0
        while i < entry_count and key_count < 64
            if str.ends_with(entries[i], ".pub")
                let key_path = path.join_path(keyring_dir, entries[i])
                // Avoid duplicates
                mut is_dup = false
                mut j = 0
                while j < key_count
                    if str.equals(all_keys[j], key_path)
                        is_dup = true
                    end if
                    j = j + 1
                end while
                if not is_dup
                    all_keys[key_count] = key_path
                    key_count = key_count + 1
                end if
            end if
            i = i + 1
        end while
    end if

    if key_count == 0
        return error_verify_result("No trusted keys found")
    end if

    // Try each key
    mut i = 0
    while i < key_count
        let key_path = all_keys[i]
        let result = verify_file(pkg_path, sig_path, key_path)

        if result.success and result.valid
            // Extract keyid from path
            let filename = path.basename(key_path)
            let keyid = str.substring(filename, 0, str.length(filename) - 4)
            return VerifyResult{ success: true, valid: true, keyid: keyid, error: "" }
        end if

        i = i + 1
    end while

    return VerifyResult{ success: true, valid: false, keyid: "", error: "Signature does not match any trusted key" }
end verify_package

// Verify a repository manifest (repo.toml and repo.toml.sig)
fn verify_manifest(manifest_path: string): VerifyResult
    if not file.fileExists(manifest_path)
        return error_verify_result("Manifest not found: " + manifest_path)
    end if

    let sig_path = manifest_path + ".sig"
    if not file.fileExists(sig_path)
        return error_verify_result("Manifest signature not found: " + sig_path)
    end if

    return verify_package(manifest_path, sig_path)
end verify_manifest

end module