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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#![allow(dead_code)]
//! HTTP API module for IntentForge v2
//!
//! Provides REST endpoints for crawling, searching, and health checks
//! using axum web framework.

use axum::{
    extract::{Path, Query, Request, State},
    http::{HeaderMap, StatusCode},
    middleware::{self, Next},
    response::{IntoResponse, Response},
    routing::{get, post},
    Json, Router,
};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use std::time::Instant;

use crate::metrics::Metrics;
use crate::AppState;

/// Count phrase-aware significant term hits in a text.
/// Phrase matches count as 2 hits each; individual terms that are part of a matched phrase are skipped.
fn count_phrase_aware_hits<S: AsRef<str>>(
    combined: &str,
    phrase_terms: &[String],
    significant_terms: &[S],
) -> usize {
    let phrase_hits = phrase_terms
        .iter()
        .filter(|p| combined.contains(p.as_str()))
        .count();
    let individual_hits = significant_terms
        .iter()
        .filter(|t| {
            let t_str = t.as_ref();
            let in_phrase = phrase_terms.iter().any(|p| p.contains(t_str));
            if in_phrase {
                return false;
            }
            combined.contains(t_str)
        })
        .count();
    phrase_hits * 2 + individual_hits
}

/// Helper to hash a string for ID generation
fn hash_string(s: &str) -> String {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    s.hash(&mut hasher);
    format!("{:x}", hasher.finish())
}

/// Shared API state wrapping the app state with metrics
pub struct ApiState {
    pub app: Arc<AppState>,
    pub metrics: Metrics,
}

/// Query parameters for search endpoint
#[derive(Debug, Deserialize)]
pub struct SearchParams {
    pub q: String,
    #[serde(default = "default_limit")]
    pub limit: usize,
    #[serde(default = "default_offset")]
    pub offset: usize,
    pub filter: Option<String>,
    pub category: Option<String>,
    pub media_type: Option<String>,
    pub semantic_ratio: Option<f32>,
}

fn default_limit() -> usize {
    15
}
fn default_offset() -> usize {
    0
}

/// Search result item
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SearchResult {
    pub id: String,
    pub title: String,
    pub url: String,
    pub description: Option<String>,
    pub category: String,
    pub source: String,
    pub media_type: String,
    pub thumbnail_url: Option<String>,
    pub intent_score: f32,
    pub relevance_score: f32,
    pub commercial_score: f32,
    pub spam_score: f32,
}

/// Search response
#[derive(Debug, Serialize, Deserialize)]
pub struct SearchResponse {
    pub query: String,
    pub results: Vec<SearchResult>,
    pub total: usize,
    pub latency_ms: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub message: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    #[serde(default)]
    pub intent_scores: Vec<crate::intent_classifier::GroupScore>,
    #[serde(default)]
    pub self_improving: bool,
}

/// Query parameters for news/images/videos endpoints
#[derive(Debug, Deserialize)]
pub struct MediaSearchParams {
    pub q: String,
    #[serde(default = "default_limit")]
    pub limit: usize,
    pub category: Option<String>,
    pub location: Option<String>,
}

/// News result item
#[derive(Debug, Serialize, Clone)]
pub struct NewsResult {
    pub title: String,
    pub url: String,
    pub description: String,
    pub source: String,
    pub published_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thumbnail_url: Option<String>,
}

/// News search response
#[derive(Debug, Serialize)]
pub struct NewsResponse {
    pub query: String,
    pub results: Vec<NewsResult>,
    pub total: usize,
    pub latency_ms: u64,
    pub sources: Vec<String>,
}

/// Image result item
#[derive(Debug, Serialize, Clone)]
pub struct ImageResult {
    pub id: String,
    pub title: String,
    pub url: String,
    pub source: String,
    pub category: String,
    pub intent_score: f32,
    pub relevance_score: f32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thumbnail_url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alt_text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub photographer: Option<String>,
    pub width: Option<u32>,
    pub height: Option<u32>,
    pub avg_color: Option<String>,
}

/// Image search response
#[derive(Debug, Serialize)]
pub struct ImageResponse {
    pub query: String,
    pub results: Vec<ImageResult>,
    pub total: usize,
    pub latency_ms: u64,
    pub sources: Vec<String>,
}

/// Video result item
#[derive(Debug, Serialize, Clone)]
pub struct VideoResult {
    pub id: String,
    pub title: String,
    pub url: String,
    pub source: String,
    pub description: Option<String>,
    pub intent_score: f32,
    pub relevance_score: f32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thumbnail_url: Option<String>,
    pub duration_secs: Option<u32>,
    pub view_count: Option<u64>,
    pub channel: Option<String>,
    pub published_at: Option<String>,
}

/// Video search response
#[derive(Debug, Serialize)]
pub struct VideoResponse {
    pub query: String,
    pub results: Vec<VideoResult>,
    pub total: usize,
    pub latency_ms: u64,
    pub sources: Vec<String>,
}

/// Crawl parameters
#[derive(Debug, Deserialize)]
pub struct CrawlParams {
    pub url: String,
}

/// Crawl response
#[derive(Debug, Serialize)]
pub struct CrawlResponse {
    pub url: String,
    pub title: String,
    pub content_length: usize,
    pub success: bool,
    pub latency_ms: u64,
    pub error: Option<String>,
}

/// Batch crawl request
#[derive(Debug, Deserialize)]
pub struct BatchCrawlRequest {
    pub urls: Vec<String>,
}

/// Discovery enqueue request
#[derive(Debug, Deserialize)]
pub struct DiscoveryEnqueueRequest {
    pub url: String,
    #[serde(default)]
    pub category: Option<String>,
    #[serde(default = "default_priority")]
    pub priority: u32,
}

fn default_priority() -> u32 {
    5
}

/// Discovery enqueue response
#[derive(Debug, Serialize)]
pub struct DiscoveryEnqueueResponse {
    pub url: String,
    pub enqueued: bool,
    pub error: Option<String>,
}

