patent 0.7.0

A prior-art search for your code ideas — has this dev tool already been shipped?
Documentation
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
//! Integration tests for the source adapters.
//!
//! Each source is exercised against a `wiremock` server serving canned registry
//! responses — no live network in CI. Filled in alongside M1/M2.

// M1: crates.io parsing via wiremock.
// M2: each remaining source + dedup.
use patent::model::{Match, Query, Source as SourceId};
use patent::sources::artifacthub::ArtifactHub;
use patent::sources::aur::Aur;
use patent::sources::crates_io::CratesIo;
use patent::sources::docker_hub::DockerHub;
use patent::sources::github::GitHub;
use patent::sources::go::GoPkgDev;
use patent::sources::hacker_news::HackerNews;
use patent::sources::hex::Hex;
use patent::sources::homebrew::Homebrew;
use patent::sources::maven::Maven;
use patent::sources::npm::Npm;
use patent::sources::nuget::NuGet;
use patent::sources::packagist::Packagist;
use patent::sources::pypi::PyPI;
use patent::sources::rubygems::RubyGems;
use patent::sources::vscode::VsCodeMarketplace;
use patent::sources::{dedup, search_sources, SearchOutcome, SourceAdapter};
use reqwest::Client;
use serde_json::json;
use wiremock::matchers::{header_exists, method, path, query_param, query_param_is_missing};
use wiremock::{Mock, MockServer, ResponseTemplate};

fn test_client() -> reqwest::Client {
    reqwest::Client::builder()
        .user_agent(concat!(
            "patent/",
            env!("CARGO_PKG_VERSION"),
            " (prior-art search; https://github.com/r14dd/patent)"
        ))
        .build()
        .unwrap()
}

/// A query whose keywords join to the string we assert on the wire.
fn query() -> Query {
    Query {
        idea: "a fast async runtime for rust".to_string(),
        keywords: vec!["async".to_string(), "runtime".to_string()],
    }
}

/// Build a `CratesIo` whose requests are aimed at the mock server.
fn source_for(server: &MockServer) -> CratesIo {
    CratesIo::with_base_url(test_client(), server.uri())
}

/// A canonical crates.io search payload with two hits.
fn two_crate_body() -> serde_json::Value {
    json!({
        "crates": [
            {
                "name": "tokio",
                "description": "An event-driven, non-blocking I/O platform.",
                "downloads": 950_000_000_u64,
                "max_version": "1.40.0",
                "repository": "https://github.com/tokio-rs/tokio"
            },
            {
                "name": "async-std",
                "description": "Async version of the Rust standard library.",
                "downloads": 45_000_000_u64,
                "max_version": "1.13.0",
                "repository": "https://github.com/async-rs/async-std"
            }
        ],
        "meta": { "total": 2 }
    })
}

#[tokio::test]
async fn crates_io_id_is_crates_io() {
    let src = CratesIo::with_base_url(reqwest::Client::new(), "https://crates.io".to_string());
    assert_eq!(src.id(), SourceId::CratesIo);
}

#[tokio::test]
async fn crates_io_maps_results_into_matches() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(ResponseTemplate::new(200).set_body_json(two_crate_body()))
        .mount(&server)
        .await;

    let matches = source_for(&server).search(&query()).await.unwrap();

    assert_eq!(matches.len(), 2);

    let tokio = &matches[0];
    assert_eq!(tokio.name, "tokio");
    assert_eq!(tokio.source, SourceId::CratesIo);
    assert_eq!(
        tokio.description,
        "An event-driven, non-blocking I/O platform."
    );
    assert_eq!(tokio.popularity, Some(950_000_000));
    // similarity is filled in later by rank.rs; sources leave it at 0.0.
    assert_eq!(tokio.similarity, 0.0);

    let async_std = &matches[1];
    assert_eq!(async_std.name, "async-std");
    assert_eq!(async_std.popularity, Some(45_000_000));
}

#[tokio::test]
async fn crates_io_links_use_the_configured_base_url() {
    // The result `url` field is built from `self.base_url`, so a request
    // served by a mock server (or a crates.io mirror) should surface links
    // against the same host we queried, not the hard-coded production host.
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(ResponseTemplate::new(200).set_body_json(two_crate_body()))
        .mount(&server)
        .await;

    let matches = source_for(&server).search(&query()).await.unwrap();

    assert_eq!(matches[0].url, format!("{}/crates/tokio", server.uri()));
    assert_eq!(matches[1].url, format!("{}/crates/async-std", server.uri()));
}

#[tokio::test]
async fn crates_io_sends_joined_keywords_as_query_and_a_user_agent() {
    let server = MockServer::start().await;
    // The mock only matches if `q` is the space-joined keywords AND a
    // User-Agent header is present (crates.io rejects requests without one).
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .and(query_param("q", "async runtime"))
        .and(header_exists("user-agent"))
        .respond_with(ResponseTemplate::new(200).set_body_json(two_crate_body()))
        .expect(1)
        .mount(&server)
        .await;

    let matches = source_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches.len(), 2);
    // `expect(1)` is verified on server drop: the request matched our assertions.
}

#[tokio::test]
async fn crates_io_user_agent_contains_correct_github_handle() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(ResponseTemplate::new(200).set_body_json(two_crate_body()))
        .mount(&server)
        .await;

    source_for(&server).search(&query()).await.unwrap();

    let requests = server.received_requests().await.unwrap();
    let ua = requests[0]
        .headers
        .get("user-agent")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    assert!(
        ua.contains("r14dd/patent"),
        "expected 'r14dd/patent' in User-Agent, got: {ua}"
    );
}

#[tokio::test]
async fn crates_io_null_description_becomes_empty_string() {
    let server = MockServer::start().await;
    let body = json!({
        "crates": [
            { "name": "mystery-crate", "description": null, "downloads": 7 }
        ],
        "meta": { "total": 1 }
    });
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    let matches = source_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches.len(), 1);
    assert_eq!(matches[0].description, "");
}

#[tokio::test]
async fn crates_io_missing_downloads_becomes_none() {
    let server = MockServer::start().await;
    let body = json!({
        "crates": [
            { "name": "obscure", "description": "no download count here" }
        ],
        "meta": { "total": 1 }
    });
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    let matches = source_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches.len(), 1);
    assert_eq!(matches[0].popularity, None);
}

#[tokio::test]
async fn crates_io_empty_results_is_ok_not_error() {
    let server = MockServer::start().await;
    let body = json!({ "crates": [], "meta": { "total": 0 } });
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    let matches = source_for(&server).search(&query()).await.unwrap();
    assert!(matches.is_empty());
}

