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
{-# LANGUAGE QuasiQuotes #-}

module Redacted where

import AppT
import Arg
import Bencode
import Builder
import Comparison
import Conduit (ConduitT)
import Conduit qualified as Cond
import Control.Monad.Logger.CallStack
import Control.Monad.Reader
import Control.Monad.Trans.Resource (resourceForkWith)
import Data.Aeson qualified as Json
import Data.Aeson.BetterErrors qualified as Json
import Data.Aeson.Key qualified as Key
import Data.Aeson.KeyMap qualified as KeyMap
import Data.BEncode (BEncode)
import Data.Conduit ((.|))
import Data.Error.Tree
import Data.IntSet (IntSet)
import Data.IntSet qualified as IntSet
import Data.List qualified as List
import Data.List.NonEmpty qualified as NonEmpty
import Data.Map.Strict qualified as Map
import Data.Maybe (catMaybes)
import Data.Text qualified as Text
import Data.Text.IO qualified as Text.IO
import Data.Time (NominalDiffTime, UTCTime, addUTCTime, getCurrentTime)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import Database.PostgreSQL.Simple (Binary (Binary), Only (..))
import Database.PostgreSQL.Simple qualified as Postgres
import Database.PostgreSQL.Simple.Types (PGArray (PGArray))
import FieldParser (FieldParser)
import FieldParser qualified as Field
import Http qualified
import Json qualified
import Json.Enc qualified as Enc
import Label
import MyLabel
import MyPrelude
import Network.HTTP.Types
import Network.HTTP.Types qualified as Http
import Network.Wai qualified as Wai
import Network.Wai.Handler.Warp qualified as Warp
import Network.Wai.Parse qualified as Wai
import OpenTelemetry.Context.ThreadLocal qualified as Otel
import OpenTelemetry.Trace qualified as Otel hiding (getTracer, inSpan, inSpan')
import Optional
import Parse (Parse, mapLookup, mapLookupMay, runParse)
import Parse qualified
import Postgres.Decoder qualified as Dec
import Postgres.MonadPostgres
import Pretty
import RevList (RevList)
import RevList qualified
import RunCommand (prettyArgsForBash)
import System.FilePath ((</>))
import System.FilePath qualified as File
import System.Process.Typed (proc, readProcessStdout)
import Tool
import Transmission (getTransmissionDownloads)
import UnliftIO (MonadUnliftIO (..), askRunInIO, async, newQSem, withQSem)
import UnliftIO.Async (Async)
import UnliftIO.Async qualified as Async
import UnliftIO.Concurrent (threadDelay)
import Prelude hiding (length, span)

getRedactedApiKey :: App ByteString
getRedactedApiKey = AppT (asks (.redactedApiKey))

data FreeleechStatus = NoTokensRemaining | FreeleechPossible
  deriving stock (Eq, Show)

redactedSearch ::
  ( HasField "actionArgs" extraArguments [(ByteString, ByteString)],
    HasField "page" dat (Maybe Natural)
  ) =>
  extraArguments ->
  dat ->
  Json.Parse ErrorTree a ->
  App a
redactedSearch extraArguments dat parser =
  inSpan' "Redacted API Search" $ \span ->
    redactedPagedRequest
      span
      ( t3
          #action
          "browse"
          #actionArgs
          extraArguments.actionArgs
          #page
          dat.page
      )
      parser

redactedGetArtist ::
  ( HasField "artistId" r Int,
    HasField "page" r (Maybe Natural)
  ) =>
  r ->
  Json.Parse ErrorTree a ->
  App a
redactedGetArtist dat parser =
  inSpan' "Redacted Get Artist" $ \span -> do
    redactedPagedRequest
      span
      ( t3
          #action
          "artist"
          #actionArgs
          [("id", buildBytes intDecimalB dat.artistId)]
          #page
          (dat.page)
      )
      parser

redactedPagedRequest ::
  ( HasField "action" dat ByteString,
    HasField "actionArgs" dat [(ByteString, ByteString)],
    HasField "page" dat (Maybe Natural)
  ) =>
  Otel.Span ->
  dat ->
  Json.Parse ErrorTree a ->
  App a
redactedPagedRequest span dat parser =
  redactedApiRequestJson
    span
    ( t2
        #action
        dat.action
        #actionArgs
        ( (dat.actionArgs <&> second Just)
            <> ( dat.page
                   & ifExists
                     (\page -> ("page", Just $ buildBytes naturalDecimalB page))
               )
        )
    )
    parser

redactedGetTorrentFile ::
  ( HasField "torrentId" dat Int,
    HasField "freelechTokensExhaustedAt" dat (Maybe UTCTime)
  ) =>
  dat ->
  App (T2 "freelechStatus" FreeleechStatus "torrentFile" ByteString)
redactedGetTorrentFile dat = inSpan' "Redacted Get Torrent File" $ \span -> do
  let mkRequest req = do
        let reqName = req.reqName
        let useTokens = req.useTokens
        let actionArgs =
              [ ("id", Just (buildBytes intDecimalB dat.torrentId))
              ]
                <> (if useTokens then [("usetoken", Just "1")] else [])
        let reqDat =
              ( T2
                  (label @"action" "download")
                  ( label @"actionArgs" $ actionArgs
                  )
              )
        addAttribute span reqName (toOtelJsonAttr reqDat)
        mkRedactedApiRequest reqDat

  -- Check if we should test freeleech tokens again (if exhausted > 24 hours ago)
  now <- liftIO getCurrentTime
  shouldTestFreeleech <- case dat.freelechTokensExhaustedAt of
    Nothing -> pure True -- No exhaustion recorded: use freeleech tokens
    Just exhaustedAt -> do
      let dayAgo = addUTCTime (-86400) now -- 24 hours ago
      if exhaustedAt < dayAgo
        then do
          addEventSimple span "Testing freeleech tokens (24+ hours since exhaustion)"
          pure True -- Test freeleech regardless of user setting
        else do
          pure False -- Skip freeleech, too recent

  -- First attempt with freeleech if should test or user requested
  req <- mkRequest (t2 #reqName "redacted.request" #useTokens shouldTestFreeleech)
  result <- httpTorrent req
  case result of
    Right torrentFile ->
      pure $
        T2
          (label @"freelechStatus" FreeleechPossible)
          (label @"torrentFile" torrentFile)
    Left err -> case err of
      (E21 _tokensExhausted) -> do
        -- Log that we're retrying due to token exhaustion
        addEventSimple span "Freeleech tokens exhausted, retrying without tokens"
        -- Retry without tokens
        reqWithoutTokens <- mkRequest (t2 #reqName "redacted.request.retry" #useTokens False)
        retryResult <- httpTorrent reqWithoutTokens
        case retryResult of
          Right torrentFile -> do
            pure $
              T2
                (label @"freelechStatus" NoTokensRemaining)
                (label @"torrentFile" torrentFile)
          Left (E22 otherErr) -> do
            appThrow span otherErr.otherError
          Left (E21 _shouldNotHappen) -> do
            appThrow span [fmt|Unexpected token exhaustion error on retry without tokens|]
      (E22 otherError) -> appThrow span otherError.otherError

mkRedactedTorrentLink :: Arg "torrentGroupId" Int -> Text
mkRedactedTorrentLink torrentId = [fmt|https://redacted.sh/torrents.php?id={torrentId.unArg}|]

exampleSearch :: AppTransaction ()
exampleSearch = do
  _x1 <-
    redactedSearchAndInsert
      (lbl #maxPages 0)
      [ ("searchstr", "cherish"),
        ("artistname", "kirinji"),
        -- ("year", "1982"),
        -- ("format", "MP3"),
        -- ("releasetype", "album"),
        ("order_by", "year")
      ]
  _x3 <-
    redactedSearchAndInsert
      (lbl #maxPages 0)
      [ ("searchstr", "mouss et hakim"),
        ("artistname", "mouss et hakim"),
        -- ("year", "1982"),
        -- ("format", "MP3"),
        -- ("releasetype", "album"),
        ("order_by", "year")
      ]
  _x2 <-
    redactedSearchAndInsert
      (lbl #maxPages 0)
      [ ("searchstr", "thriller"),
        ("artistname", "michael jackson"),
        -- ("year", "1982"),
        -- ("format", "MP3"),
        -- ("releasetype", "album"),
        ("order_by", "year")
      ]
  pure ()

redactedRefreshArtist ::
  (HasField "artistId" dat Int) =>
  dat ->
  AppTransaction (Label "newTorrents" [Label "torrentId" Int])
redactedRefreshArtist dat = do
  redactedPagedSearchAndInsert
    (lbl #maxPages 0)
    ( Json.key "torrentgroup" $
        parseTourGroups
          ( t2
              #torrentFieldName
              "torrent"
              #torrentIdName
              "id"
          )
    )
    ( \page ->
        redactedGetArtist
          ( T2
              (getLabel @"artistId" dat)
              page
          )
    )

-- | Do the search, return a transaction that inserts all results from all pages of the search.
redactedSearchAndInsert ::
  (HasField "maxPages" opts Natural) =>
  opts ->
  [(ByteString, ByteString)] ->
  AppTransaction (Label "newTorrents" [Label "torrentId" Int])
redactedSearchAndInsert opts extraArguments =
  redactedPagedSearchAndInsert
    opts
    (Json.key "results" $ parseTourGroups (T2 (label @"torrentFieldName" "torrents") (label @"torrentIdName" "torrentId")))
    ( redactedSearch
        (label @"actionArgs" extraArguments)
    )

-- | Parse the standard Redacted reply object, @{ status: "success", response: ... }@ or throw an error.
--
-- The response might contain a `pages` field, if not we’ll return 1.
parseRedactedReplyStatus ::
  (Monad m) =>
  Json.ParseT ErrorTree m b ->
  Json.ParseT ErrorTree m (T2 "pages" Natural "response" b)
parseRedactedReplyStatus inner = do
  status <- Json.key "status" Json.asText
  when (status /= "success") $ do
    Json.throwCustomError ([fmt|Status was not "success", but {status}|] :: ErrorTree)
  Json.key "response" $ do
    pages <-
      Json.keyMay
        "pages"
        ( Field.toJsonParser
            ( Field.mapError singleError $
                Field.jsonNumber >>> Field.boundedScientificIntegral @Int "not an Integer" >>> Field.integralToNatural
            )
        )
        -- in case the field is missing, let’s assume there is only one page
        <&> fromMaybe 1
    res <- inner
    pure $
      T2
        (label @"pages" pages)
        (label @"response" res)

type TourGroups =
  ( Label
      "tourGroups"
      [ T2
          "tourGroup"
          TourGroup
          "torrents"
          [T2 "torrentId" Int "fullJsonResult" Json.Value]
      ]
  )

data TourGroup = TourGroup
  { groupId :: Int,
    groupName :: Text,
    fullJsonResult :: Json.Value,
    -- | Needed for sm0rt request recursion
    groupArtists :: [Label "artistId" Int]
  }

parseTourGroups ::
  ( Monad m,
    HasField "torrentFieldName" opts Text,
    HasField "torrentIdName" opts Text
  ) =>
  opts ->
  Json.ParseT err m TourGroups
parseTourGroups opts =
  do
    label @"tourGroups"
    <$> ( catMaybes
            <$> ( Json.eachInArray $ do
                    Json.keyMay opts.torrentFieldName (pure ()) >>= \case
                      -- not a torrent group, maybe some files or something (e.g. guitar tabs see Dream Theater Systematic Chaos)
                      Nothing -> pure Nothing
                      Just () -> do
                        groupId <- Json.key "groupId" (Json.asIntegral @_ @Int)
                        groupName <- Json.key "groupName" Json.asText
                        groupArtists <-
                          Json.keyMayMempty "artists" $
                            Json.eachInArray $
                              lbl #artistId <$> Json.key "id" (Json.asIntegral @_ @Int)
                        fullJsonResult <-
                          Json.asObject
                            -- remove torrents cause they are inserted separately below
                            <&> KeyMap.filterWithKey (\k _ -> k /= (opts.torrentFieldName & Key.fromText))
                            <&> Json.Object
                        let tourGroup = TourGroup {..}
                        torrents <- Json.keyLabel @"torrents" opts.torrentFieldName $
                          Json.eachInArray $ do
                            torrentId <- Json.keyLabel @"torrentId" opts.torrentIdName (Json.asIntegral @_ @Int)
                            fullJsonResultT <-
                              label @"fullJsonResult"
                                <$> ( Json.asObject
                                        <&> KeyMap.mapKeyVal
                                          ( \k ->
                                              if
                                                -- some torrent objects use “snatched” instead of “snatches”
                                                | k == "snatched" -> "snatches"
                                                -- normalize the torrent id field
                                                | k == (opts.torrentIdName & Key.fromText) -> "torrentId"
                                                | otherwise -> k
                                          )
                                          id
                                        <&> Json.Object
                                    )
                            pure $ T2 torrentId fullJsonResultT
                        pure $ Just (T2 (label @"tourGroup" tourGroup) torrents)
                )
        )

testChunkBetween :: IO [NonEmpty Integer]
testChunkBetween = do
  Cond.runConduit $
    ( do
        Cond.yield [0]
        Cond.yield [1, 2]
        Cond.yield [3, 4]
        Cond.yield []
        Cond.yield [5, 6]
        Cond.yield [7]
    )
      .| filterEmpty
      .| chunkBetween (t2 #low 2 #high 4)
      .| Cond.sinkList

filterEmpty :: (Monad m) => ConduitT [a] (NonEmpty a) m ()
filterEmpty = Cond.awaitForever yieldIfNonEmpty

-- | Chunk the given stream of lists into chunks that are between @low@ and @high@ (both incl).
-- The last chunk might be shorter than low.
chunkBetween ::
  ( HasField "low" p Natural,
    HasField "high" p Natural,
    Monad m
  ) =>
  p ->
  ConduitT (NonEmpty a) (NonEmpty a) m ()
chunkBetween opts = do
  go mempty
  where
    low = min opts.low opts.high
    high = max opts.low opts.high
    high' = assertField (boundedNatural @Int) high
    l = lengthNatural
    go !acc = do
      if l acc >= low
        then do
          let (c, rest) = List.splitAt high' acc
          yieldIfNonEmpty c
          go rest
        else do
          xs <- Cond.await
          case xs of
            Nothing -> yieldIfNonEmpty acc
            Just xs' -> go (acc <> NonEmpty.toList xs')

yieldIfNonEmpty :: (Monad m) => [a] -> ConduitT i (NonEmpty a) m ()
yieldIfNonEmpty = \case
  IsNonEmpty xs -> Cond.yield xs
  IsEmpty -> pure ()

-- | maxPages: 0 means no limit, 1 means only the first page … etc
redactedPagedSearchAndInsert ::
  (HasField "maxPages" opts Natural) =>
  opts ->
  Json.Parse ErrorTree TourGroups ->
  -- | A redacted request that returns a paged result
  ( forall a.
    Label "page" (Maybe Natural) ->
    Json.Parse ErrorTree a ->
    App a
  ) ->
  AppTransaction (Label "newTorrents" [Label "torrentId" Int])
redactedPagedSearchAndInsert opts innerParser pagedRequest = do
  -- The first search returns the amount of pages, so we use that to query all results piece by piece.
  firstPage <- go Nothing
  let totalPagesToFetch =
        -- 0 requests all pages
        if opts.maxPages == 0
          then firstPage.pages
          else min opts.maxPages firstPage.pages
  let remainingPages = if totalPagesToFetch > 0 then totalPagesToFetch - 1 else 0
  logInfo [fmt|Got the first page, found {remainingPages} more pages|]
  let otherPagesNum = [(2 :: Natural) .. remainingPages]

  Cond.runConduit @(Transaction (AppT IO)) $
    ( do
        Cond.yield (singleton firstPage)
        case otherPagesNum of
          IsNonEmpty pages -> do
            runConcurrentlyBunched' (lbl #batchSize 5) (go . Just <$> pages)
          IsEmpty -> pure ()
    )
      -- .| Cond.takeC 3
      .| chunkBetween (t2 #low 5 #high 10)
      .| Cond.mapMC
        ( \block ->
            block
              & concatMap (.response.tourGroups)
              & \case
                IsNonEmpty tgs -> do
                  tgs & insertTourGroupsAndTorrents (lbl #searchPages $ block & lengthNatural)
                  pure $ tgs & concatMap (\tg -> tg.torrents <&> getLabel @"torrentId")
                IsEmpty -> pure []
        )
      .| Cond.concatC
      .| Cond.sinkList
        <&> label @"newTorrents"
  where
    go mpage =
      lift @Transaction $
        pagedRequest
          (label @"page" mpage)
          ( parseRedactedReplyStatus $ innerParser
          )
    insertTourGroupsAndTorrents ::
      (Label "searchPages" Natural) ->
      NonEmpty
        ( T2
            "tourGroup"
            TourGroup
            "torrents"
            [T2 "torrentId" Int "fullJsonResult" Json.Value]
        ) ->
      AppTransaction ()
    insertTourGroupsAndTorrents insertOpts dat = inSpan' "Insert Tour Groups & Torrents" $ \span -> do
      addAttribute span "search_pages.length" (insertOpts.searchPages, naturalDecimalT)
      addAttribute span "tour_group.length" (dat & lengthNatural, naturalDecimalT)
      let tourGroups = dat <&> (.tourGroup)
      let torrents = dat <&> (.torrents)
      insertTourGroups tourGroups
        >>= ( \res -> do
                insertTorrents $
                  zipT2 $
                    T2
                      (label @"torrentGroupIdPg" $ res <&> (.tourGroupIdPg))
                      (label @"torrents" (torrents & toList))
                -- Extract and insert artist data from both tour groups and torrents
                let tourGroupJsons = tourGroups <&> \tg -> T2 (label @"jsonResult" tg.fullJsonResult) (label @"sourceType" "torrent_group")
                let torrentJsons = dat & concatMap (\d -> d.torrents <&> \t -> T2 (label @"jsonResult" t.fullJsonResult) (label @"sourceType" "torrent"))
                insertArtists (NonEmpty.toList tourGroupJsons <> torrentJsons)
            )
    insertTourGroups ::
      NonEmpty TourGroup ->
      AppTransaction [Label "tourGroupIdPg" Int]
    insertTourGroups dats = do
      let groupNames =
            dats <&> \dat -> [fmt|{dat.groupId}: {dat.groupName}|]
      logInfo [fmt|Inserting tour groups for {showPretty groupNames}|]
      _ <-
        execute
          [fmt|
                  DELETE FROM redacted.torrent_groups
                  WHERE group_id = ANY (?::integer[])
              |]
          (Only $ (dats <&> (.groupId) & toList & PGArray :: PGArray Int))
      executeManyReturningWith
        [fmt|
              INSERT INTO redacted.torrent_groups (
                group_id, group_name, full_json_result
              ) VALUES
              ( ?, ? , ? )
              ON CONFLICT (group_id) DO UPDATE SET
                group_id = excluded.group_id,
                group_name = excluded.group_name,
                full_json_result = excluded.full_json_result
              RETURNING (id)
            |]
        ( dats
            -- make sure we don’t have the same conflict target twice
            & NonEmpty.nubBy (\a b -> a.groupId == b.groupId)
            <&> ( \dat ->
                    ( dat.groupId,
                      dat.groupName,
                      dat.fullJsonResult
                    )
                )
        )
        (label @"tourGroupIdPg" <$> Dec.fromField @Int)

    insertTorrents ::
      [ T2
          "torrentGroupIdPg"
          Int
          "torrents"
          [T2 "torrentId" Int "fullJsonResult" Json.Value]
      ] ->
      AppTransaction ()
    insertTorrents dats = do
      _ <-
        execute
          [sql|
            DELETE FROM redacted.torrents_json
            WHERE torrent_id = ANY (?::integer[])
          |]
          ( Only $
              PGArray
                [ torrent.torrentId
                  | dat <- dats,
                    torrent <- dat.torrents
                ]
          )

      execute
        [sql|
          INSERT INTO redacted.torrents_json
            ( torrent_group
            , torrent_id
            , full_json_result)
          SELECT *
          FROM UNNEST(
              ?::integer[]
            , ?::integer[]
            , ?::jsonb[]
          ) AS inputs(
              torrent_group
            , torrent_id
            , full_json_result)
          |]
        ( [ T3
              (getLabel @"torrentGroupIdPg" dat)
              (getLabel @"torrentId" group)
              (getLabel @"fullJsonResult" group)
            | dat <- dats,
              group <- dat.torrents
          ]
            & List.nubBy (\a b -> a.torrentId == b.torrentId)
            & unzip3PGArray
              @"torrentGroupIdPg"
              @Int
              @"torrentId"
              @Int
              @"fullJsonResult"
              @Json.Value
        )
      pure ()

-- | Traverse over the given function in parallel, but only allow a certain amount of concurrent requests.
-- Will start new threads as soon as a resource becomes available, but always return results in input ordering.
runConcurrentlyBunched' ::
  forall m opts a.
  ( MonadUnliftIO m,
    HasField "batchSize" opts Natural
  ) =>
  opts ->
  -- | list of actions to run
  NonEmpty (m a) ->
  ConduitT () (NonEmpty a) m ()
runConcurrentlyBunched' opts acts = do
  let batchSize = assertField (boundedNatural @Int) opts.batchSize
  runInIO <- lift askRunInIO
  -- NB: make sure none of the asyncs escape from here
  Cond.transPipe (Cond.runResourceT @m) $ do
    -- This use of resourceForkWith looks a little off, but it’s the only way to return an `Async a`, I hope it brackets correctly lol
    ctx <- Otel.getContext
    let spawn :: m a -> Cond.ResourceT m (Async a)
        spawn f = resourceForkWith (\io -> async (io >> Otel.attachContext ctx >> runInIO f)) (pure ())
    qsem <- newQSem batchSize

    -- spawn all asyncs here, but limit how many get run consecutively by threading through a semaphore
    spawned <- for acts $ \act ->
      lift $ spawn $ withQSem qsem $ act

    Cond.yieldMany (spawned & NonEmpty.toList)
      .| awaitAllReadyAsyncs

-- | Consume as many asyncs as are ready and return their results.
--
-- Make sure they are already running (if you use 'Cond.yieldM' they are only started when awaited by the conduit).
--
-- If any async throws an exception, the exception will be thrown in the conduit.
-- Already running asyncs will not be cancelled. (TODO: can we somehow make that a thing?)
awaitAllReadyAsyncs :: forall m a. (MonadIO m) => ConduitT (Async a) (NonEmpty a) m ()
awaitAllReadyAsyncs = go
  where
    -- wait for the next async and then consume as many as are already done
    go :: ConduitT (Async a) (NonEmpty a) m ()
    go = do
      Cond.await >>= \case
        Nothing -> pure ()
        Just nextAsync -> do
          res <- Async.wait nextAsync
          -- consume as many asyncs as are already done
          goAllReady (RevList.singleton res)

    goAllReady :: RevList a -> ConduitT (Async a) (NonEmpty a) m ()
    goAllReady !acc = do
      next <- Cond.await
      case next of
        Nothing -> yieldIfNonEmptyRev acc
        Just a -> do
          thereAlready <- Async.poll a
          case thereAlready of
            Nothing -> do
              -- consumed everything that was available, yield and wait for the next block
              yieldIfNonEmptyRev acc
              Cond.leftover a
              go
            Just _ -> do
              -- will not block
              res <- Async.wait a
              goAllReady (acc <> RevList.singleton res)

    yieldIfNonEmptyRev :: RevList a -> ConduitT (Async a) (NonEmpty a) m ()
    yieldIfNonEmptyRev r = do
      case r & RevList.revListToList of
        IsNonEmpty e -> Cond.yield e
        IsEmpty -> pure ()

testAwaitAllReadyAsyncs :: IO [[Char]]
testAwaitAllReadyAsyncs =
  Cond.runConduit $
    ( do
        running <-
          lift $
            sequence
              [ async (print "foo" >> pure 'a'),
                async (pure 'b'),
                async (threadDelay 5000 >> pure 'c'),
                async (print "bar" >> pure '5'),
                async (threadDelay 1_000_000 >> print "lol" >> pure 'd'),
                async (error "no"),
                async (print "baz" >> pure 'f')
              ]
        Cond.yieldMany running
    )
      .| awaitAllReadyAsyncs
      .| Cond.mapC toList
      .| Cond.sinkList

-- | Run the field parser and throw an uncatchable assertion error if it fails.
assertField :: (HasCallStack) => FieldParser from to -> from -> to
assertField parser from = Field.runFieldParser parser from & unwrapError

boundedNatural :: forall i. (Integral i, Bounded i) => FieldParser Natural i
boundedNatural = lmap naturalToInteger (Field.bounded @i "boundedNatural")

redactedGetTorrentFileAndInsert ::
  ( HasField "torrentId" r Int,
    HasField "freelechTokensExhaustedAt" r (Maybe UTCTime)
  ) =>
  r ->
  AppTransaction (T2 "freelechStatus" FreeleechStatus "torrentFile" ByteString)
redactedGetTorrentFileAndInsert dat = inSpan' "Redacted Get Torrent File and Insert" $ \span -> do
  result <- lift $ redactedGetTorrentFile dat
  let bytes = result.torrentFile
  execute
    [sql|
    UPDATE redacted.torrents_json
    SET torrent_file = ?::bytea
    WHERE torrent_id = ?::integer
  |]
    ( (Binary bytes :: Binary ByteString),
      dat.torrentId
    )
    >>= lift . assertOneUpdated span "redactedGetTorrentFileAndInsert"
    >>= \() -> pure result

getTorrentFileById ::
  ( HasField "torrentId" r Int
  ) =>
  r ->
  AppTransaction (Maybe (Label "torrentFile" ByteString))
getTorrentFileById dat = do
  queryWith
    [sql|
    SELECT torrent_file
    FROM redacted.torrents
    WHERE torrent_id = ?::integer
  |]
    (Only $ (dat.torrentId :: Int))
    (fmap @Maybe (label @"torrentFile") <$> Dec.byteaMay)
    >>= ensureSingleRow

updateTransmissionTorrentHashById ::
  ( HasField "torrentId" r Int,
    HasField "torrentHash" r Text
  ) =>
  r ->
  AppTransaction (Label "numberOfRowsAffected" Natural)
updateTransmissionTorrentHashById dat = do
  execute
    [sql|
    UPDATE redacted.torrents_json
    SET transmission_torrent_hash = ?::text
    WHERE torrent_id = ?::integer
    |]
    ( dat.torrentHash :: Text,
      dat.torrentId :: Int
    )

assertOneUpdated ::
  ( HasField "numberOfRowsAffected" r Natural
  ) =>
  Otel.Span ->
  Text ->
  r ->
  App ()
assertOneUpdated span name x = case x.numberOfRowsAffected of
  1 -> pure ()
  n -> appThrow span ([fmt|{name :: Text}: Expected to update exactly one row, but updated {n :: Natural} row(s)|])

data TorrentData transmissionInfo = TorrentData
  { groupId :: Int,
    torrentId :: Int,
    releaseType :: ReleaseType,
    seedingWeight :: Int,
    artists :: [T2 "artistId" Int "artistName" Text],
    torrentGroupJson :: TorrentGroupJson,
    torrentStatus :: TorrentStatus transmissionInfo,
    torrentFormat :: Text
  }

-- | https://redacted.sh/wiki.php?action=article&id=455#_1804298149
data ReleaseType = ReleaseType {intKey :: Int, stringKey :: Text}
  deriving stock (Eq, Show)

releaseTypeFromTextOrIntKey :: Text -> ReleaseType
releaseTypeFromTextOrIntKey t =
  allReleaseTypesSorted
    & List.find
      ( \rt -> do
          rt.stringKey == t || buildText intDecimalT rt.intKey == t
      )
    & fromMaybe (ReleaseType {intKey = (-1), stringKey = t})

releaseTypeComparison :: Comparison ReleaseType
releaseTypeComparison = listIndexComparison allReleaseTypesSorted

allReleaseTypesSorted :: [ReleaseType]
allReleaseTypesSorted =
  [ releaseTypeAlbum,
    releaseTypeLiveAlbum,
    releaseTypeAnthology,
    releaseTypeSoundtrack,
    releaseTypeEP,
    releaseTypeCompilation,
    releaseTypeSingle,
    releaseTypeRemix,
    releaseTypeBootleg,
    releaseTypeInterview,
    releaseTypeMixtape,
    releaseTypeDemo,
    releaseTypeConcertRecording,
    releaseTypeDJMix,
    releaseTypeUnknown,
    releaseTypeProducedBy,
    releaseTypeComposition,
    releaseTypeRemixedBy,
    releaseTypeGuestAppearance
  ]

-- | The search allows us to pass which release types we are interested in,
-- however I want to disallow certain types, but they don’t provide a mechanism to do that.
-- So instead let’s overapproximate the ids in case new types get added in the future.
releaseTypeIntsOverapproximated :: IntSet
releaseTypeIntsOverapproximated = IntSet.fromList $ [1 .. 50] <> [1000 .. 1050]

releaseTypesOverapproximatedWithout :: [ReleaseType] -> IntSet
releaseTypesOverapproximatedWithout disallowed = do
  let disallowedInts = disallowed <&> (.intKey)
  IntSet.difference releaseTypeIntsOverapproximated (IntSet.fromList disallowedInts)

releaseTypeAlbum, releaseTypeSoundtrack, releaseTypeEP, releaseTypeAnthology, releaseTypeCompilation, releaseTypeSingle, releaseTypeLiveAlbum, releaseTypeRemix, releaseTypeBootleg, releaseTypeInterview, releaseTypeMixtape, releaseTypeDemo, releaseTypeConcertRecording, releaseTypeDJMix, releaseTypeUnknown, releaseTypeProducedBy, releaseTypeComposition, releaseTypeRemixedBy, releaseTypeGuestAppearance :: ReleaseType
releaseTypeAlbum = ReleaseType 1 "Album"
releaseTypeSoundtrack = ReleaseType 3 "Soundtrack"
releaseTypeEP = ReleaseType 5 "EP"
releaseTypeAnthology = ReleaseType 6 "Anthology"
releaseTypeCompilation = ReleaseType 7 "Compilation"
releaseTypeSingle = ReleaseType 9 "Single"
releaseTypeLiveAlbum = ReleaseType 11 "Live album"
releaseTypeRemix = ReleaseType 13 "Remix"
releaseTypeBootleg = ReleaseType 14 "Bootleg"
releaseTypeInterview = ReleaseType 15 "Interview"
releaseTypeMixtape = ReleaseType 16 "Mixtape"
releaseTypeDemo = ReleaseType 17 "Demo"
releaseTypeConcertRecording = ReleaseType 18 "Concert Recording"
releaseTypeDJMix = ReleaseType 19 "DJ Mix"
releaseTypeUnknown = ReleaseType 21 "Unknown"
releaseTypeProducedBy = ReleaseType 1021 "Produced By"
releaseTypeComposition = ReleaseType 1022 "Composition"
releaseTypeRemixedBy = ReleaseType 1023 "Remixed By"
releaseTypeGuestAppearance = ReleaseType 1024 "Guest Appearance"

data TorrentGroupJson = TorrentGroupJson
  { groupName :: Text,
    groupYear :: Natural
  }

data TorrentStatus transmissionInfo
  = NoTorrentFileYet
  | NotInTransmissionYet
  | InTransmission (T2 "torrentHash" Text "transmissionInfo" transmissionInfo)

getTorrentById :: (MonadPostgres m, HasField "torrentId" r Int, MonadThrow m) => r -> Transaction m Json.Value
getTorrentById dat = do
  queryWith
    [sql|
    SELECT full_json_result FROM redacted.torrents
    WHERE torrent_id = ?::integer
  |]
    (getLabel @"torrentId" dat)
    (Dec.json Json.asValue)
    >>= ensureSingleRow

data GetBestTorrentsFilter = GetBestTorrentsFilter
  { onlyArtist :: Maybe (Label "artistRedactedId" Int),
    onlyTheseTorrents :: Maybe ([Label "torrentId" Int]),
    disallowedReleaseTypes :: [ReleaseType],
    limitResults :: Maybe Natural,
    ordering :: BestTorrentsOrdering,
    onlyFavourites :: Bool
  }

data BestTorrentsOrdering = BySeedingWeight | ByLastReleases

-- | Get best recommendation: one highest-weighted album per similar artist
getBestRecommendations ::
  ( MonadPostgres m,
    HasField "disallowedReleaseTypes" opts [ReleaseType],
    HasField "limitResults" opts (Maybe Natural)
  ) =>
  opts ->
  Transaction m [T2 "torrentData" (TorrentData ()) "recommendedBy" [T3 "favoritedArtistId" Int "favoritedArtistName" Text "recommendedArtistId" Int]]
getBestRecommendations opts = do
  queryWith
    [sql|
      WITH
        favorited_artists AS (
          SELECT DISTINCT unnest(artist_ids) as artist_id
          FROM redacted.torrents_json
          WHERE transmission_torrent_hash IS NOT NULL
          UNION
          SELECT artist_id
          FROM redacted.artist_favourites
        ),
        valid_recommendations AS (
          SELECT
            sa.artist_id as favorited_artist_id,
            sa.similar_artist_id as recommended_artist_id,
            a.artist_name as favorited_artist_name,
            sa.rn
          FROM (
            SELECT
              artist_id,
              similar_artist_id,
              ROW_NUMBER() OVER (PARTITION BY artist_id ORDER BY score DESC) as rn
            FROM redacted.similar_artists
            WHERE
              artist_id IN (SELECT artist_id FROM favorited_artists)
              AND similar_artist_id NOT IN (SELECT artist_id FROM favorited_artists)
          ) sa
          JOIN redacted.artists a ON a.artist_id = sa.artist_id
        ),
        top_recommendations AS (
          SELECT DISTINCT ON (rec_id)
            tg.group_id,
            t.torrent_id,
            t.seeding_weight,
            tg.full_json_result->>'releaseType' AS release_type,
            COALESCE(
              t.full_json_result->'artists',
              tg.full_json_result->'artists',
              '[]'::jsonb
            ) as artists,
            t.artist_ids as artist_ids,
            tg.full_json_result->>'groupName' AS group_name,
            tg.full_json_result->>'groupYear' AS group_year,
            t.torrent_file IS NOT NULL AS has_torrent_file,
            t.transmission_torrent_hash,
            t.full_json_result->>'encoding' AS torrent_format
          FROM (SELECT recommended_artist_id FROM valid_recommendations) vr
          CROSS JOIN LATERAL unnest(ARRAY[vr.recommended_artist_id]) AS rec_id
          JOIN redacted.torrents_json t ON t.artist_ids @> ARRAY[rec_id]
          JOIN redacted.torrent_groups tg ON tg.id = t.torrent_group
          WHERE
            tg.full_json_result->>'releaseType' <> ALL (?::text[])
          ORDER BY
            rec_id,
            t.seeding_weight DESC
        ),
        final_unsorted AS (
          SELECT
            tr.group_id,
            tr.torrent_id,
            tr.seeding_weight,
            tr.release_type,
            tr.artists,
            tr.group_name,
            tr.group_year,
            tr.has_torrent_file,
            tr.transmission_torrent_hash,
            tr.torrent_format,
            (
              SELECT json_agg(
                json_build_object(
                  'favorited_artist_id', vr2.favorited_artist_id,
                  'favorited_artist_name', vr2.favorited_artist_name,
                  'recommended_artist_id', vr2.recommended_artist_id
                )
              )
              FROM valid_recommendations vr2
              WHERE ARRAY[vr2.recommended_artist_id] <@ tr.artist_ids
            ) as recommendation_mappings
          FROM top_recommendations tr
          ORDER BY
            (SELECT MIN(vr2.rn) FROM valid_recommendations vr2 WHERE ARRAY[vr2.recommended_artist_id] <@ tr.artist_ids)
        )
      SELECT * FROM final_unsorted
      ORDER BY seeding_weight DESC
      LIMIT ?::int
    |]
    ( (opts.disallowedReleaseTypes & concatMap (\rt -> [rt.stringKey, rt.intKey & buildText intDecimalT]) & PGArray :: PGArray Text),
      opts.limitResults <&> naturalToInteger :: Maybe Integer
    )
    ( do
        groupId <- Dec.fromField @Int
        torrentId <- Dec.fromField @Int
        seedingWeight <- Dec.fromField @Int
        releaseType <- releaseTypeFromTextOrIntKey <$> Dec.text
        artists <- Dec.fromField @Json.Value
        groupName <- Dec.text
        groupYear <- Dec.textParse Field.decimalNatural
        hasTorrentFile <- Dec.fromField @Bool
        transmissionTorrentHash <- Dec.fromField @(Maybe Text)
        torrentFormat <- Dec.text
        recommendationMappings <- Dec.fromField @Json.Value

        let torrentData =
              TorrentData
                { groupId = groupId,
                  torrentId = torrentId,
                  seedingWeight = seedingWeight,
                  releaseType = releaseType,
                  artists = case Json.parseValue
                    ( Json.eachInArray $ do
                        artistId <- Json.key "id" (Json.asIntegral @_ @Int)
                        artistName <- Json.key "name" Json.asText
                        pure $
                          T2
                            (label @"artistId" artistId)
                            (label @"artistName" artistName)
                    )
                    artists of
                    Left _ -> []
                    Right res -> res,
                  torrentGroupJson =
                    TorrentGroupJson
                      { groupName = groupName,
                        groupYear = groupYear
                      },
                  torrentStatus = case transmissionTorrentHash of
                    Nothing -> if hasTorrentFile then NotInTransmissionYet else NoTorrentFileYet
                    Just hash -> InTransmission (T2 (label @"torrentHash" hash) (label @"transmissionInfo" ())),
                  torrentFormat = torrentFormat
                }
            recommendedBy = case Json.parseValue
              ( Json.eachInArray $ do
                  favoritedArtistId <- Json.key "favorited_artist_id" (Json.asIntegral @_ @Int)
                  favoritedArtistName <- Json.key "favorited_artist_name" Json.asText
                  recommendedArtistId <- Json.key "recommended_artist_id" (Json.asIntegral @_ @Int)
                  pure $
                    T3
                      (label @"favoritedArtistId" favoritedArtistId)
                      (label @"favoritedArtistName" favoritedArtistName)
                      (label @"recommendedArtistId" recommendedArtistId)
              )
              recommendationMappings of
              Left _ -> []
              Right res -> res

        pure $
          T2
            (label @"torrentData" torrentData)
            (label @"recommendedBy" recommendedBy)
    )

-- | Find the best torrent for each torrent group (based on the seeding_weight)
getBestTorrents ::
  (MonadPostgres m) =>
  GetBestTorrentsFilter ->
  Transaction m [TorrentData ()]
getBestTorrents opts = do
  queryWith
    ( [sql|
      WITH
      artist_has_been_snatched AS (
        SELECT DISTINCT artist_id
        FROM (
          SELECT
            UNNEST(artist_ids) as artist_id,
            t.torrent_file IS NOT NULL as has_torrent_file
          FROM redacted.torrents t) as _
        WHERE has_torrent_file
      ),
      filtered_torrents AS (
        SELECT DISTINCT ON (torrent_group)
          id
        FROM
          redacted.torrents
        JOIN LATERAL
          -- filter everything that’s not a favourite if requested
          (SELECT (
            artist_ids && ARRAY(
              SELECT DISTINCT unnest(artist_ids)
              FROM redacted.torrents_json
              WHERE transmission_torrent_hash IS NOT NULL
              UNION
              SELECT artist_id
              FROM redacted.artist_favourites
            )
            OR artist_ids && ARRAY(SELECT artist_id FROM artist_has_been_snatched)
          ) as is_favourite) as _
          ON (NOT ?::bool OR is_favourite)
        WHERE
          -- filter by artist id
          (?::bool OR (?::int = any (artist_ids)))
          -- filter by torrent ids
          AND
          (?::bool OR torrent_id = ANY (?::int[]))
        ORDER BY
          torrent_group,
          -- prefer torrents which we already downloaded
          torrent_file,
          seeding_weight DESC
      ),
      prepare1 AS (
        SELECT
          tg.group_id,
          t.torrent_id,
          t.seeding_weight,
          tg.full_json_result->>'releaseType' AS release_type,
          -- TODO: different endpoints handle this differently (e.g. action=search and action=artist), we should unify this while parsing
          COALESCE(
            t.full_json_result->'artists',
            tg.full_json_result->'artists',
            '[]'::jsonb
          ) as artists,
          t.artist_ids as artist_ids,
          tg.full_json_result->>'groupName' AS group_name,
          tg.full_json_result->>'groupYear' AS group_year,
          t.torrent_file IS NOT NULL AS has_torrent_file,
          t.transmission_torrent_hash,
          t.full_json_result->>'encoding' AS torrent_format
        FROM filtered_torrents f
        JOIN redacted.torrents t ON t.id = f.id
        JOIN redacted.torrent_groups tg ON tg.id = t.torrent_group
        WHERE
          tg.full_json_result->>'releaseType' <> ALL (?::text[])
      )
      SELECT
        group_id,
        torrent_id,
        seeding_weight,
        release_type,
        artists,
        group_name,
        group_year,
        has_torrent_file,
        transmission_torrent_hash,
        torrent_format
      FROM prepare1
    |]
        <> case opts.ordering of
          BySeedingWeight -> [fmt|ORDER BY seeding_weight DESC|] <> "\n"
          ByLastReleases -> [fmt|ORDER BY group_id DESC|] <> "\n"
        <> [sql|
      LIMIT ?::int
    |]
    )
    ( do
        let (onlyArtistB, onlyArtistId) = case opts.onlyArtist of
              Nothing -> (True, 0)
              Just a -> (False, a.artistRedactedId)
        let (onlyTheseTorrentsB, onlyTheseTorrents) = case opts.onlyTheseTorrents of
              Nothing -> (True, PGArray [])
              Just a -> (False, a <&> (.torrentId) & PGArray)
        ( opts.onlyFavourites :: Bool,
          onlyArtistB :: Bool,
          onlyArtistId :: Int,
          onlyTheseTorrentsB :: Bool,
          onlyTheseTorrents,
          (opts.disallowedReleaseTypes & concatMap (\rt -> [rt.stringKey, rt.intKey & buildText intDecimalT]) & PGArray :: PGArray Text),
          opts.limitResults <&> naturalToInteger :: Maybe Integer
          )
    )
    ( do
        groupId <- Dec.fromField @Int
        torrentId <- Dec.fromField @Int
        seedingWeight <- Dec.fromField @Int
        releaseType <- releaseTypeFromTextOrIntKey <$> Dec.text
        artists <- Dec.json $
          Json.eachInArray $ do
            id_ <- Json.keyLabel @"artistId" "id" (Json.asIntegral @_ @Int)
            name <- Json.keyLabel @"artistName" "name" Json.asText
            pure $ T2 id_ name
        torrentGroupJson <- do
          groupName <- Dec.text
          groupYear <- Dec.textParse Field.decimalNatural
          pure $ TorrentGroupJson {..}
        hasTorrentFile <- Dec.fromField @Bool
        transmissionTorrentHash <- Dec.fromField @(Maybe Text)
        torrentFormat <- Dec.text
        pure $
          TorrentData
            { torrentStatus =
                if
                  | not hasTorrentFile -> NoTorrentFileYet
                  | Nothing <- transmissionTorrentHash -> NotInTransmissionYet
                  | Just hash <- transmissionTorrentHash ->
                      InTransmission $
                        T2 (label @"torrentHash" hash) (label @"transmissionInfo" ()),
              torrentFormat = case torrentFormat of
                "Lossless" -> "flac"
                "V0 (VBR)" -> "V0"
                "V2 (VBR)" -> "V2"
                "320" -> "320"
                "256" -> "256"
                o -> o,
              ..
            }
    )

getArtistNameById :: (MonadPostgres m, HasField "artistId" r Int) => r -> Transaction m (Maybe Text)
getArtistNameById dat = do
  queryFirstRowWithMaybe
    [sql|
        SELECT artist_name FROM redacted.artists
        WHERE artist_id = ?::int
        LIMIT 1
  |]
    (getLabel @"artistId" dat)
    (Dec.fromField @Text)

-- | Do a request to the redacted API. If you know what that is, you know how to find the API docs.
mkRedactedApiRequest ::
  ( HasField "action" p ByteString,
    HasField "actionArgs" p [(ByteString, Maybe ByteString)]
  ) =>
  p ->
  App Http.RequestOptions
mkRedactedApiRequest dat = do
  authKey <- getRedactedApiKey
  pure $
    (Http.mkRequestOptions (t2 #method "GET" #host "redacted.sh"))
      { Http.path = mkOptional ["ajax.php"],
        Http.queryParams = mkOptional (("action", Just dat.action) : dat.actionArgs),
        Http.headers = mkOptional [("Authorization", authKey)]
      }

httpTorrent ::
  Http.RequestOptions ->
  App (Either (E2 "tokensExhausted" () "otherError" AppException) ByteString)
httpTorrent reqOpts = do
  resp <- Http.executeRequestOptions reqOpts Nothing
  let statusCode = resp & Http.getResponseStatus & (.statusCode)
      contentType =
        resp
          & Http.getResponseHeaders
          & List.lookup "content-type"
          <&> Wai.parseContentType
          <&> (\(ct, _mimeAttributes) -> ct)
      responseBody = resp & Http.getResponseBody
  pure $
    if
      | statusCode == 200,
        Just "application/x-bittorrent" <- contentType ->
          Right responseBody
      | statusCode == 200,
        Just otherType <- contentType ->
          Left $ e22 #otherError $ AppExceptionPretty [[fmt|Redacted returned a non-torrent body, with content-type "{otherType}"|]]
      | statusCode == 200,
        Nothing <- contentType ->
          Left $ e22 #otherError $ AppExceptionPretty [[fmt|Redacted returned a body with unspecified content type|]]
      | statusCode == 400 ->
          -- Check if this is a token exhaustion error
          case Json.eitherDecode (responseBody & toLazyBytes) of
            Right (json :: Json.Value) ->
              case Parse.runParse "parse error response" (Json.parseJsonValue (Json.key "error" Json.asText)) json of
                Right errorMsg
                  | "You do not have any freeleech tokens left" `Text.isInfixOf` errorMsg ->
                      Left $ e21 #tokensExhausted ()
                _ ->
                  Left $ e22 #otherError $ AppExceptionPretty [[fmt|Redacted returned a 400 error|], pretty resp]
            Left _ ->
              Left $ e22 #otherError $ AppExceptionPretty [[fmt|Redacted returned a 400 error|], pretty resp]
      | code <- statusCode ->
          Left $ e22 #otherError $ AppExceptionPretty [[fmt|Redacted returned an non-200 error code, code {code}|], pretty resp]

redactedApiRequestJson ::
  ( HasField "action" p ByteString,
    HasField "actionArgs" p [(ByteString, Maybe ByteString)]
  ) =>
  Otel.Span ->
  p ->
  Json.Parse ErrorTree a ->
  App a
redactedApiRequestJson span dat parser = do
  addAttribute span "redacted.request" (toOtelJsonAttr (T2 (getLabel @"action" dat) (getLabel @"actionArgs" dat)))
  mkRedactedApiRequest dat
    >>= Http.httpJsonWithRateLimit defaults parser

-- Type-safe similar artists response
data SimilarArtist = SimilarArtist
  { artistId :: Int,
    artistName :: Text,
    score :: Int
  }
  deriving stock (Show, Eq)

similarArtistToEnc :: SimilarArtist -> Enc.Enc
similarArtistToEnc sa =
  Enc.object
    [ ("id", Enc.int sa.artistId),
      ("name", Enc.text sa.artistName),
      ("score", Enc.int sa.score)
    ]

redactedGetSimilarArtists ::
  ( HasField "artistId" r Int,
    HasField "limit" r (Maybe Natural)
  ) =>
  r ->
  App [SimilarArtist]
redactedGetSimilarArtists dat =
  inSpan' "Redacted Get Similar Artists" $ \span -> do
    let actionArgs =
          [("id", Just $ buildBytes intDecimalB dat.artistId)]
            <> case dat.limit of
              Nothing -> []
              Just lim -> [("limit", Just $ buildBytes naturalDecimalB lim)]
    redactedApiRequestJson
      span
      ( t2
          #action
          "similar_artists"
          #actionArgs
          actionArgs
      )
      ( do
          status <- Json.key "status" Json.asText
          when (status /= "success") $ do
            Json.throwCustomError ([fmt|Status was not "success", but {status}|] :: ErrorTree)
          Json.key "response" $
            Json.eachInArray $ do
              artistId <- Json.key "id" (Json.asIntegral @_ @Int)
              artistName <- Json.key "name" Json.asText
              score <- Json.key "score" (Json.asIntegral @_ @Int)
              pure $ SimilarArtist {..}
      )

-- Version that returns raw JSON for exploration
redactedGetSimilarArtistsRaw ::
  ( HasField "artistId" r Int,
    HasField "limit" r (Maybe Natural)
  ) =>
  r ->
  App Json.Value
redactedGetSimilarArtistsRaw dat =
  inSpan' "Redacted Get Similar Artists Raw" $ \span -> do
    let actionArgs =
          [("id", Just $ buildBytes intDecimalB dat.artistId)]
            <> case dat.limit of
              Nothing -> []
              Just lim -> [("limit", Just $ buildBytes naturalDecimalB lim)]
    redactedApiRequestJson
      span
      ( t2
          #action
          "similar_artists"
          #actionArgs
          actionArgs
      )
      Json.asValue

-- Simple test server for API exploration
testServer :: App ()
testServer = do
  liftIO $ putStrLn "Starting test server on http://localhost:9094"
  liftIO $ putStrLn "Endpoints:"
  liftIO $ putStrLn "  curl 'http://localhost:9094/similar-raw?artist=2785&limit=5'   # Raw JSON"
  liftIO $ putStrLn "  curl 'http://localhost:9094/similar?artist=2785&limit=5'       # Type-safe"
  withRunInIO $ \runInIO ->
    Warp.run 9094 $ \req respond -> do
      let path = req & Wai.pathInfo
      case path of
        ["similar-raw"] -> do
          let parseParam name parser =
                req & Wai.queryString & lookup name >>= \mbs ->
                  mbs >>= \bs ->
                    Field.runFieldParser parser bs & hush
          let artistId = parseParam "artist" (Field.utf8 >>> Field.signedDecimal >>> Field.bounded @Int "int")
          let limit = parseParam "limit" (Field.utf8 >>> Field.decimalNatural)
          case artistId of
            Nothing -> respond $ Wai.responseLBS Http.badRequest400 [] "Missing or invalid artist parameter"
            Just aid -> do
              result <- runInIO $ redactedGetSimilarArtistsRaw (t2 #artistId aid #limit limit)
              respond $
                Wai.responseLBS
                  Http.ok200
                  [("Content-Type", "application/json")]
                  (result & Json.encode)
        ["similar"] -> do
          let parseParam name parser =
                req & Wai.queryString & lookup name >>= \mbs ->
                  mbs >>= \bs ->
                    Field.runFieldParser parser bs & hush
          let artistId = parseParam "artist" (Field.utf8 >>> Field.signedDecimal >>> Field.bounded @Int "int")
          let limit = parseParam "limit" (Field.utf8 >>> Field.decimalNatural)
          case artistId of
            Nothing -> respond $ Wai.responseLBS Http.badRequest400 [] "Missing or invalid artist parameter"
            Just aid -> do
              result <- runInIO $ redactedGetSimilarArtists (t2 #artistId aid #limit limit)
              respond $
                Wai.responseLBS
                  Http.ok200
                  [("Content-Type", "application/json")]
                  (result & Enc.list similarArtistToEnc & Enc.encToBytesUtf8 & toLazyBytes)
        _ -> respond $ Wai.responseLBS Http.notFound404 [] "Available endpoints: /similar, /similar-raw"

-- | Insert similar artists data into the database
insertSimilarArtists ::
  ( HasField "artistId" dat Int,
    MonadPostgres m
  ) =>
  dat ->
  [SimilarArtist] ->
  Transaction m ()
insertSimilarArtists dat similarArtists = do
  -- Delete existing similar artists for this artist to avoid duplicates
  _ <-
    execute
      [sql|
      DELETE FROM redacted.similar_artists
      WHERE artist_id = ?::integer
    |]
      (Only dat.artistId)

  -- Insert new similar artists
  case similarArtists of
    [] -> pure () -- No similar artists to insert
    artists -> do
      _ <-
        execute
          [sql|
          INSERT INTO redacted.similar_artists
            (artist_id, similar_artist_id, similar_artist_name, score)
          SELECT * FROM UNNEST(
            ?::integer[],
            ?::integer[],
            ?::text[],
            ?::integer[]
          )
        |]
          ( PGArray (artists <&> const dat.artistId),
            PGArray (artists <&> (.artistId)),
            PGArray (artists <&> (.artistName)),
            PGArray (artists <&> (.score))
          )
      pure ()

-- | Fetch and store similar artists for a given artist
populateSimilarArtistsForArtist ::
  ( HasField "artistId" dat Int
  ) =>
  dat ->
  AppTransaction (Label "similarArtistsCount" Natural)
populateSimilarArtistsForArtist dat = inSpan' "Populate Similar Artists" $ \span -> do
  addAttribute span "artist.id" (dat.artistId, intDecimalT)

  -- Fetch similar artists from the API
  similarArtists <- lift $ redactedGetSimilarArtists (t2 #artistId dat.artistId #limit (Just 20))

  addAttribute span "similar-artists.fetched" (List.length similarArtists, intDecimalT)

  -- Insert into database
  insertSimilarArtists dat similarArtists

  pure $ label @"similarArtistsCount" (lengthNatural similarArtists)

-- | Populate similar artists for all favorite artists
populateSimilarArtistsForFavorites :: AppTransaction (Label "processedArtists" Natural)
populateSimilarArtistsForFavorites = inSpan' "Populate Similar Artists for Favorites" $ \span -> do
  -- Get all favorite artist IDs
  favoriteArtistIds <-
    queryWith
      [sql|
      SELECT DISTINCT unnest(artist_ids) as artist_id
      FROM redacted.torrents_json
      WHERE transmission_torrent_hash IS NOT NULL
      UNION
      SELECT artist_id
      FROM redacted.artist_favourites
      ORDER BY artist_id
    |]
      ()
      (Dec.fromField @Int)

  addAttribute span "favorite-artists.count" (List.length favoriteArtistIds, intDecimalT)

  -- Process each favorite artist
  processedCount <- for favoriteArtistIds $ \artistId -> do
    result <- populateSimilarArtistsForArtist (label @"artistId" artistId)
    logInfo [fmt|Populated {result.similarArtistsCount} similar artists for artist {artistId}|]
    pure result.similarArtistsCount

  let totalProcessed = processedCount & map naturalToInteger & sum & (fromInteger :: Integer -> Natural)
  addAttribute span "similar-artists.total-populated" (totalProcessed, naturalDecimalT)

  pure $ label @"processedArtists" (lengthNatural favoriteArtistIds)

-- | Fetch releases for all similar artists to populate the torrent database
populateReleasesForSimilarArtists :: AppTransaction (Label "processedArtists" Natural)
populateReleasesForSimilarArtists = inSpan' "Populate Releases for Similar Artists" $ \span -> do
  -- Get all similar artist IDs that we don't have releases for yet
  similarArtistIds <-
    queryWith
      [sql|
      SELECT DISTINCT sa.similar_artist_id, sa.similar_artist_name
      FROM redacted.similar_artists sa
      WHERE sa.similar_artist_id NOT IN (
        -- Only fetch artists we don't already have data for
        SELECT DISTINCT unnest(artist_ids)
        FROM redacted.torrent_groups
        WHERE artist_ids IS NOT NULL
      )
      ORDER BY sa.similar_artist_id
      LIMIT 20  -- Process in batches to avoid overwhelming the API
    |]
      ()
      ( do
          artistId <- Dec.fromField @Int
          artistName <- Dec.fromField @Text
          pure (artistId, artistName)
      )

  addAttribute span "similar-artists-to-fetch.count" (List.length similarArtistIds, intDecimalT)

  -- Search for releases by each similar artist
  totalNewTorrents <- for similarArtistIds $ \(artistId, artistName) -> do
    inSpan' [fmt|Search Similar Artist: {artistName}|] $ \artistSpan -> do
      addAttribute artistSpan "artist.id" (artistId, intDecimalT)
      addAttribute artistSpan "artist.name" artistName

      logInfo [fmt|Searching for releases by similar artist: {artistName} (ID: {artistId})|]

      let allowedReleaseTypes =
            releaseTypesOverapproximatedWithout
              [ releaseTypeCompilation
              ]
      let releaseTypeParam =
            allowedReleaseTypes
              & IntSet.toList
              & map (buildText intDecimalT)
              & Text.intercalate ","
              & textToBytesUtf8
      result <-
        redactedSearchAndInsert
          -- only fetch the first page that should be enough for suggesting a release
          (lbl #maxPages 1)
          [ ("artistname", textToBytesUtf8 artistName),
            -- Exclude compilations, DJ mixes, mixtapes, and remixes at API level for performance
            ("releasetype", releaseTypeParam)
          ]

      let newTorrentsCount = List.length result.newTorrents
      addAttribute artistSpan "torrents.found" (newTorrentsCount, intDecimalT)

      logInfo [fmt|Found {newTorrentsCount} new torrents for artist {artistName}|]

      pure (fromIntegral newTorrentsCount)

  let totalTorrents = totalNewTorrents & map naturalToInteger & sum & (fromInteger :: Integer -> Natural)
  addAttribute span "similar-artists.total-new-torrents" (totalTorrents, naturalDecimalT)

  pure $ label @"processedArtists" (lengthNatural similarArtistIds)

-- | Extract and insert artist data from JSON into the artists table
insertArtists ::
  [T2 "jsonResult" Json.Value "sourceType" Text] ->
  AppTransaction ()
insertArtists jsonInputs = inSpan' "Insert Artists" $ \span -> do
  let allArtists =
        jsonInputs
          & concatMap
            ( \input ->
                case Json.parseValue
                  ( Json.key "artists" $ Json.eachInArray $ do
                      artistId <- Json.key "id" (Json.asIntegral @_ @Int)
                      artistName <- Json.key "name" Json.asText
                      pure (artistId, artistName)
                  )
                  input.jsonResult of
                  Left _ -> []
                  Right artists -> artists
            )

  case allArtists of
    [] -> do
      addAttribute span "artists.count" (0 :: Int, intDecimalT)
      pure ()
    artists -> do
      -- Deduplicate artists by ID, keeping the first name for each ID
      let deduplicatedArtists =
            artists
              & Map.fromList -- Map.fromList keeps first occurrence for duplicate keys
              & Map.toList

      addAttribute span "artists.count" (List.length deduplicatedArtists, intDecimalT)

      -- Insert deduplicated artists
      execute
        [sql|
          INSERT INTO redacted.artists (artist_id, artist_name)
          SELECT * FROM UNNEST(?::integer[], ?::text[])
          ON CONFLICT (artist_id) DO UPDATE SET
            artist_name = EXCLUDED.artist_name,
            updated_at = NOW()
        |]
        ( PGArray (deduplicatedArtists <&> fst),
          PGArray (deduplicatedArtists <&> snd)
        )

      logInfo [fmt|Inserted/updated {List.length deduplicatedArtists} unique artists|]

-- | One-time migration to populate artists table from existing torrent/torrent_group data
populateExistingArtists :: AppTransaction (Label "artistsPopulated" Natural)
populateExistingArtists = inSpan' "Populate Existing Artists" $ \span -> do
  logInfo "Starting migration to populate artists table from existing data..."

  -- Direct insert with proper deduplication by artist_id
  artistCount <-
    execute
      [sql|
      INSERT INTO redacted.artists (artist_id, artist_name)
      SELECT
        artist_id,
        MIN(artist_name) as artist_name  -- Pick one name per artist_id
      FROM (
        SELECT DISTINCT
          (artist_data->>'id')::integer as artist_id,
          artist_data->>'name' as artist_name
        FROM (
          SELECT jsonb_array_elements(full_json_result->'artists') as artist_data
          FROM redacted.torrent_groups
          WHERE full_json_result ?? 'artists'
          UNION ALL
          SELECT jsonb_array_elements(full_json_result->'artists') as artist_data
          FROM redacted.torrents_json
          WHERE full_json_result ?? 'artists'
        ) expanded
        WHERE artist_data ?? 'id' AND artist_data ?? 'name'
      ) all_artists
      GROUP BY artist_id
      ON CONFLICT (artist_id) DO UPDATE SET
        artist_name = EXCLUDED.artist_name,
        updated_at = NOW()
    |]
      ()

  addAttribute span "artists.populated" (artistCount.numberOfRowsAffected, naturalDecimalT)
  logInfo [fmt|Successfully populated {artistCount.numberOfRowsAffected} artists in the artists table|]
  pure $ label @"artistsPopulated" artistCount.numberOfRowsAffected

test :: App ()
test =
  inSpan' "test" $ \span -> do
    redactedApiRequestJson
      span
      (T2 (label @"action" "artist") (label @"actionArgs" [("id", Just "2785")]))
      (Json.asValue)
      <&> Pretty.showPrettyJsonColored
      >>= liftIO . putStderrLn

readTorrentFile :: (MonadIO m, MonadPostgres m) => m ()
readTorrentFile = runTransaction $ do
  torrentBytes <-
    queryWith
      [sql|
    SELECT torrent_file from redacted.torrents where torrent_file is not null limit 10 |]
      ()
      Dec.bytea
  liftIO $ for_ torrentBytes $ \b -> case testBencode b of
    Left e -> do
      Text.IO.putStrLn $ prettyErrorTree e
    Right a -> printPretty a
  liftIO $ print $ lengthNatural torrentBytes

testBencode :: ByteString -> (Either ErrorTree TorrentFile)
testBencode bs = Parse.runParse "cannot parse bencode" (parseBencode >>> bencodeTorrentParser) bs

-- | A torrent file
--
-- from wikipedia:
--
-- * announce—the URL of the high tracker
-- * info—this maps to a dictionary whose keys are very dependent on whether one or more files are being shared:
--   - files—a list of dictionaries each corresponding to a file (only when multiple files are being shared). Each dictionary has the following keys:
--     * length—size of the file in bytes.
--     * path—a list of strings corresponding to subdirectory names, the last of which is the actual file name
--   - length—size of the file in bytes (only when one file is being shared though)
--   - name—suggested filename where the file is to be saved (if one file)/suggested directory name where the files are to be saved (if multiple files)
--   - piece length—number of bytes per piece. This is commonly 28 KiB = 256 KiB = 262,144 B.
--   - pieces—a hash list, i.e., a concatenation of each piece's SHA-1 hash. As SHA-1 returns a 160-bit hash, pieces will be a string whose length is a multiple of 20 bytes. If the torrent contains multiple files, the pieces are formed by concatenating the files in the order they appear in the files dictionary (i.e., all pieces in the torrent are the full piece length except for the last piece, which may be shorter).
data TorrentFile = TorrentFile
  { announce :: Text,
    comment :: Maybe Text,
    createdBy :: Maybe Text,
    creationDate :: Maybe UTCTime,
    encoding :: Maybe Text,
    info :: Info
  }
  deriving stock (Eq, Show)

data Info = Info
  { name :: Text,
    files :: [File],
    pieceLength :: Natural,
    pieces :: ByteString,
    private :: Maybe Bool,
    source :: Maybe Text
  }
  deriving stock (Eq, Show)

data File = File
  { length_ :: Natural,
    path :: [Text]
  }
  deriving stock (Eq, Show)

bencodeTorrentParser :: Parse BEncode TorrentFile
bencodeTorrentParser =
  bencodeDict >>> do
    announce <- mapLookup "announce" bencodeTextLenient
    comment <- mapLookupMay "comment" bencodeTextLenient
    createdBy <- mapLookupMay "created by" bencodeTextLenient
    creationDate <- mapLookupMay "creation date" (bencodeInteger <&> posixSecondsToUTCTime . fromInteger @NominalDiffTime)
    encoding <- mapLookupMay "encoding" bencodeTextLenient
    info <-
      mapLookup "info" $
        bencodeDict >>> do
          name <- mapLookup "name" bencodeTextLenient
          files <-
            mapLookup "files" $
              bencodeList
                >>> ( Parse.multiple $
                        bencodeDict >>> do
                          length_ <- mapLookup "length" bencodeNatural
                          path <- mapLookup "path" $ bencodeList >>> Parse.multiple bencodeTextLenient
                          pure $ File {..}
                    )
          pieceLength <- mapLookup "piece length" bencodeNatural
          pieces <- mapLookup "pieces" bencodeBytes
          private <-
            mapLookupMay "private" bencodeInteger
              <&> fmap
                ( \case
                    0 -> False
                    _ -> True
                )
          source <- mapLookupMay "source" bencodeTextLenient
          pure Info {..}
    pure TorrentFile {..}

getTorrentFilePath ::
  ( HasField "torrentId" dat Int,
    HasField "fileId" dat Natural,
    MonadOtel m,
    MonadPostgres m
  ) =>
  dat ->
  Transaction m (Label "torrent" (Maybe FilePath))
getTorrentFilePath dat = inSpan' "getTorrentFilePath" $ \span -> do
  mTorrent <- getTorrentFile dat
  if
    | Just torrent <- mTorrent -> do
        addAttribute span "torrent.found" True
        let mfile =
              torrent.info.files
                & atMay dat.fileId
                <&> ( \f ->
                        (torrent.info.name & textToString)
                          </> (f.path <&> textToString & foldl' (</>) "")
                    )
        addAttribute span "torrent.file" (toOtelJsonAttr (mfile <&> stringToText))
        pure $ lbl #torrent mfile
    | otherwise -> do
        addAttribute span "torrent.found" False
        pure $ lbl #torrent Nothing

getTorrentCoverArt ::
  ( HasField "torrentId" dat Int
  ) =>
  dat ->
  AppTransaction (Maybe (E2 "coverArtStatic" FilePath "coverArtBytes" (T2 "mimeType" Text "picture" ByteString)))
getTorrentCoverArt dat = inSpan' "getTorrentCoverArt" $ \span -> do
  mTorrent <- getTorrentFile dat
  mTransmissionDownloads <- lift getTransmissionDownloads
  if
    | Nothing <- mTransmissionDownloads -> do
        addAttribute span "transmission.downloads.enabled" False
        pure $ Nothing
    | Just transmission <- mTransmissionDownloads,
      Just torrent <- mTorrent -> do
        addAttribute span "torrent.found" True
        addAttribute span "torrent.name" torrent.info.name
        let mkTorrentPath path =
              (torrent.info.name & textToString)
                </> (path <&> textToString & foldl' (</>) "")
        let mCoverArt =
              torrent.info.files
                -- search for cover only on toplevel
                & mapMaybe
                  ( \f -> case f.path of
                      [fn] -> Just fn
                      _ -> Nothing
                  )
                & findCoverArtInDirectory
                <&> (mkTorrentPath . (: []))
        -- if there’s no cover image file, try to extract the cover from the exif data of the first audio file
        case mCoverArt of
          Just coverArt -> do
            addAttribute span "torrent.cover-type" ("directory-file" :: Text)
            addAttribute span "torrent.cover" (coverArt & stringToText)
            pure $ Just $ e21 #coverArtStatic coverArt
          Nothing -> do
            addAttribute span "torrent.cover-type" ("exif-metadata" :: Text)
            let mfile = torrent.info.files & findAudioFileIds & headMay <&> snd
            case mfile of
              Nothing -> do
                addAttribute span "torrent.cover" (toOtelJsonAttr (Nothing :: Maybe Text))
                pure $ Nothing
              Just file -> do
                -- we read the file directly from the transmission downloads dir
                -- instead of going through the static file server, to speed up exiftool.
                lift (readExiftoolData (transmission.downloadDirectory </> mkTorrentPath file.path))
                  >>= \case
                    Left e -> do
                      recordError span e
                      pure $ Nothing
                    Right exiftoolData -> do
                      exiftoolData
                        & runParse
                          "Cannot parse exiftool cover"
                          ( Json.parseJsonValue
                              ( Json.nth 0 $ Json.asErrorTree $ do
                                  mimeType <- Json.keyMay "PictureMIMEType" Json.asText
                                  picture <- Json.keyMay "Picture" $ Json.asBase64 (lbl #prefix $ Just "base64:")
                                  pure $ t2A #mimeType mimeType #picture picture
                              )
                          )
                        & \case
                          Left e -> do
                            recordErrorTree span e
                            pure $ Nothing
                          Right (Just coverArt) -> do
                            addAttribute span "exiftool.coverArt.mime-type" coverArt.mimeType
                            pure $ Just $ e22 #coverArtBytes coverArt
                          Right Nothing -> do
                            addAttribute span "exiftool.coverArt.found" False
                            pure $ Nothing
    | otherwise -> do
        addAttribute span "torrent.found" False
        pure $ Nothing

findAudioFileIds :: [File] -> [(Natural, File)]
findAudioFileIds files = do
  let extensionList :: [Text] = [".flac", ".mp3", ".opus", ".ogg", ".m4a", ".aac", ".wma", ".wav", ".aiff", ".ape", ".alac", ".mka", ".tta", ".wv", ".pcm", ".dsd", ".dff", ".dsf", ".mpc", ".mpa", ".mp2", ".mp1", ".m4b", ".m4p"]
  files
    & zip [0 ..]
    & mapMaybe
      ( \(idx, f) -> do
          last' <- textToString <$> lastMay f.path
          let ext = Text.toLower $ stringToText $ File.takeExtension last'
          guard $ ext `elem` extensionList
          pure (idx, f)
      )

-- | Read the output of exiftool for the given file.
readExiftoolData :: FilePath -> App (Either Error Json.Value)
readExiftoolData filePath = inSpan' "run exiftool" $ \span -> do
  exiftool <- getTools <&> (.exiftool)
  let args = ["-json", "-all", "-binary", filePath]
  addAttribute span "exiftool.cmd" $
    exiftool.toolPath : args & map stringToText & prettyArgsForBash
  withRunInIO $ \_runInIO -> do
    readProcessStdout (proc exiftool.toolPath args)
      & ifIOError "Cannot run exiftool"
      <&> ( \ei ->
              ei >>= \(_ex, stdout) ->
                Json.eitherDecode' stdout
                  & first (\e -> [fmt|Cannot decode exiftool stdout as json: {e}|])
          )

getTorrentFile ::
  ( MonadPostgres m,
    HasField "torrentId" dat Int
  ) =>
  dat ->
  (Transaction m (Maybe TorrentFile))
getTorrentFile dat = do
  queryFirstRowWithMaybe
    [fmt|
          SELECT torrent_file FROM redacted.torrents
          WHERE torrent_file IS NOT NULL
          AND torrent_id = ?::int
        |]
    ( Only $ (dat.torrentId :: Int)
    )
    ( Dec.parse @(Postgres.Binary ByteString)
        (lmap (Postgres.fromBinary) parseBencode >>> bencodeTorrentParser)
    )

-- | Try to find something that looks like cover art in the given list of file names.
findCoverArtInDirectory :: [Text] -> Maybe Text
findCoverArtInDirectory fileNames = do
  let coverArts = mapMaybe (\f -> (f,) <$> (isCoverArt f)) fileNames
  -- filter by priority, take the cover art with lowest priority
  coverArts & List.sortOn snd & headMay <&> fst
  where
    isCoverArt :: Text -> Maybe Natural
    isCoverArt t = case Text.toLower t of
      "cover.jpg" -> Just 1
      "cover.jpeg" -> Just 1
      "cover.png" -> Just 1
      "folder.jpg" -> Just 1
      "folder.jpeg" -> Just 1
      "folder.png" -> Just 1
      -- now we check for subset and prefer “front” over “back”
      other ->
        if
          | Text.isInfixOf "cover" other,
            Text.isInfixOf "front" other ->
              Just 2
          | Text.isInfixOf "cover" other -> Just 3
          -- anything that is png or jpg
          | Text.isSuffixOf ".jpg" other -> Just 4
          | Text.isSuffixOf ".jpeg" other -> Just 4
          | Text.isSuffixOf ".png" other -> Just 4
          | otherwise -> Nothing