async fn auth_middleware(
    State(state): State<Arc<ApiState>>,
    headers: HeaderMap,
    request: Request,
    next: Next,
) -> Response {
    // If no API key is configured, allow all requests (for dev/local)
    let expected_key = match &state.app.config.api_key {
        Some(k) if !k.is_empty() => k,
        _ => return next.run(request).await,
    };

    let api_key = headers.get("X-API-Key").and_then(|h| h.to_str().ok());

    match api_key {
        Some(key) if key == expected_key => next.run(request).await,
        _ => {
            tracing::warn!("Unauthorized access attempt from {:?}", request.uri());
            (
                StatusCode::UNAUTHORIZED,
                Json(serde_json::json!({ "error": "Unauthorized" })),
            )
                .into_response()
        }
    }
}

/// Initialize the API router
pub fn create_router(state: Arc<ApiState>) -> Router {
    let public_routes = Router::new()
        .route("/health", get(health_handler))
        .route("/metrics", get(metrics_handler));

    let protected_routes = Router::new()
        .route("/search", get(search_handler))
        .route("/meta", get(meta_search_handler))
        .route("/news", get(news_handler))
        .route("/images", get(images_handler))
        .route("/videos", get(videos_handler))
        .route("/crawl", get(crawl_single_handler))
        .route("/crawl/batch", post(crawl_batch_handler))
        .route("/content/:id", get(get_full_content_handler))
        .route("/discovery/status", get(discovery_status_handler))
        .route("/discovery/enqueue", post(discovery_enqueue_handler))
        .route("/admin/reindex-scores", post(reindex_scores_handler))
        .layer(middleware::from_fn_with_state(
            state.clone(),
            auth_middleware,
        ));

    Router::new()
        .merge(public_routes)
        .merge(protected_routes)
        .with_state(state)
}

/// Health check endpoint
async fn health_handler() -> impl IntoResponse {
    (StatusCode::OK, Json(serde_json::json!({"status": "ok"})))
}

/// Validate filter string to prevent injection attacks
fn validate_filter(filter: &str) -> Result<(), (StatusCode, String)> {
    if filter.contains('\0') {
        return Err((
            StatusCode::BAD_REQUEST,
            "Invalid filter: contains null bytes".to_string(),
        ));
    }
    let dangerous_patterns = [
        "DROP TABLE",
        "DELETE FROM",
        "UPDATE SET",
        "INSERT INTO",
        "ALTER TABLE",
        "CREATE TABLE",
        "EXEC ",
        "--",
    ];
    let upper_filter = filter.to_uppercase();
    for pattern in dangerous_patterns {
        if upper_filter.contains(pattern) {
            return Err((
                StatusCode::BAD_REQUEST,
                "Invalid filter: contains dangerous pattern".to_string(),
            ));
        }
    }
    Ok(())
}

/// Query expansion and rewriting
fn rewrite_query(
    query: &str,
    config: &crate::query_expansion::QueryExpansionConfig,
) -> (String, Vec<String>) {
    let expansion = crate::query_expansion::expand_query(query, config);
    let mut auto_filters = Vec::new();
    let lower = query.to_lowercase();
    if !(lower.contains("buy") || lower.contains("price") || lower.contains("discount")) {
        auto_filters.push("commercial_score < 0.7".to_string());
    }
    auto_filters.push("spam_score < 0.5".to_string());
    (expansion.expanded, auto_filters)
}