#[tokio::test]
async fn crates_io_server_error_is_propagated() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;

    let result = source_for(&server).search(&query()).await;
    assert!(result.is_err(), "a 5xx response must surface as an error");
}

#[tokio::test]
async fn crates_io_malformed_body_is_propagated() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(ResponseTemplate::new(200).set_body_string("not json at all"))
        .mount(&server)
        .await;

    let result = source_for(&server).search(&query()).await;
    assert!(
        result.is_err(),
        "an unparseable body must surface as an error"
    );
}

// ---------------------------------------------------------------------------
// GitHub
// ---------------------------------------------------------------------------

fn github_for(server: &MockServer) -> GitHub {
    GitHub::with_base_url(test_client(), server.uri())
}

fn github_body() -> serde_json::Value {
    json!({
        "total_count": 2,
        "items": [
            {
                "full_name": "tokio-rs/tokio",
                "description": "An async runtime for Rust.",
                "html_url": "https://github.com/tokio-rs/tokio",
                "stargazers_count": 27000
            },
            {
                "full_name": "async-rs/async-std",
                "description": "Async std library.",
                "html_url": "https://github.com/async-rs/async-std",
                "stargazers_count": 4000
            }
        ]
    })
}

#[tokio::test]
async fn github_id_is_github() {
    let src = GitHub::with_base_url(reqwest::Client::new(), "https://api.github.com".to_string());
    assert_eq!(src.id(), SourceId::GitHub);
}

#[tokio::test]
async fn github_maps_repositories_into_matches() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/search/repositories"))
        .respond_with(ResponseTemplate::new(200).set_body_json(github_body()))
        .mount(&server)
        .await;

    let matches = github_for(&server).search(&query()).await.unwrap();

    assert_eq!(matches.len(), 2);
    let first = &matches[0];
    assert_eq!(first.name, "tokio-rs/tokio");
    assert_eq!(first.source, SourceId::GitHub);
    assert_eq!(first.url, "https://github.com/tokio-rs/tokio");
    assert_eq!(first.description, "An async runtime for Rust.");
    assert_eq!(first.popularity, Some(27000));
    assert_eq!(first.similarity, 0.0);
}

#[tokio::test]
async fn github_sends_query_and_user_agent() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/search/repositories"))
        .and(query_param("q", "async runtime in:description,readme"))
        // #31: no `sort` param (GitHub defaults to best-match relevance, not
        // raw stars) and a wider page so low-star on-topic repos can surface.
        .and(query_param_is_missing("sort"))
        .and(query_param("per_page", "50"))
        .and(header_exists("user-agent"))
        .respond_with(ResponseTemplate::new(200).set_body_json(github_body()))
        .expect(1)
        .mount(&server)
        .await;

    let matches = github_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches.len(), 2);
}

#[tokio::test]
async fn github_null_description_is_filtered_out() {
    let server = MockServer::start().await;
    let body = json!({
        "total_count": 1,
        "items": [
            { "full_name": "x/y", "description": null,
              "html_url": "https://github.com/x/y", "stargazers_count": 1 }
        ]
    });
    Mock::given(method("GET"))
        .and(path("/search/repositories"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    let matches = github_for(&server).search(&query()).await.unwrap();
    assert!(matches.is_empty());
}

#[tokio::test]
async fn github_empty_results_is_ok() {
    let server = MockServer::start().await;
    let body = json!({ "total_count": 0, "items": [] });
    Mock::given(method("GET"))
        .and(path("/search/repositories"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    assert!(github_for(&server)
        .search(&query())
        .await
        .unwrap()
        .is_empty());
}

#[tokio::test]
async fn github_server_error_is_propagated() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/search/repositories"))
        .respond_with(ResponseTemplate::new(503))
        .mount(&server)
        .await;

    assert!(github_for(&server).search(&query()).await.is_err());
}

#[tokio::test]
async fn github_401_with_token_returns_auth_error() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/search/repositories"))
        .respond_with(ResponseTemplate::new(401))
        .mount(&server)
        .await;

    let src = GitHub::with_base_url_and_token(
        reqwest::Client::new(),
        server.uri(),
        "bad-token".to_string(),
    );
    let err = src.search(&query()).await.unwrap_err();
    let msg = err.to_string().to_lowercase();
    assert!(
        msg.contains("401") || msg.contains("token") || msg.contains("invalid"),
        "expected auth error, got: {err}"
    );
}

#[tokio::test]
async fn github_403_with_token_returns_rate_limit_error() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/search/repositories"))
        .respond_with(ResponseTemplate::new(403).append_header("X-RateLimit-Remaining", "0"))
        .mount(&server)
        .await;

    let src = GitHub::with_base_url_and_token(
        reqwest::Client::new(),
        server.uri(),
        "valid-token".to_string(),
    );
    let err = src.search(&query()).await.unwrap_err();
    assert!(
        err.to_string().to_lowercase().contains("rate limit"),
        "expected rate limit error, got: {err}"
    );
}

#[tokio::test]
async fn github_403_without_token_returns_rate_limit_hint() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/search/repositories"))
        .respond_with(ResponseTemplate::new(403))
        .mount(&server)
        .await;

    let err = github_for(&server).search(&query()).await.unwrap_err();
    assert!(
        err.to_string().contains("GITHUB_TOKEN"),
        "expected GITHUB_TOKEN hint, got: {err}"
    );
}

// ---------------------------------------------------------------------------
// npm
// ---------------------------------------------------------------------------

fn npm_for(server: &MockServer) -> Npm {
    Npm::with_base_url(reqwest::Client::new(), server.uri())
}

fn npm_body() -> serde_json::Value {
    json!({
        "total": 2,
        "objects": [
            { "package": { "name": "express", "description": "Fast web framework." } },
            { "package": { "name": "koa", "description": "Next-gen web framework." } }
        ]
    })
}

#[tokio::test]
async fn npm_id_is_npm() {
    let src = Npm::with_base_url(
        reqwest::Client::new(),
        "https://registry.npmjs.org".to_string(),
    );
    assert_eq!(src.id(), SourceId::Npm);
}

#[tokio::test]
async fn npm_maps_packages_into_matches() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/-/v1/search"))
        .respond_with(ResponseTemplate::new(200).set_body_json(npm_body()))
        .mount(&server)
        .await;

    let matches = npm_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches.len(), 2);
    let first = &matches[0];
    assert_eq!(first.name, "express");
    assert_eq!(first.source, SourceId::Npm);
    assert_eq!(first.url, "https://www.npmjs.com/package/express");
    assert_eq!(first.description, "Fast web framework.");
    // npm search exposes no integer download count.
    assert_eq!(first.popularity, None);
    assert_eq!(first.similarity, 0.0);
}

