codemem-engine 0.18.0

Domain logic engine for Codemem: indexing, hooks, watching, scoring, recall, consolidation
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
//! API surface detection: endpoint definitions and HTTP client calls.
//!
//! Post-processing pass on extracted symbols to detect REST/HTTP endpoints
//! and client calls for cross-service linking.

use crate::index::symbol::{Reference, ReferenceKind, Symbol, SymbolKind};
use std::sync::LazyLock;

// ── Precompiled regexes ─────────────────────────────────────────────────────

static RE_QUOTED_STRING: LazyLock<regex::Regex> =
    LazyLock::new(|| regex::Regex::new(r#"["']([^"']+)["']"#).unwrap());

static RE_METHODS_PARAM: LazyLock<regex::Regex> =
    LazyLock::new(|| regex::Regex::new(r#"methods\s*=\s*\[([^\]]+)\]"#).unwrap());

static RE_NESTJS_METHOD: LazyLock<regex::Regex> =
    LazyLock::new(|| regex::Regex::new(r"^@(Get|Post|Put|Delete|Patch|Head|Options)\b").unwrap());

static RE_FLASK_PARAM: LazyLock<regex::Regex> =
    LazyLock::new(|| regex::Regex::new(r"<(?:\w+:)?(\w+)>").unwrap());

static RE_EXPRESS_PARAM: LazyLock<regex::Regex> =
    LazyLock::new(|| regex::Regex::new(r":(\w+)").unwrap());

/// A detected API endpoint.
#[derive(Debug, Clone, PartialEq)]
pub struct DetectedEndpoint {
    /// Endpoint ID: "ep:{namespace}:{method}:{path}"
    pub id: String,
    /// HTTP method (GET, POST, PUT, DELETE, PATCH, etc.) or None for catch-all.
    pub method: Option<String>,
    /// URL path pattern, normalized (e.g., "/api/users/{id}").
    pub path: String,
    /// Handler symbol qualified name.
    pub handler: String,
    /// File path of the handler.
    pub file_path: String,
    /// Line number.
    pub line: usize,
}

/// A detected HTTP client call.
#[derive(Debug, Clone, PartialEq)]
pub struct DetectedClientCall {
    /// Symbol making the HTTP call.
    pub caller: String,
    /// HTTP method if detectable.
    pub method: Option<String>,
    /// URL pattern extracted from the call (may be partial/relative).
    pub url_pattern: Option<String>,
    /// The HTTP client library being used.
    pub client_library: String,
    /// File path.
    pub file_path: String,
    /// Line number.
    pub line: usize,
}

/// A detected event channel interaction (publish or subscribe).
#[derive(Debug, Clone, PartialEq)]
pub struct DetectedEventCall {
    /// Symbol making the event call.
    pub caller: String,
    /// Channel/topic name (if extractable from the call target).
    pub channel: Option<String>,
    /// "publish" or "subscribe".
    pub direction: String,
    /// Protocol: kafka, rabbitmq, redis, sqs, sns, nats.
    pub protocol: String,
    /// File path.
    pub file_path: String,
    /// Line number.
    pub line: usize,
}

/// Result of API surface detection.
#[derive(Debug, Default)]
pub struct ApiSurfaceResult {
    pub endpoints: Vec<DetectedEndpoint>,
    pub client_calls: Vec<DetectedClientCall>,
    pub event_calls: Vec<DetectedEventCall>,
}

/// Detect API endpoints from extracted symbols.
///
/// Scans symbol attributes/decorators for framework-specific route patterns:
/// - Python: `@app.route`, `@router.get`, `@api_view`, `@GetMapping` (for Django views, Flask, FastAPI)
/// - TypeScript: `@Get`, `@Post` (NestJS), `app.get` (Express) — detected from call references
/// - Java: `@GetMapping`, `@PostMapping`, `@RequestMapping`
/// - Go: detected via call patterns (`http.HandleFunc`, `router.GET`, etc.)
pub fn detect_endpoints(symbols: &[Symbol], namespace: &str) -> Vec<DetectedEndpoint> {
    let mut endpoints = Vec::new();

    for sym in symbols {
        // Check attributes/decorators for route patterns
        for attr in &sym.attributes {
            if let Some(ep) = parse_route_decorator(attr, sym, namespace) {
                endpoints.push(ep);
            }
        }

        // Check for Django URL pattern-style views (class-based views)
        if is_django_view_class(sym) {
            // Django CBVs: methods like get(), post() on View subclasses
            // The URL pattern linking happens elsewhere; here we just mark the handler
            for method in &["get", "post", "put", "patch", "delete"] {
                if sym.kind == SymbolKind::Method && sym.name == *method {
                    if let Some(parent) = &sym.parent {
                        endpoints.push(DetectedEndpoint {
                            id: format!("ep:{namespace}:{}:view:{parent}", method.to_uppercase()),
                            method: Some(method.to_uppercase()),
                            path: format!("view:{parent}"), // placeholder until URL conf resolved
                            handler: sym.qualified_name.clone(),
                            file_path: sym.file_path.clone(),
                            line: sym.line_start,
                        });
                    }
                }
            }
        }
    }

    endpoints
}

/// Parse a route decorator/annotation string into an endpoint.
///
/// Handles patterns like:
/// - `@app.route("/users")` or `@app.route("/users", methods=["GET", "POST"])`
/// - `@router.get("/users/{id}")` or `@app.get("/users/<int:id>")`
/// - `@GetMapping("/users")` or `@RequestMapping(value="/users", method=RequestMethod.GET)`
/// - `@Get("/users")` (NestJS)
/// - `@api_view(["GET"])` (DRF — path comes from urls.py, not decorator)
fn parse_route_decorator(attr: &str, sym: &Symbol, namespace: &str) -> Option<DetectedEndpoint> {
    let attr_lower = attr.to_lowercase();

    // Flask/FastAPI style: @app.route("/path") or @router.get("/path")
    if attr_lower.contains("route(")
        || attr_lower.contains(".get(")
        || attr_lower.contains(".post(")
        || attr_lower.contains(".put(")
        || attr_lower.contains(".delete(")
        || attr_lower.contains(".patch(")
    {
        let method = extract_http_method_from_decorator(attr);
        let path = extract_path_from_decorator(attr)?;
        let normalized_path = normalize_path_pattern(&path);

        return Some(DetectedEndpoint {
            id: format!(
                "ep:{namespace}:{}:{normalized_path}",
                method.as_deref().unwrap_or("ANY")
            ),
            method,
            path: normalized_path,
            handler: sym.qualified_name.clone(),
            file_path: sym.file_path.clone(),
            line: sym.line_start,
        });
    }

    // Spring style: @GetMapping("/path"), @PostMapping("/path"), @RequestMapping(...)
    if attr_lower.contains("mapping(") || attr_lower.contains("mapping\"") {
        let method = extract_spring_method(attr);
        let path = extract_path_from_decorator(attr)?;
        let normalized_path = normalize_path_pattern(&path);

        return Some(DetectedEndpoint {
            id: format!(
                "ep:{namespace}:{}:{normalized_path}",
                method.as_deref().unwrap_or("ANY")
            ),
            method,
            path: normalized_path,
            handler: sym.qualified_name.clone(),
            file_path: sym.file_path.clone(),
            line: sym.line_start,
        });
    }

    // NestJS style: @Get("/path"), @Post("/path")
    if let Some(method) = extract_nestjs_method(attr) {
        let path = extract_path_from_decorator(attr).unwrap_or_else(|| "/".to_string());
        let normalized_path = normalize_path_pattern(&path);

        return Some(DetectedEndpoint {
            id: format!("ep:{namespace}:{method}:{normalized_path}"),
            method: Some(method),
            path: normalized_path,
            handler: sym.qualified_name.clone(),
            file_path: sym.file_path.clone(),
            line: sym.line_start,
        });
    }

    None
}

/// Detect HTTP client calls from extracted references.
///
/// Scans call references for known HTTP client patterns:
/// - Python: `requests.get`/`post`/..., `httpx.get`/`post`/..., `aiohttp`
/// - TS/JS: `fetch`, `axios.get`/`post`/..., `got`
/// - Java: `RestTemplate`, `WebClient`, `HttpClient`
/// - Go: `http.Get`, `http.Post`, `http.NewRequest`
pub fn detect_client_calls(references: &[Reference]) -> Vec<DetectedClientCall> {
    let mut calls = Vec::new();

    for r in references {
        if r.kind != ReferenceKind::Call {
            continue;
        }

        if let Some(call) = parse_client_call(&r.target_name, r) {
            calls.push(call);
        }
    }

    calls
}

fn parse_client_call(target: &str, reference: &Reference) -> Option<DetectedClientCall> {
    let target_lower = target.to_lowercase();

    // Python: requests.get, requests.post, httpx.get, etc.
    if target_lower.starts_with("requests.") || target_lower.starts_with("httpx.") {
        let parts: Vec<&str> = target.splitn(2, '.').collect();
        let library = parts[0].to_string();
        let method = parts.get(1).and_then(|m| http_method_from_name(m));

        return Some(DetectedClientCall {
            caller: reference.source_qualified_name.clone(),
            method,
            url_pattern: None, // would need string literal analysis
            client_library: library,
            file_path: reference.file_path.clone(),
            line: reference.line,
        });
    }

    // TS/JS: fetch (global function)
    if target_lower == "fetch" {
        return Some(DetectedClientCall {
            caller: reference.source_qualified_name.clone(),
            method: None, // determined by options argument
            url_pattern: None,
            client_library: "fetch".to_string(),
            file_path: reference.file_path.clone(),
            line: reference.line,
        });
    }

    // TS/JS: axios.get, axios.post, etc.
    if target_lower.starts_with("axios.") {
        let method = target.split('.').nth(1).and_then(http_method_from_name);
        return Some(DetectedClientCall {
            caller: reference.source_qualified_name.clone(),
            method,
            url_pattern: None,
            client_library: "axios".to_string(),
            file_path: reference.file_path.clone(),
            line: reference.line,
        });
    }

    // Go: http.Get, http.Post, http.NewRequest
    if target_lower.starts_with("http.")
        && (target.contains("Get")
            || target.contains("Post")
            || target.contains("NewRequest")
            || target.contains("Do"))
    {
        let method = if target.contains("Get") {
            Some("GET".to_string())
        } else if target.contains("Post") {
            Some("POST".to_string())
        } else {
            None
        };
        return Some(DetectedClientCall {
            caller: reference.source_qualified_name.clone(),
            method,
            url_pattern: None,
            client_library: "net/http".to_string(),
            file_path: reference.file_path.clone(),
            line: reference.line,
        });
    }

    // Java: RestTemplate, WebClient
    if target_lower.contains("resttemplate")
        || target_lower.contains("webclient")
        || target_lower.contains("httpclient")
    {
        return Some(DetectedClientCall {
            caller: reference.source_qualified_name.clone(),
            method: None,
            url_pattern: None,
            client_library: target.split('.').next().unwrap_or(target).to_string(),
            file_path: reference.file_path.clone(),
            line: reference.line,
        });
    }

    None
}

// ── Helper functions ──

/// Extract the first quoted string from a decorator (the path argument).
fn extract_path_from_decorator(attr: &str) -> Option<String> {
    RE_QUOTED_STRING.captures(attr).map(|c| c[1].to_string())
}

/// Extract HTTP method from a decorator like `@app.get(...)` or `@router.post(...)`
fn extract_http_method_from_decorator(attr: &str) -> Option<String> {
    let attr_lower = attr.to_lowercase();
    for method in &["get", "post", "put", "delete", "patch", "head", "options"] {
        // Match .get( or .post( etc
        if attr_lower.contains(&format!(".{method}(")) {
            return Some(method.to_uppercase());
        }
    }
    // @app.route with methods= parameter
    if attr_lower.contains("route(") {
        if let Some(methods) = extract_methods_param(attr) {
            return methods.first().cloned();
        }
    }
    None
}

/// Extract `methods=["GET", "POST"]` from a route decorator.
fn extract_methods_param(attr: &str) -> Option<Vec<String>> {
    let caps = RE_METHODS_PARAM.captures(attr)?;
    let methods_str = &caps[1];
    let methods: Vec<String> = methods_str
        .split(',')
        .map(|m| {
            m.trim()
                .trim_matches(|c| c == '"' || c == '\'')
                .to_uppercase()
        })
        .filter(|m| !m.is_empty())
        .collect();
    if methods.is_empty() {
        None
    } else {
        Some(methods)
    }
}

/// Extract HTTP method from Spring annotations.
fn extract_spring_method(attr: &str) -> Option<String> {
    let attr_lower = attr.to_lowercase();
    if attr_lower.contains("getmapping") {
        return Some("GET".to_string());
    }
    if attr_lower.contains("postmapping") {
        return Some("POST".to_string());
    }
    if attr_lower.contains("putmapping") {
        return Some("PUT".to_string());
    }
    if attr_lower.contains("deletemapping") {
        return Some("DELETE".to_string());
    }
    if attr_lower.contains("patchmapping") {
        return Some("PATCH".to_string());
    }
    // @RequestMapping with method= parameter
    if attr_lower.contains("requestmapping") {
        if attr_lower.contains("get") {
            return Some("GET".to_string());
        }
        if attr_lower.contains("post") {
            return Some("POST".to_string());
        }
    }
    None
}

/// Extract HTTP method from NestJS decorators.
fn extract_nestjs_method(attr: &str) -> Option<String> {
    // NestJS: @Get, @Post, @Put, @Delete, @Patch
    // These are standalone decorators (not method calls on an object)
    RE_NESTJS_METHOD.captures(attr).map(|c| c[1].to_uppercase())
}

/// Normalize a URL path pattern:
/// - Flask: `/users/<int:id>` -> `/users/{id}`
/// - Express: `/users/:id` -> `/users/{id}`
/// - Spring: `/users/{id}` -> already normalized
/// - Go: `/users/{id}` -> already normalized
pub fn normalize_path_pattern(path: &str) -> String {
    let mut result = path.to_string();

    // Flask: <type:name> or <name> → {name}
    result = RE_FLASK_PARAM.replace_all(&result, "{$1}").to_string();

    // Express: :name → {name}
    let express_re = &*RE_EXPRESS_PARAM;
    result = express_re.replace_all(&result, "{$1}").to_string();

    // Ensure leading slash
    if !result.starts_with('/') {
        result = format!("/{result}");
    }

    // Remove trailing slash (unless it's just "/")
    if result.len() > 1 && result.ends_with('/') {
        result.pop();
    }

    result
}

/// Check if a symbol looks like a Django class-based view.
fn is_django_view_class(sym: &Symbol) -> bool {
    if sym.kind != SymbolKind::Method {
        return false;
    }
    // Check if parent class has View-like attributes
    sym.parent
        .as_ref()
        .is_some_and(|p| p.ends_with("View") || p.ends_with("ViewSet") || p.ends_with("APIView"))
}

/// Map a method name to HTTP method string.
fn http_method_from_name(name: &str) -> Option<String> {
    match name.to_lowercase().as_str() {
        "get" => Some("GET".to_string()),
        "post" => Some("POST".to_string()),
        "put" => Some("PUT".to_string()),
        "delete" => Some("DELETE".to_string()),
        "patch" => Some("PATCH".to_string()),
        "head" => Some("HEAD".to_string()),
        "options" => Some("OPTIONS".to_string()),
        _ => None,
    }
}

/// Match a client call URL against registered endpoints.
///
/// Returns the best matching endpoint with confidence.
pub fn match_endpoint<'a>(
    url_path: &str,
    method: Option<&str>,
    endpoints: &'a [DetectedEndpoint],
) -> Option<(&'a DetectedEndpoint, f64)> {
    let normalized = normalize_path_pattern(url_path);
    let mut best: Option<(&DetectedEndpoint, f64)> = None;

    for ep in endpoints {
        // Base confidence from path matching
        let base_confidence: f64 = if ep.path == normalized {
            1.0
        } else if paths_match_with_params(&normalized, &ep.path) {
            0.9
        } else if normalized.starts_with(&ep.path) || ep.path.starts_with(&normalized) {
            0.7
        } else {
            continue;
        };

        let mut confidence = base_confidence;

        // Method match bonus
        if let (Some(call_method), Some(ep_method)) = (method, ep.method.as_deref()) {
            if call_method.eq_ignore_ascii_case(ep_method) {
                confidence += 0.05;
            } else {
                confidence -= 0.1;
            }
        }

        confidence = confidence.clamp(0.0, 1.0);

        if best.is_none() || confidence > best.unwrap().1 {
            best = Some((ep, confidence));
        }
    }

    // Only return matches above threshold
    best.filter(|(_, c)| *c >= 0.5)
}

/// Check if two paths match allowing parameter substitution.
/// e.g., "/users/123" matches "/users/{id}"
fn paths_match_with_params(actual: &str, pattern: &str) -> bool {
    let actual_parts: Vec<&str> = actual.split('/').collect();
    let pattern_parts: Vec<&str> = pattern.split('/').collect();

    if actual_parts.len() != pattern_parts.len() {
        return false;
    }

    actual_parts
        .iter()
        .zip(pattern_parts.iter())
        .all(|(a, p)| a == p || (p.starts_with('{') && p.ends_with('}')))
}

// ── Feature 4: Go/Express endpoint detection from call references ──────────

/// Route-registration call patterns: (target substring, framework).
const ROUTE_REGISTRATION_PATTERNS: &[(&str, &str)] = &[
    // Go stdlib
    ("http.HandleFunc", "go-http"),
    ("http.Handle", "go-http"),
    // Go Gin
    ("router.GET", "gin"),
    ("router.POST", "gin"),
    ("router.PUT", "gin"),
    ("router.DELETE", "gin"),
    ("router.PATCH", "gin"),
    // Go Echo
    ("e.GET", "echo"),
    ("e.POST", "echo"),
    ("e.PUT", "echo"),
    ("e.DELETE", "echo"),
    ("e.PATCH", "echo"),
    // Go Chi / gorilla mux
    ("mux.Handle", "mux"),
    ("mux.HandleFunc", "mux"),
    // Express.js
    ("app.get", "express"),
    ("app.post", "express"),
    ("app.put", "express"),
    ("app.delete", "express"),
    ("app.patch", "express"),
    ("router.get", "express"),
    ("router.post", "express"),
    ("router.put", "express"),
    ("router.delete", "express"),
    ("router.patch", "express"),
];

/// Detect API endpoints from call references (Go, Express.js, etc.).
///
/// These frameworks register routes via function calls rather than decorators,
/// so they can't be detected from `Symbol.attributes`. Instead we scan
/// `Reference` entries for known route-registration call targets.
pub fn detect_endpoints_from_references(
    references: &[Reference],
    namespace: &str,
) -> Vec<DetectedEndpoint> {
    let mut endpoints = Vec::new();

    for r in references {
        if r.kind != ReferenceKind::Call {
            continue;
        }

        for &(pattern, _framework) in ROUTE_REGISTRATION_PATTERNS {
            if r.target_name == pattern
                || r.target_name.ends_with(&format!(
                    ".{}",
                    pattern.split('.').next_back().unwrap_or("")
                ))
            {
                let method = extract_method_from_call_target(&r.target_name);
                // Path is not available from reference data (would need string
                // literal analysis). Store handler-based identifier so the
                // endpoint is at least registered for cross-service matching.
                let handler_path = format!("handler:{}", r.source_qualified_name);
                endpoints.push(DetectedEndpoint {
                    id: format!(
                        "ep:{namespace}:{}:{handler_path}",
                        method.as_deref().unwrap_or("ANY")
                    ),
                    method,
                    path: handler_path,
                    handler: r.source_qualified_name.clone(),
                    file_path: r.file_path.clone(),
                    line: r.line,
                });
                break;
            }
        }
    }

    endpoints
}

/// Extract HTTP method from a route-registration call target.
fn extract_method_from_call_target(target: &str) -> Option<String> {
    let last_segment = target.rsplit('.').next().unwrap_or(target);
    match last_segment {
        "GET" | "get" => Some("GET".to_string()),
        "POST" | "post" => Some("POST".to_string()),
        "PUT" | "put" => Some("PUT".to_string()),
        "DELETE" | "delete" => Some("DELETE".to_string()),
        "PATCH" | "patch" => Some("PATCH".to_string()),
        // HandleFunc, Handle — method not determinable from call target
        _ => None,
    }
}

// ── Feature 3: Event framework pattern detection ──────────────────────────

/// Event framework call patterns: (target pattern, protocol, direction).
const EVENT_PATTERNS: &[(&str, &str, &str)] = &[
    // Kafka
    ("producer.send", "kafka", "publish"),
    ("producer.produce", "kafka", "publish"),
    ("consumer.subscribe", "kafka", "subscribe"),
    ("consumer.poll", "kafka", "subscribe"),
    // RabbitMQ
    ("channel.basic_publish", "rabbitmq", "publish"),
    ("channel.basic_consume", "rabbitmq", "subscribe"),
    ("channel.publish", "rabbitmq", "publish"),
    ("channel.consume", "rabbitmq", "subscribe"),
    // Redis pub/sub
    ("redis.publish", "redis", "publish"),
    ("redis.subscribe", "redis", "subscribe"),
    ("client.publish", "redis", "publish"),
    ("client.subscribe", "redis", "subscribe"),
    // AWS SQS
    ("sqs.send_message", "sqs", "publish"),
    ("sqs.receive_message", "sqs", "subscribe"),
    ("sqs.sendMessage", "sqs", "publish"),
    ("sqs.receiveMessage", "sqs", "subscribe"),
    // AWS SNS
    ("sns.publish", "sns", "publish"),
    // NATS
    ("nc.publish", "nats", "publish"),
    ("nc.subscribe", "nats", "subscribe"),
    ("nats.publish", "nats", "publish"),
    ("nats.subscribe", "nats", "subscribe"),
    // EventEmitter / generic
    ("emitter.emit", "event", "publish"),
    ("emitter.on", "event", "subscribe"),
];

/// Java/Kotlin annotation patterns that indicate event listeners.
const EVENT_ANNOTATION_PATTERNS: &[(&str, &str, &str)] = &[
    ("KafkaListener", "kafka", "subscribe"),
    ("RabbitListener", "rabbitmq", "subscribe"),
    ("SqsListener", "sqs", "subscribe"),
    ("JmsListener", "jms", "subscribe"),
    ("EventListener", "event", "subscribe"),
];

/// Detect event channel interactions from call references and symbol annotations.
pub fn detect_event_calls(references: &[Reference], symbols: &[Symbol]) -> Vec<DetectedEventCall> {
    let mut events = Vec::new();

    // Scan call references for event framework patterns
    for r in references {
        if r.kind != ReferenceKind::Call {
            continue;
        }

        for &(pattern, protocol, direction) in EVENT_PATTERNS {
            if r.target_name == pattern || r.target_name.ends_with(pattern) {
                events.push(DetectedEventCall {
                    caller: r.source_qualified_name.clone(),
                    channel: None, // Would need string literal analysis
                    direction: direction.to_string(),
                    protocol: protocol.to_string(),
                    file_path: r.file_path.clone(),
                    line: r.line,
                });
                break;
            }
        }
    }

    // Scan symbol annotations for event listener patterns (Java/Kotlin style)
    for sym in symbols {
        for attr in &sym.attributes {
            for &(annotation, protocol, direction) in EVENT_ANNOTATION_PATTERNS {
                if attr.contains(annotation) {
                    events.push(DetectedEventCall {
                        caller: sym.qualified_name.clone(),
                        channel: extract_path_from_decorator(attr),
                        direction: direction.to_string(),
                        protocol: protocol.to_string(),
                        file_path: sym.file_path.clone(),
                        line: sym.line_start,
                    });
                    break;
                }
            }
        }
    }

    events
}

// ── Feature 5: Cross-service edge matching ────────────────────────────────

/// Match event producers to consumers on the same channel and protocol.
/// Returns pairs of (producer_caller, consumer_caller, channel, protocol, confidence).
pub fn match_event_channels(
    producers: &[DetectedEventCall],
    consumers: &[DetectedEventCall],
) -> Vec<(String, String, String, String, f64)> {
    let mut matches = Vec::new();

    for producer in producers {
        for consumer in consumers {
            if producer.protocol != consumer.protocol {
                continue;
            }
            // Require at least one side to have a known channel name.
            // Protocol-only matching (both channels unknown) would create O(n²)
            // spurious edges between all producers and consumers of the same
            // protocol within a namespace.
            match (&producer.channel, &consumer.channel) {
                (Some(pc), Some(cc)) => {
                    let confidence = if pc == cc {
                        0.95
                    } else if channels_match_pattern(pc, cc) {
                        0.8
                    } else {
                        continue;
                    };
                    matches.push((
                        producer.caller.clone(),
                        consumer.caller.clone(),
                        pc.clone(),
                        producer.protocol.clone(),
                        confidence,
                    ));
                }
                // One side has a channel, other doesn't — skip (insufficient data)
                // Both unknown — skip (would be O(n²) noise)
                _ => continue,
            }
        }
    }

    matches
}

/// Check if two channel names match, accounting for wildcards.
/// e.g., "orders.*" matches "orders.created"
fn channels_match_pattern(a: &str, b: &str) -> bool {
    if a.contains('*') || a.contains('#') {
        let prefix = a.trim_end_matches(['*', '#', '.']);
        b.starts_with(prefix)
    } else if b.contains('*') || b.contains('#') {
        let prefix = b.trim_end_matches(['*', '#', '.']);
        a.starts_with(prefix)
    } else {
        false
    }
}

#[cfg(test)]
#[path = "tests/api_surface_tests.rs"]
mod tests;