/// Search endpoint - hybrid semantic + keyword search
async fn search_handler(
    State(state): State<Arc<ApiState>>,
    Query(params): Query<SearchParams>,
) -> impl IntoResponse {
    let start = Instant::now();
    state.metrics.search_requests_total.inc();

    // Validate empty query
    if params.q.trim().is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(SearchResponse {
                query: params.q.clone(),
                total: 0,
                results: vec![],
                latency_ms: start.elapsed().as_millis() as u64,
                message: Some("Query cannot be empty".to_string()),
                intent_scores: vec![],
                self_improving: false,
            }),
        )
            .into_response();
    }

    // Check response cache (only quality responses are cached)
    let cache_key = format!("search_cache:{}", params.q.to_lowercase().trim());
    if let Ok(Some(cached)) = state.app.redis.get_json::<SearchResponse>(&cache_key).await {
        tracing::info!(
            "Cache HIT for '{}' ({} results)",
            params.q,
            cached.results.len()
        );
        return (StatusCode::OK, Json(cached)).into_response();
    }

    let (expanded_query, auto_filters) =
        rewrite_query(&params.q, &state.app.query_expansion_config);

    let mut filter_parts = Vec::new();
    if let Some(f) = &params.filter {
        if let Err((status, msg)) = validate_filter(f) {
            return (
                status,
                Json(SearchResponse {
                    query: params.q.clone(),
                    total: 0,
                    results: vec![],
                    latency_ms: start.elapsed().as_millis() as u64,
                    message: Some(msg),
                    intent_scores: vec![],
                    self_improving: false,
                }),
            )
                .into_response();
        }
        filter_parts.push(format!("({})", f));
    }
    for af in auto_filters {
        filter_parts.push(af);
    }
    if let Some(category) = &params.category {
        filter_parts.push(format!("category = \"{}\"", category));
    }
    if let Some(media_type) = &params.media_type {
        filter_parts.push(format!("media_type = \"{}\"", media_type));
    }

    let final_filter = if filter_parts.is_empty() {
        if params.media_type.is_none() {
            Some("media_type = \"text\"".to_string())
        } else {
            None
        }
    } else {
        Some(filter_parts.join(" AND "))
    };

    let _semantic_ratio = params
        .semantic_ratio
        .unwrap_or(state.app.config.meilisearch.semantic_ratio);

    // --- DYNAMIC INTENT CLASSIFICATION (no hardcoded keywords) ---
    let intent_scores = state
        .app
        .intent_classifier
        .classify_with_scores(&params.q, None);
    let primary_intent = intent_scores.first().map(|g| g.primary_intent.clone());
    let primary_intent_score = intent_scores.first().map(|g| g.score).unwrap_or(0.0);
    let primary = primary_intent
        .clone()
        .unwrap_or(crate::intent_classifier::QueryIntent::General);

    // Extract query keywords for term matching
    let query_terms: Vec<String> = params
        .q
        .to_lowercase()
        .split_whitespace()
        .filter(|w| w.len() > 2)
        .map(|w| w.to_string())
        .collect();

    // Stop words that don't carry query-specific meaning
    let stop_words: HashSet<&str> = [
        "the", "and", "for", "with", "from", "that", "this", "what", "how", "are", "was", "were",
        "been", "being", "have", "has", "had", "does", "did", "will", "would", "could", "should",
        "may", "might", "can", "not", "but", "yet", "also", "just", "than", "then", "too", "very",
        "best", "top", "most", "more", "about", "into", "some", "any", "all", "who", "which",
        "when", "where", "why", "use", "using", "used",
    ]
    .iter()
    .copied()
    .collect();

    // Significant terms: content-bearing words that discriminate this query
    let significant_terms: Vec<&String> = query_terms
        .iter()
        .filter(|t| !stop_words.contains(t.as_str()))
        .collect();
    let has_significant_terms = !significant_terms.is_empty();

    // Known compound terms that should be matched as phrases
    let compound_terms: Vec<(&str, &str)> = vec![
        ("machine", "learning"),
        ("deep", "learning"),
        ("reinforcement", "learning"),
        ("neural", "network"),
        ("natural", "language"),
        ("computer", "vision"),
        ("data", "science"),
        ("cloud", "computing"),
        ("web", "development"),
        ("async", "programming"),
        ("binary", "search"),
        ("linked", "list"),
        ("hash", "table"),
        ("red", "black"),
        ("dynamic", "programming"),
        ("zero", "knowledge"),
        ("state", "locking"),
        ("full", "text"),
        ("black", "pine"),
        ("reward", "shaping"),
        ("cold", "ferment"),
        ("pressure", "profiling"),
        ("pod", "affinity"),
        ("helm", "chart"),
        ("near", "duplicate"),
        ("sourdough", "starter"),
        ("knife", "sharpening"),
        ("espresso", "machine"),
        ("ground", "plane"),
    ];

    let mut phrase_terms: Vec<String> = Vec::new();
    let sig_words: Vec<&str> = query_terms.iter().map(|s| s.as_str()).collect();
    for window in sig_words.windows(2) {
        let pair = (window[0], window[1]);
        if compound_terms
            .iter()
            .any(|&(a, b)| a == pair.0 && b == pair.1)
        {
            phrase_terms.push(format!("{} {}", pair.0, pair.1));
        }
    }

    // Effective sig count: each phrase replaces 2 individual terms with 1 phrase unit
    let effective_sig_count = significant_terms.len().saturating_sub(phrase_terms.len());
    let min_sig_required = if effective_sig_count <= 1 {
        1
    } else if effective_sig_count == 2 {
        2
    } else {
        effective_sig_count.div_ceil(2)
    };

    // PHASE 1: Fast local index search (<1 second target)
    let q_local = expanded_query.clone();
    let filter_local = final_filter.clone();
    let local_res = state
        .app
        .indexer
        .search(&q_local, filter_local.as_deref(), Some(50))
        .await
        .unwrap_or_default();

    // Pre-filter obvious garbage
    let valid_docs: Vec<_> = local_res
        .iter()
        .filter(|doc| {
            let title_low = doc.title.to_lowercase();
            !(title_low.contains("just a moment")
                || title_low.contains("cloudflare")
                || doc.title.trim().is_empty())
        })
        .collect();

    // Batch alignment boost for all valid documents
    let combined_texts: Vec<String> = valid_docs
        .iter()
        .map(|doc| {
            let title_low = doc.title.to_lowercase();
            let desc_low = doc.description.as_deref().unwrap_or("").to_lowercase();
            format!("{} {}", title_low, desc_low)
        })
        .collect();
    let combined_refs: Vec<&str> = combined_texts.iter().map(|s| s.as_str()).collect();
    let alignments = if primary == crate::intent_classifier::QueryIntent::General {
        vec![1.0; combined_refs.len()]
    } else {
        state
            .app
            .intent_classifier
            .calculate_alignment_boost_batch(&primary, &combined_refs)
    };

    let mut local_results: Vec<SearchResult> = Vec::new();
    let mut local_urls = HashSet::new();

    for (idx, doc) in valid_docs.iter().enumerate() {
        let combined = &combined_texts[idx];
        let alignment = alignments[idx];

        if alignment < 0.2 {
            continue;
        }

        // Significant term overlap (phrase-aware)
        let sig_hits = count_phrase_aware_hits(combined, &phrase_terms, &significant_terms);

        // Require minimum significant term coverage to pass
        if has_significant_terms && sig_hits < min_sig_required {
            continue;
        }

        // Score based on significant term coverage + alignment
        let term_relevance = if !has_significant_terms {
            0.5
        } else {
            sig_hits as f32 / significant_terms.len() as f32
        };
        let alignment_norm = (alignment / 1.2).min(1.0);
        let computed_intent = (term_relevance * 0.7 + alignment_norm * 0.3).clamp(0.0, 1.0);
        let intent_score = computed_intent.max(doc.intent_score * 0.7);

        if !local_urls.contains(&doc.url) {
            local_results.push(SearchResult {
                id: doc.id.clone(),
                title: doc.title.clone(),
                url: doc.url.clone(),
                description: doc.description.clone(),
                category: doc.category.clone(),
                source: doc.source.clone(),
                media_type: doc.media_type.clone(),
                thumbnail_url: doc.thumbnail_url.clone(),
                intent_score,
                relevance_score: doc.relevance_score,
                commercial_score: doc.commercial_score,
                spam_score: doc.spam_score,
            });
            local_urls.insert(doc.url.clone());
        }
    }

    // Sort local results: intent-first, then relevance
    local_results.sort_by(|a, b| {
        let a_priority = a.intent_score * 0.6 + a.relevance_score * 0.4;
        let b_priority = b.intent_score * 0.6 + b.relevance_score * 0.4;
        b_priority
            .partial_cmp(&a_priority)
            .unwrap_or(std::cmp::Ordering::Equal)
    });

    let local_elapsed = start.elapsed().as_millis() as u64;

    // Check if we already have 15+ high-quality, intent-matching results
    let target_count = 15;
    let quality_threshold = 0.35;
    let high_quality_local: Vec<&SearchResult> = local_results
        .iter()
        .filter(|r| {
            r.relevance_score >= quality_threshold && r.intent_score >= 0.35 && r.spam_score < 0.3
        })
        .collect();

    let needs_improvement = local_results.len() < target_count
        || high_quality_local.len() < target_count
        || primary_intent_score < 0.3;

    tracing::info!(
        "Search quality: local={}, high_quality={}, intent={:.2}, needs_improve={}",
        local_results.len(),
        high_quality_local.len(),
        primary_intent_score,
        needs_improvement
    );

    // PHASE 2: Lightweight synchronous meta-search when local results are insufficient
    let mut meta_count = 0usize;
    if needs_improvement && local_elapsed < 1500 {
        let meta_timeout = std::time::Duration::from_millis(2000);
        if let Ok(meta_resp) = tokio::time::timeout(
            meta_timeout,
            state
                .app
                .aggregator
                .search_with_intent(&params.q, Some(&primary)),
        )
        .await
        {
            for r in &meta_resp.results {
                if local_urls.contains(&r.url) {
                    continue;
                }
                if params.media_type.is_none() && r.media_type != "text" {
                    continue;
                }

                let combined = format!(
                    "{} {}",
                    r.title.to_lowercase(),
                    r.description.to_lowercase()
                );

                let alignment = state
                    .app
                    .intent_classifier
                    .calculate_alignment_boost(&primary, &combined);
                if alignment < 0.2 {
                    continue;
                }

                if has_significant_terms {
                    let meta_sig_hits =
                        count_phrase_aware_hits(&combined, &phrase_terms, &significant_terms);
                    if meta_sig_hits < 1 {
                        continue;
                    }
                }

                let alignment_norm = (alignment / 1.2).min(1.0);
                let rrf_contribution = (r.score * 10.0).min(0.3);
                let intent_score = (alignment_norm * 0.5 + rrf_contribution + 0.2).clamp(0.0, 1.0);

                let doc_text = format!("{} {}", r.title, r.description);
                let cat_intent = state.app.intent_classifier.get_intent_for_text(&doc_text);

                local_results.push(SearchResult {
                    id: hash_string(&r.url),
                    title: r.title.clone(),
                    url: r.url.clone(),
                    description: Some(r.description.clone()),
                    category: format!("{:?}", cat_intent),
                    source: r.source.clone(),
                    media_type: r.media_type.clone(),
                    thumbnail_url: r.thumbnail_url.clone(),
                    intent_score,
                    relevance_score: intent_score,
                    commercial_score: 0.0,
                    spam_score: 0.0,
                });
                local_urls.insert(r.url.clone());
                meta_count += 1;
            }
        }

        if meta_count > 0 {
            local_results.sort_by(|a, b| {
                let a_priority = a.intent_score * 0.6 + a.relevance_score * 0.4;
                let b_priority = b.intent_score * 0.6 + b.relevance_score * 0.4;
                b_priority
                    .partial_cmp(&a_priority)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });
        }
    }

    let self_improving_flag = needs_improvement && meta_count < 5;

    // Apply pagination to merged results
    let local_count = local_results.len();
    let paginated_results: Vec<SearchResult> = local_results
        .into_iter()
        .skip(params.offset)
        .take(params.limit)
        .collect();

    let quality_count = paginated_results
        .iter()
        .filter(|r| r.intent_score >= 0.35 && r.relevance_score >= 0.35 && r.spam_score < 0.3)
        .count();
    let is_quality_response = quality_count >= 5 && paginated_results.len() >= target_count;

    let message = if meta_count > 0 {
        Some(format!(
            "Local {} + meta {} in {}ms ({} quality)",
            local_count - meta_count,
            meta_count,
            start.elapsed().as_millis(),
            quality_count
        ))
    } else if self_improving_flag {
        Some(format!(
            "Found {} results ({}ms), {} quality. Improving in background — retry in ~30-60s for better results.",
            paginated_results.len(), local_elapsed, quality_count
        ))
    } else {
        Some(format!(
            "Local index: {} results in {}ms ({} quality)",
            local_count, local_elapsed, quality_count
        ))
    };

    let query_owned = params.q.clone();

    let response = SearchResponse {
        query: params.q,
        total: paginated_results.len(),
        results: paginated_results,
        latency_ms: start.elapsed().as_millis() as u64,
        message,
        intent_scores,
        self_improving: self_improving_flag,
    };

    // Cache quality responses
    if is_quality_response {
        let _ = state.app.redis.set_json(&cache_key, &response, 300).await;
        tracing::info!(
            "Cached quality response for '{}' ({} quality, {} total)",
            query_owned,
            quality_count,
            response.results.len()
        );
    }

    // Spawn background self-improvement when quality is insufficient (3-min budget)
    if self_improving_flag {
        let lock_key = format!("self_imp:active:{}", query_owned.to_lowercase().trim());

        // Acquire distributed lock via SETNX to prevent duplicate tasks
        let lock_acquired = if let Ok(mut conn) = state.app.redis.get_connection().await {
            let acquired: bool = redis::cmd("SETNX")
                .arg(&lock_key)
                .arg("1")
                .query_async(&mut conn)
                .await
                .unwrap_or(true);
            if acquired {
                let _: Result<(), _> = redis::cmd("EXPIRE")
                    .arg(&lock_key)
                    .arg(180i64)
                    .query_async(&mut conn)
                    .await;
            }
            acquired
        } else {
            true
        };

        if lock_acquired {
            let imp_state = state.clone();
            let imp_query = query_owned.clone();
            let imp_intent = primary.clone();
            let imp_sig_terms: Vec<String> =
                significant_terms.iter().map(|s| s.to_string()).collect();
            let imp_phrase_terms: Vec<String> = phrase_terms.clone();
            let imp_min_sig = min_sig_required;
            let imp_query_terms = query_terms.clone();
            let imp_cache_key = cache_key.clone();
            let imp_lock_key = lock_key;
            let imp_expanded_query = expanded_query.clone();

            tokio::spawn(async move {
                let task_start = Instant::now();
                let budget = std::time::Duration::from_secs(300); // 5 minutes
                let target = 15usize;
                let max_rounds = 10;
                let mut quality_indexed = 0usize;
                let mut seen_urls: HashSet<String> = HashSet::new();

                // Generate query variations for multi-round search
                let mut variations = imp_state
                    .app
                    .intent_classifier
                    .generate_variations(&imp_query, &imp_intent);
                if !variations.contains(&imp_query) {
                    variations.insert(0, imp_query.clone());
                }
                variations.push(imp_query_terms.join(" "));
                // Add more aggressive variations for persistent discovery
                variations.push(format!("{} tutorial examples", imp_query));
                variations.push(format!("{} complete guide walkthrough", imp_query));
                variations.push(format!("{} best practices tips", imp_query));
                variations.push(format!("{} advanced techniques", imp_query));
                variations.push(format!("{} how to step by step", imp_query));

                tracing::info!(
                    "Background self-improvement started for '{}' (target: {}, max rounds: {}, budget: 300s, variations: {})",
                    imp_query, target, max_rounds, variations.len()
                );

                // Embed query once for intent scoring
                let query_embedding = match imp_state
                    .app
                    .embedding_model
                    .embed_batch(std::slice::from_ref(&imp_query))
                {
                    Ok(embs) => embs.into_iter().next().unwrap_or_default(),
                    Err(_) => imp_state
                        .app
                        .embedding_model
                        .embed_fallback(std::slice::from_ref(&imp_query))
                        .into_iter()
                        .next()
                        .unwrap_or_default(),
                };

                let mut round = 0;
                let mut consecutive_empty = 0;
                loop {
                    // Hard stop conditions
                    if quality_indexed >= target
                        || task_start.elapsed() >= budget
                        || round >= max_rounds
                    {
                        break;
                    }

                    // Stop if we've had too many consecutive empty rounds (no new URLs found)
                    if consecutive_empty >= 5 {
                        tracing::info!(
                            "Background self-improvement stopping for '{}': {} consecutive empty rounds, quality={}/{} (partial)",
                            imp_query, consecutive_empty, quality_indexed, target
                        );
                        break;
                    }

                    let search_query = &variations[round % variations.len()];
                    let remaining = budget.saturating_sub(task_start.elapsed());
                    if remaining < std::time::Duration::from_secs(10) {
                        break;
                    }

                    tracing::info!(
                        "Self-improvement round {}/{} for '{}': query='{}', quality={}/{}, elapsed={}s",
                        round + 1, max_rounds, imp_query, search_query, quality_indexed, target,
                        task_start.elapsed().as_secs()
                    );

                    // Meta search with per-round timeout (intent-aware weighted RRF)
                    let meta_res = tokio::time::timeout(
                        std::time::Duration::from_secs(10),
                        imp_state
                            .app
                            .aggregator
                            .search_with_intent(search_query, Some(&imp_intent)),
                    )
                    .await;

                    let meta_resp = match meta_res {
                        Ok(resp) => resp,
                        Err(_) => {
                            tracing::warn!(
                                "Self-improvement: meta search timed out round {}",
                                round + 1
                            );
                            round += 1;
                            consecutive_empty += 1;
                            tokio::time::sleep(std::time::Duration::from_secs(1)).await;
                            continue;
                        }
                    };

                    if meta_resp.results.is_empty() {
                        consecutive_empty += 1;
                        tracing::debug!(
                            "Self-improvement round {}: meta returned 0 results, consecutive_empty={}",
                            round + 1, consecutive_empty
                        );
                        round += 1;
                        tokio::time::sleep(std::time::Duration::from_secs(1)).await;
                        continue;
                    }

                    // Collect ALL unseen URLs with their scores for relative ranking
                    let mut scored_candidates: Vec<(
                        &crate::meta_search::models::SearchResult,
                        f32,
                    )> = Vec::new();
                    for r in &meta_resp.results {
                        if seen_urls.contains(&r.url) {
                            continue;
                        }
                        seen_urls.insert(r.url.clone());

                        let combined = format!(
                            "{} {}",
                            r.title.to_lowercase(),
                            r.description.to_lowercase()
                        );
                        let alignment = imp_state
                            .app
                            .intent_classifier
                            .calculate_alignment_boost(&imp_intent, &combined);
                        if alignment < 0.2 {
                            continue;
                        } // Relaxed alignment threshold

                        // Score = RRF score * 0.4 + alignment * 0.3 + source weight * 0.3
                        let source_weight = match r.source.as_str() {
                            "searxng" => 1.0,
                            "arxiv" | "github" => 0.9,
                            "reddit" => 0.8,
                            "duckduckgo" => 0.7,
                            _ => 0.5,
                        };
                        let combined_score = r.score * 0.4 + alignment * 0.3 + source_weight * 0.3;
                        scored_candidates.push((r, combined_score));
                    }

                    if scored_candidates.is_empty() {
                        consecutive_empty += 1;
                        tracing::debug!(
                            "Self-improvement round {}: all {} results already seen or filtered, consecutive_empty={}",
                            round + 1, meta_resp.results.len(), consecutive_empty
                        );
                        round += 1;
                        tokio::time::sleep(std::time::Duration::from_secs(1)).await;
                        continue;
                    }

                    // Reset consecutive empty counter since we found new candidates
                    consecutive_empty = 0;

                    // Sort by combined score and take top candidates (relative ranking)
                    scored_candidates
                        .sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
                    let take_count = std::cmp::min(10, scored_candidates.len());
                    let top_candidates: Vec<_> = scored_candidates
                        .into_iter()
                        .take(take_count)
                        .map(|(r, _)| r)
                        .collect();

                    tracing::info!(
                        "Self-improvement round {}: selected {}/{} candidates (top by relative score, best={:.3})",
                        round + 1, take_count, meta_resp.results.len(),
                        top_candidates.first().map(|r| r.score).unwrap_or(0.0)
                    );

                    // Crawl candidates
                    let urls: Vec<&str> = top_candidates.iter().map(|r| r.url.as_str()).collect();
                    let crawl_results = match imp_state.app.crawler.fetch_batch(urls).await {
                        Ok(r) => r,
                        Err(e) => {
                            tracing::warn!(
                                "Self-improvement: crawl failed round {}: {}",
                                round + 1,
                                e
                            );
                            round += 1;
                            tokio::time::sleep(std::time::Duration::from_secs(1)).await;
                            continue;
                        }
                    };

                    // Embed, score, and index each document
                    for (idx, crawl_result) in crawl_results.iter().enumerate() {
                        if quality_indexed >= target {
                            break;
                        }

                        let ext = top_candidates.get(idx);
                        let source = ext.map(|r| r.source.as_str()).unwrap_or("self_improvement");
                        let rrf_score = ext.map(|r| r.score).unwrap_or(0.0);

                        let text = format!("{} {}", crawl_result.title, crawl_result.content);
                        let embedding = match imp_state
                            .app
                            .embedding_model
                            .embed_batch(std::slice::from_ref(&text))
                        {
                            Ok(embs) => embs.into_iter().next().unwrap_or_default(),
                            Err(_) => imp_state
                                .app
                                .embedding_model
                                .embed_fallback(std::slice::from_ref(&text))
                                .into_iter()
                                .next()
                                .unwrap_or_default(),
                        };

                        let intent_score =
                            crate::utils::cosine_similarity(&query_embedding, &embedding)
                                .clamp(0.0, 1.0);
                        let quality_score = imp_state
                            .app
                            .embedding_model
                            .calculate_quality_score(&text, &crawl_result.url);
                        let relevance_score =
                            (intent_score * 0.5 + quality_score * 0.3 + rrf_score.min(0.2))
                                .clamp(0.1, 1.0);

                        // Relaxed intent threshold for partial improvements
                        if intent_score < 0.25 {
                            continue;
                        }

                        // Dynamic category via intent classifier
                        let content_snippet: String =
                            crawl_result.content.chars().take(500).collect();
                        let doc_text = format!("{} {}", crawl_result.title, content_snippet);
                        let dynamic_cat = format!(
                            "{:?}",
                            imp_state
                                .app
                                .intent_classifier
                                .get_intent_for_text(&doc_text)
                        );

                        let safe_id = hash_string(&crawl_result.url);
                        let _ = imp_state
                            .app
                            .indexer
                            .get_redis()
                            .store_content(&safe_id, &crawl_result.content)
                            .await;

                        let doc = crate::indexer::IntentDocument::new(
                            format!("ext-{}", safe_id),
                            crawl_result.title.clone(),
                            crawl_result.content.clone(),
                            crawl_result.url.clone(),
                            source.to_string(),
                            dynamic_cat,
                            intent_score,
                            relevance_score,
                            embedding,
                        )
                        .with_extra_scores(0.0, 0.0);

                        if let Err(e) = imp_state.app.indexer.index_document(&doc).await {
                            tracing::warn!(
                                "Self-improvement: failed to index {}: {}",
                                crawl_result.url,
                                e
                            );
                        } else {
                            // Relaxed quality gate for partial improvements
                            let is_quality = intent_score >= 0.3 && relevance_score >= 0.3;
                            if is_quality {
                                quality_indexed += 1;
                            }
                            tracing::info!(
                                "Self-improvement indexed: intent={:.3} rel={:.3} quality={} [{}/{}] | {}",
                                intent_score, relevance_score, is_quality,
                                quality_indexed, target, doc.title
                            );
                        }
                    }

                    round += 1;

                    // Add delay between rounds to avoid rate limiting
                    tokio::time::sleep(std::time::Duration::from_secs(2)).await;
                }

                // After indexing, re-run the search to see if quality improved
                if quality_indexed > 0 {
                    tracing::info!(
                        "Re-running search for '{}' after indexing {} quality docs",
                        imp_query,
                        quality_indexed
                    );

                    let re_filter = Some(
                        "media_type = \"text\" AND commercial_score < 0.7 AND spam_score < 0.5"
                            .to_string(),
                    );
                    let re_local = imp_state
                        .app
                        .indexer
                        .search(&imp_expanded_query, re_filter.as_deref(), Some(50))
                        .await
                        .unwrap_or_default();

                    let mut re_results: Vec<SearchResult> = Vec::new();
                    let mut re_urls = HashSet::new();

                    for doc in &re_local {
                        let title_low = doc.title.to_lowercase();
                        let desc_low = doc.description.as_deref().unwrap_or("").to_lowercase();
                        let combined = format!("{} {}", title_low, desc_low);

                        if title_low.contains("just a moment")
                            || title_low.contains("cloudflare")
                            || doc.title.trim().is_empty()
                        {
                            continue;
                        }

                        let alignment = imp_state
                            .app
                            .intent_classifier
                            .calculate_alignment_boost(&imp_intent, &combined);
                        if alignment < 0.2 {
                            continue;
                        }

                        let sig_hits =
                            count_phrase_aware_hits(&combined, &imp_phrase_terms, &imp_sig_terms);
                        if !imp_sig_terms.is_empty() && sig_hits < imp_min_sig {
                            continue;
                        }

                        let term_relevance = if imp_sig_terms.is_empty() {
                            0.5
                        } else {
                            sig_hits as f32 / imp_sig_terms.len() as f32
                        };
                        let alignment_norm = (alignment / 1.2).min(1.0);
                        let computed_intent =
                            (term_relevance * 0.7 + alignment_norm * 0.3).clamp(0.0, 1.0);
                        let intent_score = computed_intent.max(doc.intent_score * 0.7);

                        if !re_urls.contains(&doc.url) {
                            re_results.push(SearchResult {
                                id: doc.id.clone(),
                                title: doc.title.clone(),
                                url: doc.url.clone(),
                                description: doc.description.clone(),
                                category: doc.category.clone(),
                                source: doc.source.clone(),
                                media_type: doc.media_type.clone(),
                                thumbnail_url: doc.thumbnail_url.clone(),
                                intent_score,
                                relevance_score: doc.relevance_score,
                                commercial_score: doc.commercial_score,
                                spam_score: doc.spam_score,
                            });
                            re_urls.insert(doc.url.clone());
                        }
                    }

                    re_results.sort_by(|a, b| {
                        let a_p = a.intent_score * 0.6 + a.relevance_score * 0.4;
                        let b_p = b.intent_score * 0.6 + b.relevance_score * 0.4;
                        b_p.partial_cmp(&a_p).unwrap_or(std::cmp::Ordering::Equal)
                    });

                    let re_final: Vec<SearchResult> = re_results
                        .into_iter()
                        .filter(|r| r.media_type == "text")
                        .take(15)
                        .collect();

                    let re_total = re_final.len();
                    let re_quality = re_final
                        .iter()
                        .filter(|r| {
                            r.intent_score >= 0.35
                                && r.relevance_score >= 0.35
                                && r.spam_score < 0.3
                        })
                        .count();

                    if re_quality >= 5 && re_total >= 15 {
                        let cached_response = SearchResponse {
                            query: imp_query.clone(),
                            total: re_total,
                            results: re_final,
                            latency_ms: 0,
                            message: Some(format!(
                                "Self-improved: {} quality results indexed and cached",
                                quality_indexed
                            )),
                            intent_scores: vec![],
                            self_improving: false,
                        };
                        let _ = imp_state
                            .app
                            .redis
                            .set_json(&imp_cache_key, &cached_response, 300)
                            .await;
                        tracing::info!(
                            "Cached quality response for '{}' after self-improvement ({}/{} quality)",
                            imp_query, re_quality, re_total
                        );
                    } else {
                        // Not quality yet — clear any stale cache so next request re-evaluates
                        if let Ok(mut conn) = imp_state.app.redis.get_connection().await {
                            let _: Result<(), _> = redis::cmd("DEL")
                                .arg(&imp_cache_key)
                                .query_async(&mut conn)
                                .await;
                        }
                        tracing::info!(
                            "Self-improvement for '{}': re-search has {}/{} quality (not yet sufficient to cache)",
                            imp_query, re_quality, re_total
                        );
                    }
                }

                // Release lock
                if let Ok(mut conn) = imp_state.app.redis.get_connection().await {
                    let _: Result<(), _> = redis::cmd("DEL")
                        .arg(&imp_lock_key)
                        .query_async(&mut conn)
                        .await;
                }

                tracing::info!(
                    "Background self-improvement completed for '{}': quality={}/{} in {}s",
                    imp_query,
                    quality_indexed,
                    target,
                    task_start.elapsed().as_secs()
                );
            });
        }
    }

    (StatusCode::OK, Json(response)).into_response()
}