#[tokio::test]
async fn npm_sends_text_query_param() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/-/v1/search"))
        .and(query_param("text", "a fast async runtime for rust"))
        .respond_with(ResponseTemplate::new(200).set_body_json(npm_body()))
        .expect(1)
        .mount(&server)
        .await;

    assert_eq!(npm_for(&server).search(&query()).await.unwrap().len(), 2);
}

#[tokio::test]
async fn npm_missing_description_becomes_empty() {
    let server = MockServer::start().await;
    let body = json!({ "total": 1, "objects": [ { "package": { "name": "bare" } } ] });
    Mock::given(method("GET"))
        .and(path("/-/v1/search"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    let matches = npm_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches[0].description, "");
}

#[tokio::test]
async fn npm_empty_results_is_ok() {
    let server = MockServer::start().await;
    let body = json!({ "total": 0, "objects": [] });
    Mock::given(method("GET"))
        .and(path("/-/v1/search"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    assert!(npm_for(&server).search(&query()).await.unwrap().is_empty());
}

#[tokio::test]
async fn npm_server_error_is_propagated() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/-/v1/search"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;

    assert!(npm_for(&server).search(&query()).await.is_err());
}

// ---------------------------------------------------------------------------
// PyPI (HTML scrape)
// ---------------------------------------------------------------------------

fn pypi_for(server: &MockServer) -> PyPI {
    PyPI::with_base_url(reqwest::Client::new(), server.uri())
}

fn pypi_html() -> String {
    r#"<!doctype html><html><body>
      <ul>
        <li>
          <a class="package-snippet" href="/project/requests/">
            <h3 class="package-snippet__title">
              <span class="package-snippet__name">requests</span>
              <span class="package-snippet__version">2.31.0</span>
            </h3>
            <p class="package-snippet__description">Python HTTP for Humans.</p>
          </a>
        </li>
        <li>
          <a class="package-snippet" href="/project/httpx/">
            <h3 class="package-snippet__title">
              <span class="package-snippet__name">httpx</span>
              <span class="package-snippet__version">0.27.0</span>
            </h3>
            <p class="package-snippet__description">A next-gen HTTP client.</p>
          </a>
        </li>
      </ul>
    </body></html>"#
        .to_string()
}

#[tokio::test]
async fn pypi_id_is_pypi() {
    let src = PyPI::with_base_url(reqwest::Client::new(), "https://pypi.org".to_string());
    assert_eq!(src.id(), SourceId::PyPI);
}

#[tokio::test]
async fn pypi_scrapes_packages_into_matches() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/search/"))
        .respond_with(ResponseTemplate::new(200).set_body_string(pypi_html()))
        .mount(&server)
        .await;

    let matches = pypi_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches.len(), 2);
    let first = &matches[0];
    assert_eq!(first.name, "requests");
    assert_eq!(first.source, SourceId::PyPI);
    // The URL is built from the (mock) base_url + the relative href.
    assert!(first.url.ends_with("/project/requests/"));
    assert_eq!(first.description, "Python HTTP for Humans.");
    assert_eq!(first.popularity, None);
    assert_eq!(first.similarity, 0.0);

    assert_eq!(matches[1].name, "httpx");
    assert!(matches[1].url.ends_with("/project/httpx/"));
}

#[tokio::test]
async fn pypi_sends_q_query_param() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/search/"))
        .and(query_param("q", "async runtime"))
        .respond_with(ResponseTemplate::new(200).set_body_string(pypi_html()))
        .expect(1)
        .mount(&server)
        .await;

    assert_eq!(pypi_for(&server).search(&query()).await.unwrap().len(), 2);
}

#[tokio::test]
async fn pypi_no_snippets_is_ok_empty() {
    let server = MockServer::start().await;
    let html = "<!doctype html><html><body><p>No results.</p></body></html>";
    Mock::given(method("GET"))
        .and(path("/search/"))
        .respond_with(ResponseTemplate::new(200).set_body_string(html))
        .mount(&server)
        .await;

    assert!(pypi_for(&server).search(&query()).await.unwrap().is_empty());
}

#[tokio::test]
async fn pypi_server_error_is_propagated() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/search/"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;

    assert!(pypi_for(&server).search(&query()).await.is_err());
}

// ---------------------------------------------------------------------------
// Hacker News (Algolia)
// ---------------------------------------------------------------------------

fn hn_for(server: &MockServer) -> HackerNews {
    HackerNews::with_base_url(reqwest::Client::new(), server.uri())
}

fn hn_body() -> serde_json::Value {
    json!({
        "hits": [
            {
                "title": "Show HN: Tokio, an async runtime",
                "story_text": "We built an async runtime.",
                "url": "https://tokio.rs",
                "objectID": "12345",
                "points": 320
            },
            {
                "title": "Async Rust explained",
                "story_text": null,
                "url": null,
                "objectID": "67890",
                "points": 88
            }
        ]
    })
}

#[tokio::test]
async fn hn_id_is_hacker_news() {
    let src =
        HackerNews::with_base_url(reqwest::Client::new(), "https://hn.algolia.com".to_string());
    assert_eq!(src.id(), SourceId::HackerNews);
}

#[tokio::test]
async fn hn_maps_hits_into_matches() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/search"))
        .respond_with(ResponseTemplate::new(200).set_body_json(hn_body()))
        .mount(&server)
        .await;

    let matches = hn_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches.len(), 2);
    let first = &matches[0];
    assert_eq!(first.name, "Show HN: Tokio, an async runtime");
    assert_eq!(first.source, SourceId::HackerNews);
    // Canonical HN URL is the discussion item, not the (optional) outbound link.
    assert_eq!(first.url, "https://news.ycombinator.com/item?id=12345");
    assert_eq!(first.description, "We built an async runtime.");
    assert_eq!(first.popularity, Some(320));
    assert_eq!(first.similarity, 0.0);
}

#[tokio::test]
async fn hn_null_story_text_falls_back_to_title() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/search"))
        .respond_with(ResponseTemplate::new(200).set_body_json(hn_body()))
        .mount(&server)
        .await;

    let matches = hn_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches[1].description, "Async Rust explained");
    assert_eq!(matches[1].url, "https://news.ycombinator.com/item?id=67890");
    assert_eq!(matches[1].popularity, Some(88));
}

#[tokio::test]
async fn hn_sends_query_param() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/search"))
        .and(query_param("query", "a fast async runtime for rust"))
        .respond_with(ResponseTemplate::new(200).set_body_json(hn_body()))
        .expect(1)
        .mount(&server)
        .await;

    assert_eq!(hn_for(&server).search(&query()).await.unwrap().len(), 2);
}