/// Meta-search endpoint
async fn meta_search_handler(
    State(state): State<Arc<ApiState>>,
    Query(params): Query<SearchParams>,
) -> impl IntoResponse {
    let start = Instant::now();
    let intent = state.app.intent_classifier.classify(&params.q);
    let response = state
        .app
        .aggregator
        .search_with_intent(&params.q, Some(&intent))
        .await;
    (
        StatusCode::OK,
        Json(SearchResponse {
            query: params.q,
            total: response.results.len(),
            results: response
                .results
                .into_iter()
                .map(|r| SearchResult {
                    id: hash_string(&r.url),
                    title: r.title,
                    url: r.url,
                    description: Some(r.description),
                    category: "meta".to_string(),
                    source: r.source,
                    media_type: r.media_type,
                    thumbnail_url: r.thumbnail_url,
                    intent_score: r.score,
                    relevance_score: r.score,
                    commercial_score: 0.0,
                    spam_score: 0.0,
                })
                .collect(),
            latency_ms: start.elapsed().as_millis() as u64,
            message: None,
            intent_scores: vec![],
            self_improving: false,
        }),
    )
}

/// Dedicated news search endpoint
async fn news_handler(
    State(state): State<Arc<ApiState>>,
    Query(params): Query<MediaSearchParams>,
) -> impl IntoResponse {
    let start = Instant::now();
    let aggregator = &state.app.aggregator;
    let response = if let Some(location) = &params.location {
        aggregator.search_news_geo(&params.q, location).await
    } else {
        aggregator.search_news(&params.q).await
    };

    let mut seen_urls = HashSet::new();
    let mut sources = HashSet::new();
    let results: Vec<NewsResult> = response
        .results
        .into_iter()
        .filter(|r| {
            if seen_urls.contains(&r.url) {
                return false;
            }
            seen_urls.insert(r.url.clone());
            sources.insert(r.source.clone());
            true
        })
        .map(|r| NewsResult {
            title: r.title,
            url: r.url,
            description: r.description,
            source: r.source,
            published_at: r.published_at,
            thumbnail_url: r.thumbnail_url,
        })
        .take(params.limit)
        .collect();

    (
        StatusCode::OK,
        Json(NewsResponse {
            query: params.q,
            total: results.len(),
            results,
            latency_ms: start.elapsed().as_millis() as u64,
            sources: sources.into_iter().collect(),
        }),
    )
}

/// Dedicated image search endpoint
async fn images_handler(
    State(state): State<Arc<ApiState>>,
    Query(params): Query<MediaSearchParams>,
) -> impl IntoResponse {
    let start = Instant::now();
    let (expanded_query, _) = rewrite_query(&params.q, &state.app.query_expansion_config);
    let filter = Some("media_type = \"image\"".to_string());
    let (local_docs, ext_res) = tokio::join!(
        state
            .app
            .indexer
            .search(&expanded_query, filter.as_deref(), Some(30)),
        state.app.image_search.search(&expanded_query, params.limit)
    );

    let mut results = Vec::new();
    let mut seen = HashSet::new();
    let mut sources = Vec::new();

    if let Ok(docs) = local_docs {
        for d in docs {
            seen.insert(d.url.clone());
            results.push(ImageResult {
                id: d.id,
                title: d.title,
                url: d.url,
                source: d.source,
                category: d.category,
                intent_score: d.intent_score,
                relevance_score: d.relevance_score,
                thumbnail_url: d.thumbnail_url,
                alt_text: d.description,
                photographer: None,
                width: None,
                height: None,
                avg_color: None,
            });
        }
    }

    if let Ok(ext) = ext_res {
        for i in ext {
            if !sources.contains(&i.source) {
                sources.push(i.source.clone());
            }
            if !seen.contains(&i.url) {
                results.push(ImageResult {
                    id: i.id,
                    title: i.title,
                    url: i.url,
                    source: i.source,
                    category: "".into(),
                    intent_score: 0.5,
                    relevance_score: 0.5,
                    thumbnail_url: i.thumbnail_url,
                    alt_text: None,
                    photographer: i.photographer,
                    width: i.width,
                    height: i.height,
                    avg_color: i.avg_color,
                });
            }
        }
    }

    (
        StatusCode::OK,
        Json(ImageResponse {
            query: params.q,
            total: results.len(),
            results: results.into_iter().take(params.limit).collect(),
            latency_ms: start.elapsed().as_millis() as u64,
            sources,
        }),
    )
}