#[tokio::test]
async fn hn_empty_hits_is_ok() {
    let server = MockServer::start().await;
    let body = json!({ "hits": [] });
    Mock::given(method("GET"))
        .and(path("/api/v1/search"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    assert!(hn_for(&server).search(&query()).await.unwrap().is_empty());
}

#[tokio::test]
async fn hn_server_error_is_propagated() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/search"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;

    assert!(hn_for(&server).search(&query()).await.is_err());
}

#[tokio::test]
async fn hn_strips_html_from_story_text() {
    let server = MockServer::start().await;
    let body = json!({
        "hits": [{
            "title": "Show HN: Something",
            "story_text": "<p>A tool that <b>does</b> things.</p>",
            "objectID": "99999",
            "points": 10
        }]
    });
    Mock::given(method("GET"))
        .and(path("/api/v1/search"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    let matches = hn_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches[0].description, "A tool that does things.");
}

#[tokio::test]
async fn hn_bare_ampersand_does_not_eat_remaining_text() {
    // A bare '&' with no closing ';' must be emitted as a literal and must NOT
    // consume the text that follows it.
    let server = MockServer::start().await;
    let body = json!({
        "hits": [{
            "title": "Show HN: Something",
            "story_text": "fast tool for C & C++",
            "objectID": "11111",
            "points": 5
        }]
    });
    Mock::given(method("GET"))
        .and(path("/api/v1/search"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    let matches = hn_for(&server).search(&query()).await.unwrap();
    assert_eq!(
        matches[0].description, "fast tool for C & C++",
        "text after bare '&' must not be eaten"
    );
}

// ---------------------------------------------------------------------------
// Fan-out + dedup
// ---------------------------------------------------------------------------

/// A source that always fails — stands in for an unreachable registry.
struct FailingSource;

#[async_trait::async_trait]
impl SourceAdapter for FailingSource {
    fn id(&self) -> SourceId {
        SourceId::PyPI
    }
    async fn search(&self, _query: &Query) -> patent::Result<Vec<Match>> {
        Err(patent::Error::Parse("simulated failure".to_string()))
    }
}

fn sample_match(name: &str, url: &str) -> Match {
    Match {
        name: name.to_string(),
        source: SourceId::CratesIo,
        url: url.to_string(),
        description: String::new(),
        popularity: None,
        similarity: 0.0,
    }
}

#[test]
fn dedup_removes_same_url_keeping_first_and_order() {
    let input = vec![
        sample_match("a", "https://x/a"),
        sample_match("b", "https://x/b"),
        sample_match("a-dup", "https://x/a"), // same URL as the first
        sample_match("c", "https://x/c"),
    ];
    let out = dedup(input);
    let urls: Vec<&str> = out.iter().map(|m| m.url.as_str()).collect();
    assert_eq!(urls, ["https://x/a", "https://x/b", "https://x/c"]);
    // First occurrence is kept, not the later duplicate.
    assert_eq!(out[0].name, "a");
}

#[test]
fn dedup_keeps_distinct_urls() {
    let input = vec![
        sample_match("a", "https://x/a"),
        sample_match("b", "https://x/b"),
    ];
    assert_eq!(dedup(input).len(), 2);
}

#[tokio::test]
async fn search_sources_skips_failing_sources() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(ResponseTemplate::new(200).set_body_json(two_crate_body()))
        .mount(&server)
        .await;

    let sources: Vec<Box<dyn SourceAdapter>> = vec![
        Box::new(FailingSource),
        Box::new(CratesIo::with_base_url(
            reqwest::Client::new(),
            server.uri(),
        )),
    ];

    // The failing source is skipped, never fatal: we still get the crates,
    // and the failed source is reported so reduced coverage is visible.
    let SearchOutcome {
        matches,
        reached,
        failed,
    } = search_sources(&sources, &query()).await;
    assert_eq!(matches.len(), 2);
    assert!(matches.iter().all(|m| m.source == SourceId::CratesIo));
    assert_eq!(reached, vec![SourceId::CratesIo]);
    assert_eq!(failed, vec![SourceId::PyPI]);
}

#[tokio::test]
async fn search_sources_dedups_across_sources() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/crates"))
        .respond_with(ResponseTemplate::new(200).set_body_json(two_crate_body()))
        .mount(&server)
        .await;

    // Two identical crates.io sources -> overlapping URLs -> deduped to 2.
    let sources: Vec<Box<dyn SourceAdapter>> = vec![
        Box::new(CratesIo::with_base_url(
            reqwest::Client::new(),
            server.uri(),
        )),
        Box::new(CratesIo::with_base_url(
            reqwest::Client::new(),
            server.uri(),
        )),
    ];

    let SearchOutcome {
        matches, reached, ..
    } = search_sources(&sources, &query()).await;
    assert_eq!(matches.len(), 2);
    assert_eq!(reached.len(), 2);
}

#[tokio::test]
async fn search_sources_empty_when_all_fail() {
    let sources: Vec<Box<dyn SourceAdapter>> =
        vec![Box::new(FailingSource), Box::new(FailingSource)];
    let SearchOutcome {
        matches,
        reached,
        failed,
    } = search_sources(&sources, &query()).await;
    assert!(matches.is_empty());
    assert!(reached.is_empty());
    assert_eq!(failed.len(), 2, "both failing sources must be reported");
}

// ---------------------------------------------------------------------------
// Go (pkg.go.dev HTML scrape)
// ---------------------------------------------------------------------------

fn go_html() -> String {
    r#"<!doctype html><html><body>
      <div class="SearchSnippet">
        <a href="/github.com/spf13/cobra">cobra</a>
        <p class="SearchSnippet-synopsis">A Commander for modern Go CLI interactions.</p>
      </div>
    </body></html>"#
        .to_string()
}

#[tokio::test]
async fn go_id_is_go() {
    let src = GoPkgDev::with_base_url(reqwest::Client::new(), "https://pkg.go.dev".to_string());
    assert_eq!(src.id(), SourceId::Go);
}

#[tokio::test]
async fn go_scrapes_packages_into_matches() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/search"))
        .and(query_param("q", "async runtime"))
        .respond_with(ResponseTemplate::new(200).set_body_string(go_html()))
        .mount(&server)
        .await;

    let src = GoPkgDev::with_base_url(reqwest::Client::new(), server.uri());
    let matches = src.search(&query()).await.unwrap();
    assert_eq!(matches.len(), 1);
    assert_eq!(matches[0].name, "cobra");
    assert_eq!(matches[0].source, SourceId::Go);
    assert!(matches[0].url.ends_with("/github.com/spf13/cobra"));
    assert_eq!(
        matches[0].description,
        "A Commander for modern Go CLI interactions."
    );
}

#[tokio::test]
async fn go_server_error_is_propagated() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/search"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;

    let src = GoPkgDev::with_base_url(reqwest::Client::new(), server.uri());
    assert!(src.search(&query()).await.is_err());
}