/// Dedicated video search endpoint
async fn videos_handler(
    State(state): State<Arc<ApiState>>,
    Query(params): Query<MediaSearchParams>,
) -> impl IntoResponse {
    let start = Instant::now();
    let mut results = Vec::new();
    let mut seen = HashSet::new();
    let mut sources = Vec::new();

    if let Ok(docs) = state
        .app
        .indexer
        .search(&params.q, Some("media_type = \"video\""), Some(20))
        .await
    {
        for d in docs {
            seen.insert(d.url.clone());
            results.push(VideoResult {
                id: d.id,
                title: d.title,
                url: d.url,
                source: d.source,
                description: d.description,
                intent_score: d.intent_score,
                relevance_score: d.relevance_score,
                thumbnail_url: d.thumbnail_url,
                duration_secs: None,
                view_count: None,
                channel: None,
                published_at: None,
            });
        }
    }

    if let Ok(videos) = state.app.video_discovery.search(&params.q).await {
        for v in videos {
            if !seen.contains(&v.url) {
                if !sources.contains(&v.source) {
                    sources.push(v.source.clone());
                }
                results.push(VideoResult {
                    id: v.id,
                    title: v.title,
                    url: v.url,
                    source: v.source,
                    description: v.description,
                    intent_score: v.intent_score,
                    relevance_score: v.relevance_score,
                    thumbnail_url: Some(v.thumbnail),
                    duration_secs: v.duration_secs,
                    view_count: v.view_count,
                    channel: v.uploader,
                    published_at: v.published_at.map(|dt| dt.to_rfc3339()),
                });
            }
        }
    }

    (
        StatusCode::OK,
        Json(VideoResponse {
            query: params.q,
            total: results.len(),
            results: results.into_iter().take(params.limit).collect(),
            latency_ms: start.elapsed().as_millis() as u64,
            sources,
        }),
    )
}

async fn crawl_single_handler(
    State(state): State<Arc<ApiState>>,
    Query(params): Query<CrawlParams>,
) -> impl IntoResponse {
    let start = Instant::now();
    match state.app.crawler.fetch(&params.url).await {
        Ok(res) => (
            StatusCode::OK,
            Json(CrawlResponse {
                url: res.url,
                title: res.title,
                content_length: res.content.len(),
                success: true,
                latency_ms: start.elapsed().as_millis() as u64,
                error: None,
            }),
        ),
        Err(e) => (
            StatusCode::OK,
            Json(CrawlResponse {
                url: params.url,
                title: "".into(),
                content_length: 0,
                success: false,
                latency_ms: start.elapsed().as_millis() as u64,
                error: Some(e.to_string()),
            }),
        ),
    }
}

async fn crawl_batch_handler(
    State(state): State<Arc<ApiState>>,
    Json(req): Json<BatchCrawlRequest>,
) -> impl IntoResponse {
    let start = Instant::now();
    let urls: Vec<&str> = req.urls.iter().map(|s| s.as_str()).collect();
    match state.app.crawler.fetch_batch(urls).await {
        Ok(res) => (
            StatusCode::OK,
            Json(
                res.into_iter()
                    .map(|r| CrawlResponse {
                        url: r.url,
                        title: r.title,
                        content_length: r.content.len(),
                        success: true,
                        latency_ms: 0,
                        error: None,
                    })
                    .collect::<Vec<_>>(),
            ),
        ),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(vec![CrawlResponse {
                url: "batch".into(),
                title: "".into(),
                content_length: 0,
                success: false,
                latency_ms: start.elapsed().as_millis() as u64,
                error: Some(e.to_string()),
            }]),
        ),
    }
}