// ---------------------------------------------------------------------------
// Maven Central (Solr JSON)
// ---------------------------------------------------------------------------

fn maven_body() -> serde_json::Value {
    json!({
        "response": {
            "docs": [
                { "g": "com.google.guava", "a": "guava", "versionCount": 50 }
            ]
        }
    })
}

#[tokio::test]
async fn maven_id_is_maven() {
    let src = Maven::with_base_url(
        reqwest::Client::new(),
        "https://search.maven.org".to_string(),
    );
    assert_eq!(src.id(), SourceId::Maven);
}

#[tokio::test]
async fn maven_maps_artifacts_into_matches() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/solrsearch/select"))
        .and(query_param("q", "async runtime"))
        .respond_with(ResponseTemplate::new(200).set_body_json(maven_body()))
        .mount(&server)
        .await;

    let src = Maven::with_base_url(reqwest::Client::new(), server.uri());
    let matches = src.search(&query()).await.unwrap();
    assert_eq!(matches.len(), 1);
    assert_eq!(matches[0].name, "com.google.guava:guava");
    assert_eq!(matches[0].source, SourceId::Maven);
    assert_eq!(
        matches[0].url,
        "https://central.sonatype.com/artifact/com.google.guava/guava"
    );
    // Maven Central's Solr response has no download / star / rank field that
    // is comparable to the popularity signals used by the other sources, so
    // popularity is intentionally left as None.
    assert_eq!(matches[0].popularity, None);
    assert_eq!(matches[0].description, "guava");
}

#[tokio::test]
async fn maven_ignores_version_count_when_mapping_results() {
    // versionCount is still a valid Solr field; the source must not surface
    // it as a popularity signal, because that would mislead the TUI's
    // popularity column.
    let server = MockServer::start().await;
    let body = json!({
        "response": {
            "docs": [
                { "g": "com.google.guava", "a": "guava", "versionCount": 999_999 }
            ]
        }
    });
    Mock::given(method("GET"))
        .and(path("/solrsearch/select"))
        .and(query_param("q", "async runtime"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    let src = Maven::with_base_url(reqwest::Client::new(), server.uri());
    let matches = src.search(&query()).await.unwrap();
    assert_eq!(matches[0].popularity, None);
}

#[tokio::test]
async fn maven_server_error_is_propagated() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/solrsearch/select"))
        .respond_with(ResponseTemplate::new(503))
        .mount(&server)
        .await;

    let src = Maven::with_base_url(reqwest::Client::new(), server.uri());
    assert!(src.search(&query()).await.is_err());
}

// ---------------------------------------------------------------------------
// NuGet (.NET)
// ---------------------------------------------------------------------------

fn nuget_body() -> serde_json::Value {
    json!({
        "data": [
            { "id": "Newtonsoft.Json", "description": "JSON framework for .NET", "totalDownloads": 100 },
            { "id": "NoDescription", "description": "", "totalDownloads": 1 }
        ]
    })
}

#[tokio::test]
async fn nuget_id_is_nuget() {
    let src = NuGet::with_search_url(
        reqwest::Client::new(),
        "https://azuresearch-usnc.nuget.org".to_string(),
    );
    assert_eq!(src.id(), SourceId::NuGet);
}

#[tokio::test]
async fn nuget_maps_packages_and_filters_empty_descriptions() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/query"))
        .and(query_param("q", "async runtime"))
        .respond_with(ResponseTemplate::new(200).set_body_json(nuget_body()))
        .mount(&server)
        .await;

    let src = NuGet::with_search_url(reqwest::Client::new(), server.uri());
    let matches = src.search(&query()).await.unwrap();
    // The empty-description package is filtered out.
    assert_eq!(matches.len(), 1);
    assert_eq!(matches[0].name, "Newtonsoft.Json");
    assert_eq!(matches[0].source, SourceId::NuGet);
    assert_eq!(
        matches[0].url,
        "https://www.nuget.org/packages/Newtonsoft.Json"
    );
    assert_eq!(matches[0].popularity, Some(100));
}

#[tokio::test]
async fn nuget_server_error_is_propagated() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/query"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;

    let src = NuGet::with_search_url(reqwest::Client::new(), server.uri());
    assert!(src.search(&query()).await.is_err());
}

// ---------------------------------------------------------------------------
// RubyGems
// ---------------------------------------------------------------------------

fn rubygems_body() -> serde_json::Value {
    json!([
        {
            "name": "rails",
            "info": "Full-stack web framework",
            "project_uri": "https://rubygems.org/gems/rails",
            "downloads": 999
        }
    ])
}

#[tokio::test]
async fn rubygems_id_is_rubygems() {
    let src = RubyGems::with_base_url(reqwest::Client::new(), "https://rubygems.org".to_string());
    assert_eq!(src.id(), SourceId::RubyGems);
}

#[tokio::test]
async fn rubygems_maps_gems_into_matches() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/search.json"))
        .and(query_param("query", "async runtime"))
        .respond_with(ResponseTemplate::new(200).set_body_json(rubygems_body()))
        .mount(&server)
        .await;

    let src = RubyGems::with_base_url(reqwest::Client::new(), server.uri());
    let matches = src.search(&query()).await.unwrap();
    assert_eq!(matches.len(), 1);
    assert_eq!(matches[0].name, "rails");
    assert_eq!(matches[0].source, SourceId::RubyGems);
    assert_eq!(matches[0].url, "https://rubygems.org/gems/rails");
    assert_eq!(matches[0].description, "Full-stack web framework");
    assert_eq!(matches[0].popularity, Some(999));
}

#[tokio::test]
async fn rubygems_server_error_is_propagated() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/search.json"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;

    let src = RubyGems::with_base_url(reqwest::Client::new(), server.uri());
    assert!(src.search(&query()).await.is_err());
}

// ---------------------------------------------------------------------------
// Docker Hub
// ---------------------------------------------------------------------------

fn docker_body() -> serde_json::Value {
    json!({
        "results": [
            { "repo_name": "library/nginx", "short_description": "Official nginx image", "star_count": 200 },
            { "repo_name": "no/desc", "short_description": "", "star_count": 1 }
        ]
    })
}

#[tokio::test]
async fn docker_hub_id_is_docker_hub() {
    let src =
        DockerHub::with_base_url(reqwest::Client::new(), "https://hub.docker.com".to_string());
    assert_eq!(src.id(), SourceId::DockerHub);
}