async fn metrics_handler(State(state): State<Arc<ApiState>>) -> impl IntoResponse {
    use prometheus::Encoder;
    let encoder = prometheus::TextEncoder::new();
    let mut buffer = Vec::new();
    let _ = encoder.encode(&state.metrics.registry.gather(), &mut buffer);
    String::from_utf8_lossy(&buffer).to_string()
}

async fn discovery_status_handler(State(state): State<Arc<ApiState>>) -> impl IntoResponse {
    let queue_size = state.app.discovery.queue_size().await.unwrap_or(0);
    Json(
        serde_json::json!({ "queue_size": queue_size, "last_cycle_secs": state.app.discovery.last_cycle_secs(), "max_queue_size": state.app.config.discovery.max_queue_size }),
    )
}

async fn discovery_enqueue_handler(
    State(state): State<Arc<ApiState>>,
    Json(req): Json<DiscoveryEnqueueRequest>,
) -> impl IntoResponse {
    let cat = req.category.as_deref().unwrap_or("manual");
    match state
        .app
        .discovery
        .enqueue_url_public(&req.url, req.priority, cat)
        .await
    {
        Ok(enqueued) => (
            StatusCode::OK,
            Json(DiscoveryEnqueueResponse {
                url: req.url,
                enqueued,
                error: None,
            }),
        ),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(DiscoveryEnqueueResponse {
                url: req.url,
                enqueued: false,
                error: Some(e.to_string()),
            }),
        ),
    }
}

async fn reindex_scores_handler(State(_state): State<Arc<ApiState>>) -> impl IntoResponse {
    (
        StatusCode::OK,
        Json(serde_json::json!({"status": "deprecated"})),
    )
}

async fn get_full_content_handler(
    Path(id): Path<String>,
    State(state): State<Arc<ApiState>>,
) -> impl IntoResponse {
    match state.app.redis.get_content(&id).await {
        Ok(Some(c)) => (
            StatusCode::OK,
            Json(serde_json::json!({"id": id, "content": c})),
        ),
        _ => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({"error": "not found"})),
        ),
    }
}