#[tokio::test]
async fn docker_hub_maps_repos_and_filters_empty_descriptions() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v2/search/repositories/"))
        .and(query_param("query", "async runtime"))
        .respond_with(ResponseTemplate::new(200).set_body_json(docker_body()))
        .mount(&server)
        .await;

    let src = DockerHub::with_base_url(reqwest::Client::new(), server.uri());
    let matches = src.search(&query()).await.unwrap();
    assert_eq!(matches.len(), 1);
    assert_eq!(matches[0].name, "library/nginx");
    assert_eq!(matches[0].source, SourceId::DockerHub);
    assert_eq!(matches[0].url, "https://hub.docker.com/r/library/nginx");
    assert_eq!(matches[0].popularity, Some(200));
}

#[tokio::test]
async fn docker_hub_server_error_is_propagated() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v2/search/repositories/"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;

    let src = DockerHub::with_base_url(reqwest::Client::new(), server.uri());
    assert!(src.search(&query()).await.is_err());
}

// ---------------------------------------------------------------------------
// VS Code Marketplace (POST gallery query)
// ---------------------------------------------------------------------------

fn vscode_body() -> serde_json::Value {
    json!({
        "results": [{
            "extensions": [{
                "publisher": { "publisherName": "rust-lang" },
                "extensionName": "rust-analyzer",
                "displayName": "rust-analyzer",
                "shortDescription": "Rust language support",
                "statistics": [{ "statisticName": "install", "value": 12345.0 }]
            }]
        }]
    })
}

#[tokio::test]
async fn vscode_id_is_vscode() {
    let src = VsCodeMarketplace::with_base_url(
        reqwest::Client::new(),
        "https://marketplace.visualstudio.com".to_string(),
    );
    assert_eq!(src.id(), SourceId::VsCodeMarketplace);
}

#[tokio::test]
async fn vscode_maps_extensions_into_matches() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/_apis/public/gallery/extensionquery"))
        .respond_with(ResponseTemplate::new(200).set_body_json(vscode_body()))
        .mount(&server)
        .await;

    let src = VsCodeMarketplace::with_base_url(reqwest::Client::new(), server.uri());
    let matches = src.search(&query()).await.unwrap();
    assert_eq!(matches.len(), 1);
    assert_eq!(matches[0].name, "rust-analyzer");
    assert_eq!(matches[0].source, SourceId::VsCodeMarketplace);
    assert_eq!(
        matches[0].url,
        "https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer"
    );
    assert_eq!(matches[0].description, "Rust language support");
    assert_eq!(matches[0].popularity, Some(12345));
}

#[tokio::test]
async fn vscode_server_error_is_propagated() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/_apis/public/gallery/extensionquery"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;

    let src = VsCodeMarketplace::with_base_url(reqwest::Client::new(), server.uri());
    assert!(src.search(&query()).await.is_err());
}

//homebrew
#[tokio::test]
async fn test_homebrew_happy_path() {
    let mock_server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/formula.json"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
            {
                "name": "ripgrep",
                "desc": "Search tool like grep and The Silver Searcher",
                "homepage": "https://github.com/BurntSushi/ripgrep"
            }
        ])))
        .mount(&mock_server)
        .await;

    Mock::given(method("GET"))
        .and(path("/api/cask.json"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
            {
                "token": "google-chrome",
                "desc": "Web browser",
                "homepage": "https://www.google.com/chrome/"
            }
        ])))
        .mount(&mock_server)
        .await;

    let client = Client::new();
    let source = Homebrew::with_base_url(client, mock_server.uri());

    // Create a mock query
    let query = Query {
        idea: "A fast search tool".into(),
        keywords: vec!["ripgrep".into()],
    };

    let results = source.search(&query).await.expect("Search should succeed");

    assert_eq!(results.len(), 1);
    assert_eq!(results[0].name, "ripgrep");
    assert!(matches!(results[0].source, SourceId::Homebrew));
}

#[tokio::test]
async fn test_homebrew_empty_results() {
    let mock_server = MockServer::start().await;

    // Mock both APIs returning empty arrays
    Mock::given(method("GET"))
        .and(path("/api/formula.json"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
        .mount(&mock_server)
        .await;

    Mock::given(method("GET"))
        .and(path("/api/cask.json"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
        .mount(&mock_server)
        .await;

    let client = Client::new();
    let source = Homebrew::with_base_url(client, mock_server.uri());

    let query = Query {
        idea: "Something completely obscure".into(),
        keywords: vec!["doesnotexist123".into()],
    };

    let results = source
        .search(&query)
        .await
        .expect("Search should succeed but be empty");
    assert!(results.is_empty());
}

#[tokio::test]
async fn test_homebrew_server_error() {
    let mock_server = MockServer::start().await;

    // Mock the formula API throwing a 500 Internal Server Error
    Mock::given(method("GET"))
        .and(path("/api/formula.json"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&mock_server)
        .await;

    // We don't need to mock cask.json here, because the adapter should
    // short-circuit and return an Err when the first formula request fails.

    let client = Client::new();
    let source = Homebrew::with_base_url(client, mock_server.uri());

    let query = Query {
        idea: "Testing server crash".into(),
        keywords: vec!["test".into()],
    };

    let result = source.search(&query).await;

    assert!(
        result.is_err(),
        "Expected the adapter to return an Error when hitting a 500 status code"
    );
}

// ---------------------------------------------------------------------------
// Packagist (PHP / Composer)
// ---------------------------------------------------------------------------

fn packagist_for(server: &MockServer) -> Packagist {
    Packagist::with_base_url(test_client(), server.uri())
}

fn packagist_body() -> serde_json::Value {
    json!({
        "results": [
            {
                "name": "laravel/framework",
                "description": "The Laravel Framework.",
                "url": "https://packagist.org/packages/laravel/framework",
                "repository": "https://github.com/laravel/framework",
                "downloads": 543_583_479_u64,
                "favers": 35_281_u64
            },
            {
                "name": "symfony/cache",
                "description": "Provides extended PSR-6, PSR-16 (and tags) implementations",
                "url": "https://packagist.org/packages/symfony/cache",
                "repository": "https://github.com/symfony/cache",
                "downloads": 373_170_138_u64,
                "favers": 4_189_u64
            }
        ],
        "total": 2
    })
}

#[tokio::test]
async fn packagist_id_is_packagist() {
    let src = Packagist::with_base_url(reqwest::Client::new(), "https://packagist.org".to_string());
    assert_eq!(src.id(), SourceId::Packagist);
}

#[tokio::test]
async fn packagist_maps_results_into_matches() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/search.json"))
        .respond_with(ResponseTemplate::new(200).set_body_json(packagist_body()))
        .mount(&server)
        .await;

    let matches = packagist_for(&server).search(&query()).await.unwrap();

    assert_eq!(matches.len(), 2);

    let first = &matches[0];
    assert_eq!(first.name, "laravel/framework");
    assert_eq!(first.source, SourceId::Packagist);
    assert_eq!(
        first.url,
        "https://packagist.org/packages/laravel/framework"
    );
    assert_eq!(first.description, "The Laravel Framework.");
    assert_eq!(first.popularity, Some(543_583_479));
    assert_eq!(first.similarity, 0.0);

    assert_eq!(matches[1].name, "symfony/cache");
    assert_eq!(matches[1].popularity, Some(373_170_138));
}

#[tokio::test]
async fn packagist_sends_joined_keywords_and_per_page() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/search.json"))
        .and(query_param("q", "async runtime"))
        .and(query_param("per_page", "15"))
        .respond_with(ResponseTemplate::new(200).set_body_json(packagist_body()))
        .expect(1)
        .mount(&server)
        .await;

    let matches = packagist_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches.len(), 2);
}

#[tokio::test]
async fn packagist_falls_back_to_favers_when_downloads_zero() {
    let server = MockServer::start().await;
    let body = json!({
        "results": [
            {
                "name": "fresh/package",
                "description": "Brand new, no downloads yet.",
                "url": "https://packagist.org/packages/fresh/package",
                "downloads": 0,
                "favers": 42
            }
        ],
        "total": 1
    });
    Mock::given(method("GET"))
        .and(path("/search.json"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    let matches = packagist_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches.len(), 1);
    assert_eq!(matches[0].popularity, Some(42));
}

#[tokio::test]
async fn packagist_missing_popularity_becomes_none() {
    let server = MockServer::start().await;
    let body = json!({
        "results": [
            {
                "name": "obscure/pkg",
                "description": "no counts here",
                "url": "https://packagist.org/packages/obscure/pkg"
            }
        ],
        "total": 1
    });
    Mock::given(method("GET"))
        .and(path("/search.json"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    let matches = packagist_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches.len(), 1);
    assert_eq!(matches[0].popularity, None);
}

#[tokio::test]
async fn packagist_empty_results_is_ok_not_error() {
    let server = MockServer::start().await;
    let body = json!({ "results": [], "total": 0 });
    Mock::given(method("GET"))
        .and(path("/search.json"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    let matches = packagist_for(&server).search(&query()).await.unwrap();
    assert!(matches.is_empty());
}

#[tokio::test]
async fn packagist_server_error_is_propagated() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/search.json"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;

    let result = packagist_for(&server).search(&query()).await;
    assert!(result.is_err(), "a 5xx response must surface as an error");
}

// ---------------------------------------------------------------------------
// Hex (Erlang/Elixir)
// ---------------------------------------------------------------------------

fn hex_for(server: &MockServer) -> Hex {
    Hex::with_base_url(test_client(), server.uri())
}

fn hex_body() -> serde_json::Value {
    json!([
        {
            "name": "phoenix",
            "html_url": "https://hex.pm/packages/phoenix",
            "meta": { "description": "Productive web framework that does not compromise speed or maintainability." },
            "downloads": { "all": 50_000_000_u64, "recent": 1_000_000_u64, "week": 250_000_u64 }
        },
        {
            "name": "cachex",
            "html_url": "https://hex.pm/packages/cachex",
            "meta": { "description": "A powerful caching library for Elixir." },
            "downloads": { "all": 12_345_u64 }
        }
    ])
}

#[tokio::test]
async fn hex_id_is_hex() {
    let src = Hex::with_base_url(reqwest::Client::new(), "https://hex.pm".to_string());
    assert_eq!(src.id(), SourceId::Hex);
}

#[tokio::test]
async fn hex_maps_packages_into_matches() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/packages"))
        .respond_with(ResponseTemplate::new(200).set_body_json(hex_body()))
        .mount(&server)
        .await;

    let matches = hex_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches.len(), 2);

    let first = &matches[0];
    assert_eq!(first.name, "phoenix");
    assert_eq!(first.source, SourceId::Hex);
    assert_eq!(first.url, "https://hex.pm/packages/phoenix");
    assert_eq!(
        first.description,
        "Productive web framework that does not compromise speed or maintainability."
    );
    assert_eq!(first.popularity, Some(50_000_000));
    assert_eq!(first.similarity, 0.0);

    assert_eq!(matches[1].name, "cachex");
    assert_eq!(matches[1].popularity, Some(12_345));
}

#[tokio::test]
async fn hex_sends_joined_keywords_as_search_param() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/packages"))
        .and(query_param("search", "async runtime"))
        .respond_with(ResponseTemplate::new(200).set_body_json(hex_body()))
        .expect(1)
        .mount(&server)
        .await;

    assert_eq!(hex_for(&server).search(&query()).await.unwrap().len(), 2);
}

#[tokio::test]
async fn hex_missing_description_becomes_empty() {
    let server = MockServer::start().await;
    let body = json!([
        { "name": "bare", "html_url": "https://hex.pm/packages/bare", "downloads": { "all": 5 } }
    ]);
    Mock::given(method("GET"))
        .and(path("/api/packages"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    let matches = hex_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches.len(), 1);
    assert_eq!(matches[0].description, "");
}

#[tokio::test]
async fn hex_zero_or_missing_downloads_becomes_none_and_url_falls_back() {
    let server = MockServer::start().await;
    let body = json!([
        { "name": "mystery", "meta": { "description": "no link, no downloads" }, "downloads": { "all": 0 } },
        { "name": "ghost", "meta": { "description": "no downloads block at all" } }
    ]);
    Mock::given(method("GET"))
        .and(path("/api/packages"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    let matches = hex_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches.len(), 2);
    assert_eq!(matches[0].popularity, None);
    assert_eq!(matches[0].url, format!("{}/packages/mystery", server.uri()));
    assert_eq!(matches[1].popularity, None);
}

#[tokio::test]
async fn hex_empty_results_is_ok_not_error() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/packages"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!([])))
        .mount(&server)
        .await;

    assert!(hex_for(&server).search(&query()).await.unwrap().is_empty());
}

#[tokio::test]
async fn hex_server_error_is_propagated() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/packages"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;

    assert!(hex_for(&server).search(&query()).await.is_err());
}

// ---------------------------------------------------------------------------
// Artifact Hub (Cloud Native package index)
// ---------------------------------------------------------------------------

fn artifacthub_for(server: &MockServer) -> ArtifactHub {
    ArtifactHub::with_base_url(test_client(), server.uri())
}

fn artifacthub_body() -> serde_json::Value {
    json!({
        "packages": [
            {
                "name": "prometheus",
                "description": "Prometheus monitoring system and time series database",
                "stars": 4200,
                "repository": {
                    "name": "prometheus-community",
                    "kind": 0,
                    "url": "https://prometheus-community.github.io/helm-charts"
                }
            },
            {
                "name": "trace-dns",
                "stars": 0,
                "repository": {
                    "name": "gadgets",
                    "kind": 22,
                    "url": "https://github.com/inspektor-gadget/inspektor-gadget"
                }
            }
        ]
    })
}

#[tokio::test]
async fn artifacthub_id_is_artifact_hub() {
    let src =
        ArtifactHub::with_base_url(reqwest::Client::new(), "https://artifacthub.io".to_string());
    assert_eq!(src.id(), SourceId::ArtifactHub);
}

#[tokio::test]
async fn artifacthub_maps_packages_into_matches() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/packages/search"))
        .respond_with(ResponseTemplate::new(200).set_body_json(artifacthub_body()))
        .mount(&server)
        .await;

    let matches = artifacthub_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches.len(), 2);

    let first = &matches[0];
    assert_eq!(first.name, "prometheus");
    assert_eq!(first.source, SourceId::ArtifactHub);
    assert_eq!(
        first.url,
        format!(
            "{}/packages/helm/prometheus-community/prometheus",
            server.uri()
        )
    );
    assert_eq!(
        first.description,
        "Prometheus monitoring system and time series database"
    );
    assert_eq!(first.popularity, Some(4200));
    assert_eq!(first.similarity, 0.0);

    let second = &matches[1];
    assert_eq!(second.name, "trace-dns");
    assert_eq!(
        second.url,
        format!(
            "{}/packages/inspektor-gadget/gadgets/trace-dns",
            server.uri()
        )
    );
    assert_eq!(second.description, "");
    assert_eq!(second.popularity, None);
}

#[tokio::test]
async fn artifacthub_sends_joined_keywords_as_query() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/packages/search"))
        .and(query_param("ts_query_web", "async runtime"))
        .and(query_param("limit", "15"))
        .and(header_exists("user-agent"))
        .respond_with(ResponseTemplate::new(200).set_body_json(artifacthub_body()))
        .expect(1)
        .mount(&server)
        .await;

    assert_eq!(
        artifacthub_for(&server)
            .search(&query())
            .await
            .unwrap()
            .len(),
        2
    );
}

#[tokio::test]
async fn artifacthub_unknown_kind_falls_back_to_repository_url() {
    let server = MockServer::start().await;
    let body = json!({
        "packages": [
            {
                "name": "future-thing",
                "description": "kind this adapter has no slug for yet",
                "stars": 3,
                "repository": {
                    "name": "some-repo",
                    "kind": 9999,
                    "url": "https://example.com/some-repo"
                }
            }
        ]
    });
    Mock::given(method("GET"))
        .and(path("/api/v1/packages/search"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    let matches = artifacthub_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches.len(), 1);
    assert_eq!(matches[0].url, "https://example.com/some-repo");
}

#[tokio::test]
async fn artifacthub_empty_results_is_ok() {
    let server = MockServer::start().await;
    let body = json!({ "packages": [] });
    Mock::given(method("GET"))
        .and(path("/api/v1/packages/search"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    assert!(artifacthub_for(&server)
        .search(&query())
        .await
        .unwrap()
        .is_empty());
}

#[tokio::test]
async fn artifacthub_server_error_is_propagated() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/packages/search"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;

    assert!(artifacthub_for(&server).search(&query()).await.is_err());
}

// ---------------------------------------------------------------------------
// AUR (Arch User Repository, RPC v5 JSON)
// ---------------------------------------------------------------------------

fn aur_for(server: &MockServer) -> Aur {
    Aur::with_base_url(test_client(), server.uri())
}

fn aur_body() -> serde_json::Value {
    json!({
        "resultcount": 2,
        "results": [
            {
                "Name": "ccache",
                "Description": "Compiler cache that speeds up recompilation",
                "URL": "https://ccache.dev",
                "NumVotes": 120,
                "Popularity": 3.5,
                "Maintainer": "someone",
                "Version": "4.10-1"
            },
            {
                "Name": "sccache-git",
                "Description": null,
                "URL": null,
                "NumVotes": 0,
                "Popularity": 0,
                "Maintainer": null,
                "Version": "0.8.1-1"
            }
        ]
    })
}

#[tokio::test]
async fn aur_id_is_aur() {
    let src = Aur::with_base_url(
        reqwest::Client::new(),
        "https://aur.archlinux.org".to_string(),
    );
    assert_eq!(src.id(), SourceId::Aur);
}

#[tokio::test]
async fn aur_maps_packages_into_matches() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/rpc/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(aur_body()))
        .mount(&server)
        .await;

    let matches = aur_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches.len(), 2);

    let ccache = &matches[0];
    assert_eq!(ccache.name, "ccache");
    assert_eq!(ccache.source, SourceId::Aur);
    assert_eq!(ccache.url, format!("{}/packages/ccache", server.uri()));
    assert_eq!(
        ccache.description,
        "Compiler cache that speeds up recompilation"
    );
    assert_eq!(ccache.popularity, Some(120));
    assert_eq!(ccache.similarity, 0.0);

    let sccache = &matches[1];
    assert_eq!(sccache.name, "sccache-git");
    assert_eq!(
        sccache.url,
        format!("{}/packages/sccache-git", server.uri())
    );
    assert_eq!(sccache.description, "");
    assert_eq!(sccache.popularity, None);
}

#[tokio::test]
async fn aur_sends_search_query_params() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/rpc/"))
        .and(query_param("v", "5"))
        .and(query_param("type", "search"))
        .and(query_param("arg", "async runtime"))
        .respond_with(ResponseTemplate::new(200).set_body_json(aur_body()))
        .expect(1)
        .mount(&server)
        .await;

    let matches = aur_for(&server).search(&query()).await.unwrap();
    assert_eq!(matches.len(), 2);
}

#[tokio::test]
async fn aur_empty_results_is_ok() {
    let server = MockServer::start().await;
    let body = json!({ "resultcount": 0, "results": [] });
    Mock::given(method("GET"))
        .and(path("/rpc/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(&server)
        .await;

    assert!(aur_for(&server).search(&query()).await.unwrap().is_empty());
}

#[tokio::test]
async fn aur_server_error_is_propagated() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/rpc/"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;

    assert!(aur_for(&server).search(&query()).await.is_err());
}