ryo-query-language 0.1.0

RyoQL - Structured code query language for AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
//! RyoQL Schema - 型定義

use ryo_pattern::{BodyMatch, Relations};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

// =============================================================================
// Query
// =============================================================================

/// RyoQLクエリ
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(
    title = "RyoQL Query",
    description = "AI agent-friendly structured code query"
)]
pub struct Query {
    /// 何を探すか
    pub kind: QueryKind,

    /// どう絞り込むか
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub r#match: Option<MatchAttrs>,

    /// ネスト条件
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub inner: Vec<Query>,

    /// Or/And用: サブクエリ
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub queries: Vec<Query>,

    /// Pattern用: パターン名
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// Body pattern matching (RyoPattern extension)
    ///
    /// Match patterns within function/method bodies.
    /// ```yaml
    /// body:
    ///   contains:
    ///     - node: MethodCall
    ///       method: { name: "unwrap" }
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<BodyMatch>,

    /// Relation conditions with logical grouping (RyoPattern extension)
    ///
    /// Filter by graph relationships: `any`/`all`/`none`.
    /// ```yaml
    /// relations:
    ///   any:
    ///     - kind: Calls
    ///       target: { kind: Function, match: { name: "unwrap" } }
    ///   none:
    ///     - kind: DependsOn
    ///       target: { kind: Struct, match: { name: "Database" } }
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub relations: Option<Relations>,

    /// LSP連携(オプション)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolve: Option<ResolveConfig>,

    /// 検索範囲
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scope: Option<Scope>,

    /// 出力形式
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub view: Option<ViewMode>,

    /// 件数制限
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
}

// =============================================================================
// QueryKind
// =============================================================================

/// クエリ対象の種類
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum QueryKind {
    /// 全種類を検索(初回探索用)
    Any,

    // 基本
    /// Free functions のみ。impl内のメソッド (Method) は含まない。
    /// Method単体をクエリする機能は未対応。
    Function,
    /// `struct` 定義。
    Struct,
    /// `enum` 定義。
    Enum,
    /// `trait` 定義。
    Trait,
    /// `impl` ブロック。
    Impl,
    /// `mod` 定義。
    Mod,
    /// `const` 定義。
    Const,
    /// `static` 定義。
    Static,
    /// `type` エイリアス定義。
    TypeAlias,

    // inner用
    /// 戻り値型 (inner クエリ用)。
    ReturnType,
    /// 関数パラメータ (inner クエリ用)。
    Parameter,
    /// struct フィールド (inner クエリ用)。
    Field,
    /// enum バリアント (inner クエリ用)。
    Variant,

    // 複合
    /// 子クエリの和集合。
    Or,
    /// 子クエリの積集合。
    And,

    // 事前定義パターン
    /// 事前定義パターンによる検索。
    Pattern,

    /// リテラル検索(文字列、数値、真偽値等)
    /// requires: literal-search feature in ryo-analysis
    Literal,
}

// =============================================================================
// MatchAttrs
// =============================================================================

/// マッチング条件
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct MatchAttrs {
    /// パターンマッチ (globパターンのショートハンド)
    ///
    /// `"*Config"` は `{"name": {"glob": "*Config"}}` と等価。
    /// nameと同時に指定された場合、nameが優先される。
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pattern: Option<String>,

    /// 名前マッチ (詳細指定)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<NameMatcher>,

    /// SymbolId直接指定
    ///
    /// discoverで出力される `SymbolId(165v1)` 形式、または `165v1` 形式で指定。
    /// 指定された場合、他のマッチング条件より優先される(直接lookup)。
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub symbol_id: Option<String>,

    /// Ignore ASCII case when matching (A-Z == a-z)
    ///
    /// Applies to `pattern` shorthand. For `name` detailed matching,
    /// use `name.ignore_case` instead.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ignore_case: Option<bool>,

    /// Ignore word separators and casing style (snake_case == camelCase == PascalCase)
    ///
    /// Applies to `pattern` shorthand. For `name` detailed matching,
    /// use `name.ignore_word_separate` instead.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ignore_word_separate: Option<bool>,

    /// 可視性
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vis: Option<Visibility>,

    /// async関数か
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub is_async: Option<bool>,

    /// unsafe関数か
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub is_unsafe: Option<bool>,

    /// selfレシーバー種別
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub receiver: Option<ReceiverKind>,

    /// アトリビュート
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attributes: Option<Vec<String>>,

    /// ジェネリクス条件
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub generics: Option<GenericsMatch>,

    /// 失敗時リカバリー
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_empty: Option<RecoveryStrategy>,

    /// リテラル種別フィルタ(Literalクエリ用)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lit_type: Option<LiteralType>,

    /// 親シンボルでフィルタ(Variant, Field, Method用)
    ///
    /// 例: `{"kind": "Variant", "match": {"parent": "Filter"}}` →
    /// Filter enumのVariantのみを返す
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent: Option<NameMatcher>,
}

// =============================================================================
// LiteralType
// =============================================================================

/// リテラルの種類(Literalクエリ用フィルタ)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum LiteralType {
    /// 文字列リテラル: `"hello"`, `r#"raw"#`
    String,
    /// バイト文字列: `b"bytes"`
    ByteStr,
    /// 文字: `'a'`
    Char,
    /// バイト: `b'x'`
    Byte,
    /// 整数: `42`, `0xFF`
    Int,
    /// 浮動小数点: `3.14`
    Float,
    /// 真偽値: `true`, `false`
    Bool,
}

// =============================================================================
// NameMatcher
// =============================================================================

/// 名前マッチング方法
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum NameMatcher {
    /// 完全一致 (文字列直接指定)
    Exact(String),
    /// 詳細指定
    Detailed(NameMatcherDetailed),
}

/// 詳細な名前マッチング
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct NameMatcherDetailed {
    /// 部分一致 (contains)。
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub contains: Option<String>,

    /// 前方一致 (starts_with)。
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub starts_with: Option<String>,

    /// 後方一致 (ends_with)。
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ends_with: Option<String>,

    /// 正規表現マッチ。
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub regex: Option<String>,

    /// glob パターンマッチ (`*`/`?`)。
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub glob: Option<String>,

    /// Ignore ASCII case when matching (A-Z == a-z)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ignore_case: Option<bool>,

    /// Ignore word separators and casing style (snake_case == camelCase == PascalCase)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ignore_word_separate: Option<bool>,
}

impl NameMatcher {
    /// 名前がマッチするか判定
    pub fn matches(&self, name: &str) -> bool {
        match self {
            NameMatcher::Exact(pattern) => name == pattern,
            NameMatcher::Detailed(d) => d.matches(name),
        }
    }
}

impl NameMatcherDetailed {
    /// Check if the name matches all specified criteria.
    pub fn matches(&self, name: &str) -> bool {
        let ignore_case = self.ignore_case.unwrap_or(false);
        let ignore_word_separate = self.ignore_word_separate.unwrap_or(false);

        // For word-separate matching, normalize both pattern and name to words
        if ignore_word_separate {
            let name_words = normalize_to_words(name);

            if let Some(ref contains) = self.contains {
                let pattern_words = normalize_to_words(contains);
                if !contains_words(&name_words, &pattern_words) {
                    return false;
                }
            }
            if let Some(ref starts) = self.starts_with {
                let pattern_words = normalize_to_words(starts);
                if !starts_with_words(&name_words, &pattern_words) {
                    return false;
                }
            }
            if let Some(ref ends) = self.ends_with {
                let pattern_words = normalize_to_words(ends);
                if !ends_with_words(&name_words, &pattern_words) {
                    return false;
                }
            }
            if let Some(ref pattern) = self.glob {
                let pattern_words = normalize_pattern_to_words(pattern);
                if !match_word_pattern(&pattern_words, &name_words) {
                    return false;
                }
            }
            // Regex with word-separate is not supported
            if let Some(ref pattern) = self.regex {
                if let Ok(re) = regex::Regex::new(pattern) {
                    if !re.is_match(name) {
                        return false;
                    }
                }
            }
        } else if ignore_case {
            // Case-insensitive matching
            let name_lower = name.to_ascii_lowercase();

            if let Some(ref contains) = self.contains {
                if !name_lower.contains(&contains.to_ascii_lowercase()) {
                    return false;
                }
            }
            if let Some(ref starts) = self.starts_with {
                if !name_lower.starts_with(&starts.to_ascii_lowercase()) {
                    return false;
                }
            }
            if let Some(ref ends) = self.ends_with {
                if !name_lower.ends_with(&ends.to_ascii_lowercase()) {
                    return false;
                }
            }
            if let Some(ref pattern) = self.regex {
                if let Ok(re) = regex::RegexBuilder::new(pattern)
                    .case_insensitive(true)
                    .build()
                {
                    if !re.is_match(name) {
                        return false;
                    }
                }
            }
            if let Some(ref pattern) = self.glob {
                if let Ok(glob_pattern) = glob::Pattern::new(&pattern.to_ascii_lowercase()) {
                    if !glob_pattern.matches(&name_lower) {
                        return false;
                    }
                }
            }
        } else {
            // Default: case-sensitive matching
            if let Some(ref contains) = self.contains {
                if !name.contains(contains) {
                    return false;
                }
            }
            if let Some(ref starts) = self.starts_with {
                if !name.starts_with(starts) {
                    return false;
                }
            }
            if let Some(ref ends) = self.ends_with {
                if !name.ends_with(ends) {
                    return false;
                }
            }
            if let Some(ref pattern) = self.regex {
                if let Ok(re) = regex::Regex::new(pattern) {
                    if !re.is_match(name) {
                        return false;
                    }
                }
            }
            if let Some(ref pattern) = self.glob {
                if let Ok(glob_pattern) = glob::Pattern::new(pattern) {
                    if !glob_pattern.matches(name) {
                        return false;
                    }
                }
            }
        }
        true
    }
}

// =============================================================================
// Word Normalization Utilities (duplicated from ryo-analysis for independence)
// =============================================================================

/// Normalize an identifier to lowercase words.
fn normalize_to_words(s: &str) -> Vec<String> {
    let mut words = Vec::new();
    let mut current_word = String::new();

    let chars: Vec<char> = s.chars().collect();
    let len = chars.len();

    for i in 0..len {
        let c = chars[i];

        if c == '_' {
            if !current_word.is_empty() {
                words.push(current_word.to_ascii_lowercase());
                current_word.clear();
            }
        } else if c.is_ascii_uppercase() {
            let prev_lower = i > 0 && chars[i - 1].is_ascii_lowercase();
            let next_lower = i + 1 < len && chars[i + 1].is_ascii_lowercase();

            if (prev_lower || (i > 0 && !current_word.is_empty() && next_lower))
                && !current_word.is_empty()
            {
                words.push(current_word.to_ascii_lowercase());
                current_word.clear();
            }
            current_word.push(c);
        } else {
            current_word.push(c);
        }
    }

    if !current_word.is_empty() {
        words.push(current_word.to_ascii_lowercase());
    }

    words
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum PatternWord {
    Literal(String),
    AnyWords,
    AnyChar,
}

fn normalize_pattern_to_words(pattern: &str) -> Vec<PatternWord> {
    let mut result = Vec::new();
    let mut current = String::new();
    let mut in_wildcard_seq = false;

    for c in pattern.chars() {
        match c {
            '*' => {
                if !current.is_empty() {
                    result.extend(
                        normalize_to_words(&current)
                            .into_iter()
                            .map(PatternWord::Literal),
                    );
                    current.clear();
                }
                if !in_wildcard_seq {
                    result.push(PatternWord::AnyWords);
                    in_wildcard_seq = true;
                }
            }
            '?' => {
                if !current.is_empty() {
                    result.extend(
                        normalize_to_words(&current)
                            .into_iter()
                            .map(PatternWord::Literal),
                    );
                    current.clear();
                }
                result.push(PatternWord::AnyChar);
                in_wildcard_seq = false;
            }
            '_' => {
                if !current.is_empty() {
                    result.extend(
                        normalize_to_words(&current)
                            .into_iter()
                            .map(PatternWord::Literal),
                    );
                    current.clear();
                }
                in_wildcard_seq = false;
            }
            _ => {
                current.push(c);
                in_wildcard_seq = false;
            }
        }
    }

    if !current.is_empty() {
        result.extend(
            normalize_to_words(&current)
                .into_iter()
                .map(PatternWord::Literal),
        );
    }

    result
}

fn match_word_pattern(pattern: &[PatternWord], target: &[String]) -> bool {
    match_word_pattern_recursive(pattern, target, 0, 0)
}

fn match_word_pattern_recursive(
    pattern: &[PatternWord],
    target: &[String],
    pi: usize,
    ti: usize,
) -> bool {
    if pi == pattern.len() && ti == target.len() {
        return true;
    }
    if pi == pattern.len() {
        return false;
    }

    match &pattern[pi] {
        PatternWord::AnyWords => {
            for skip in 0..=(target.len() - ti) {
                if match_word_pattern_recursive(pattern, target, pi + 1, ti + skip) {
                    return true;
                }
            }
            false
        }
        PatternWord::Literal(word) => {
            if ti < target.len() && target[ti] == *word {
                match_word_pattern_recursive(pattern, target, pi + 1, ti + 1)
            } else {
                false
            }
        }
        PatternWord::AnyChar => {
            if ti < target.len() {
                match_word_pattern_recursive(pattern, target, pi + 1, ti + 1)
            } else {
                false
            }
        }
    }
}

fn contains_words(haystack: &[String], needle: &[String]) -> bool {
    if needle.is_empty() {
        return true;
    }
    if needle.len() > haystack.len() {
        return false;
    }
    haystack.windows(needle.len()).any(|w| w == needle)
}

fn starts_with_words(haystack: &[String], prefix: &[String]) -> bool {
    if prefix.len() > haystack.len() {
        return false;
    }
    haystack[..prefix.len()] == *prefix
}

fn ends_with_words(haystack: &[String], suffix: &[String]) -> bool {
    if suffix.len() > haystack.len() {
        return false;
    }
    haystack[haystack.len() - suffix.len()..] == *suffix
}

// =============================================================================
// ReceiverKind
// =============================================================================

/// selfレシーバーの種類
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum ReceiverKind {
    /// 関連関数 (fn new())
    None,
    /// &self
    Ref,
    /// &mut self
    MutRef,
    /// self
    Owned,
}

// =============================================================================
// Visibility
// =============================================================================

/// 可視性
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum Visibility {
    /// `pub`
    Public,
    /// 非公開 (modifier 無し)。
    Private,
    /// `pub(crate)`
    Crate,
    /// `pub(super)`
    Super,
    /// pub(in path)
    Restricted(String),
}

// =============================================================================
// GenericsMatch
// =============================================================================

/// ジェネリクスマッチング条件
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct GenericsMatch {
    /// 型パラメータ名 ["T", "E"]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub params: Option<Vec<String>>,

    /// 境界マッチ ["Clone", "Send"]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bounds: Option<Vec<NameMatcher>>,

    /// ライフタイム ["'a"]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lifetimes: Option<Vec<String>>,
}

// =============================================================================
// RecoveryStrategy
// =============================================================================

/// 失敗時リカバリー戦略
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct RecoveryStrategy {
    /// Fuzzy検索
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fuzzy: Option<FuzzyConfig>,

    /// 単語分割して検索
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub split_words: Option<bool>,

    /// スコープ内を列挙
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enumerate_scope: Option<usize>,
}

/// Fuzzy検索設定
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct FuzzyConfig {
    /// 許容する Levenshtein 距離の上限。
    pub max_distance: u32,
}

// =============================================================================
// ResolveConfig
// =============================================================================

/// LSP連携設定
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ResolveConfig {
    /// 解決種別 (references / definition / callers ...)。
    pub kind: ResolveKind,

    /// LSP 呼び出しのタイムアウト (ミリ秒)。
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u32>,

    /// 解決を再帰する最大深度。
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub depth: Option<usize>,
}

/// Resolve種別
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum ResolveKind {
    /// LSP: 参照を列挙。
    References,
    /// LSP: 定義位置を取得。
    Definition,
    /// LSP: 呼び出し元 (callers) を列挙。
    Callers,
    /// LSP: 呼び出し先 (callees) を列挙。
    Callees,
    /// LSP: シンボル利用箇所を列挙。
    Uses,
    /// LSP: シンボルを利用している側を列挙。
    UsedBy,
    /// LSP: trait 実装を列挙。
    Implementations,
}

// =============================================================================
// Scope
// =============================================================================

/// 検索スコープ
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct Scope {
    /// パスパターン "src/**"
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,

    /// 除外パターン "tests/**"
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exclude_path: Option<String>,

    /// モジュールパス
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub module: Option<String>,
}

// =============================================================================
// ViewMode
// =============================================================================

/// 出力モード
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
pub enum ViewMode {
    /// コード片 + 周辺行(デフォルト)
    #[default]
    Snippet,
    /// 位置のみ
    Precise,
    /// 件数のみ
    Count,
    /// 定義詳細(ModPath + Definition + SpecDoc)
    Def,
    /// 完全な定義(Def + 関数body)
    Full,
}

// =============================================================================
// Response
// =============================================================================

/// クエリレスポンス
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct QueryResponse {
    /// 検索全体のステータス (found / not_found / partial)。
    pub status: QueryStatus,
    /// マッチ結果一覧。
    pub results: Vec<MatchResult>,
    /// 結果ゼロ時等に返される候補サジェスチョン。
    pub suggestions: Vec<Suggestion>,
    /// 経過時間等のメタ情報。
    pub metadata: QueryMetadata,
}

/// クエリステータス
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum QueryStatus {
    /// 1 件以上ヒット。
    Found,
    /// ヒットなし。
    NotFound,
    /// 部分的にヒット (resolve がタイムアウト等)。
    Partial,
}

/// マッチ結果
///
/// # 設計方針
///
/// - **SymbolId が主キー**: これだけで処理に十分
/// - **SymbolPath**: フルパスでシンボルを特定可能
/// - **file_path/line は含めない**: Spanを保持しない方針。ModPathで大体わかる
/// - **ファイル参照が必要な場合**: Grep等で対応可能
/// - **ViewMode別データ**: MatchViewで型安全に表現
///
/// この設計により、結果がコンパクトになりAIエージェントが扱いやすくなる。
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct MatchResult {
    /// SymbolId: slotmap key (e.g., "SymbolId(172v1)")
    ///
    /// **Warning**: This ID is session-volatile. It changes when the server restarts.
    /// For persistent references across sessions, use `uuid` instead.
    pub id: String,

    /// Persistent UUID for cross-session symbol tracking.
    ///
    /// This UUID survives server restarts and symbol renames.
    /// Use this for storing references that need to persist.
    /// Returns `None` if the symbol hasn't been assigned a persistent ID.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub uuid: Option<String>,

    /// SymbolPath: Full path (e.g., "ryo_analysis::registry::DetectRegistry")
    pub path: String,

    /// Item kind (Function, Struct, Enum, etc.)
    pub node_kind: String,

    /// Symbol name (e.g., "Node")
    pub name: String,

    /// ViewMode別のデータ
    #[serde(flatten)]
    pub view: MatchView,
}

/// ViewMode別のマッチデータ
///
/// 各ViewModeで必要なデータのみを持つ。
/// CountモードではMatchResult自体が不要なので含めない。
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "view_mode", rename_all = "snake_case")]
pub enum MatchView {
    /// Snippetモード: コード片
    Snippet {
        /// コードスニペット
        text: String,
    },

    /// Preciseモード: 位置情報のみ(追加データなし)
    Precise,

    /// Defモード: 定義詳細(シグネチャ + ドキュメント)
    Def {
        /// モジュールパス (e.g., "ryo_core::ast")
        module_path: String,
        /// 定義(シグネチャ、フィールド等)
        definition: String,
        /// ドキュメント + spec annotations
        #[serde(default, skip_serializing_if = "Option::is_none")]
        doc: Option<String>,
    },

    /// Fullモード: 完全な定義(Def + 関数body)
    Full {
        /// モジュールパス
        module_path: String,
        /// 定義シグネチャ
        definition: String,
        /// 関数body等の完全なソース
        body: String,
        /// ドキュメント + spec annotations
        #[serde(default, skip_serializing_if = "Option::is_none")]
        doc: Option<String>,
    },
}

/// サジェスチョン
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Suggestion {
    /// 候補の種別 (typo / similar / in_scope)。
    pub kind: SuggestionKind,
    /// 候補シンボル名。
    pub name: String,

    /// 元クエリとの編集距離 (typo 候補のみ)。
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub distance: Option<u32>,

    /// 候補の確からしさ (0.0-1.0)。
    pub confidence: f32,
}

/// サジェスチョン種別
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum SuggestionKind {
    /// タイポ候補 (編集距離が近い)。
    Typo,
    /// 類似名候補。
    Similar,
    /// 同スコープ内に存在する候補。
    InScope,
}

/// クエリメタデータ
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct QueryMetadata {
    /// 検索全体の経過時間 (ミリ秒)。
    pub elapsed_ms: u32,
    /// `limit` 適用前の総マッチ数。
    pub total_matches: usize,

    /// resolve (LSP 連携) のステータス。
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolve_status: Option<ResolveStatus>,
}

/// Resolveステータス
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum ResolveStatus {
    /// すべての resolve が完了した。
    Complete,
    /// タイムアウトで一部 resolve 未完了。
    TimedOut,
    /// レートリミットで resolve 抑制された。
    RateLimited,
}

// =============================================================================
// Schema Generation
// =============================================================================

/// Generate JSON Schema for RyoQL Query
pub fn query_json_schema() -> schemars::Schema {
    schemars::schema_for!(Query)
}

/// Generate JSON Schema for RyoQL QueryResponse
pub fn response_json_schema() -> schemars::Schema {
    schemars::schema_for!(QueryResponse)
}

/// Generate JSON Schema as pretty-printed string
pub fn query_json_schema_string() -> String {
    serde_json::to_string_pretty(&query_json_schema()).unwrap_or_default()
}

/// Generate JSON Schema for response as pretty-printed string
pub fn response_json_schema_string() -> String {
    serde_json::to_string_pretty(&response_json_schema()).unwrap_or_default()
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_simple_query() {
        let yaml = r#"
kind: Function
match:
  name: "process"
  vis: Public
  is_async: true
"#;
        let query: Query = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(query.kind, QueryKind::Function);
        let m = query.r#match.unwrap();
        assert!(matches!(m.name, Some(NameMatcher::Exact(ref s)) if s == "process"));
        assert_eq!(m.vis, Some(Visibility::Public));
        assert_eq!(m.is_async, Some(true));
    }

    #[test]
    fn test_parse_nested_query() {
        let yaml = r#"
kind: Function
match:
  name: { starts_with: "process_" }
inner:
  - kind: ReturnType
    match:
      name: "Result"
"#;
        let query: Query = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(query.kind, QueryKind::Function);
        assert_eq!(query.inner.len(), 1);
        assert_eq!(query.inner[0].kind, QueryKind::ReturnType);
    }

    #[test]
    fn test_parse_or_query() {
        let yaml = r#"
kind: Or
queries:
  - kind: Struct
    match:
      name: { contains: "Error" }
  - kind: Enum
    match:
      name: { contains: "Error" }
"#;
        let query: Query = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(query.kind, QueryKind::Or);
        assert_eq!(query.queries.len(), 2);
    }

    #[test]
    fn test_name_matcher_exact() {
        let matcher = NameMatcher::Exact("process".to_string());
        assert!(matcher.matches("process"));
        assert!(!matcher.matches("process_event"));
    }

    #[test]
    fn test_name_matcher_contains() {
        let matcher = NameMatcher::Detailed(NameMatcherDetailed {
            contains: Some("process".to_string()),
            starts_with: None,
            ends_with: None,
            regex: None,
            glob: None,
            ignore_case: None,
            ignore_word_separate: None,
        });
        assert!(matcher.matches("process"));
        assert!(matcher.matches("process_event"));
        assert!(matcher.matches("do_process"));
        assert!(!matcher.matches("handle"));
    }

    #[test]
    fn test_name_matcher_glob() {
        let matcher = NameMatcher::Detailed(NameMatcherDetailed {
            contains: None,
            starts_with: None,
            ends_with: None,
            regex: None,
            glob: Some("*Config".to_string()),
            ignore_case: None,
            ignore_word_separate: None,
        });
        assert!(matcher.matches("AppConfig"));
        assert!(matcher.matches("Config"));
        assert!(!matcher.matches("ConfigManager"));
    }

    #[test]
    fn test_name_matcher_ignore_case() {
        let matcher = NameMatcher::Detailed(NameMatcherDetailed {
            contains: Some("config".to_string()),
            starts_with: None,
            ends_with: None,
            regex: None,
            glob: None,
            ignore_case: Some(true),
            ignore_word_separate: None,
        });
        assert!(matcher.matches("AppConfig"));
        assert!(matcher.matches("APPCONFIG"));
        assert!(matcher.matches("config"));
    }

    #[test]
    fn test_name_matcher_ignore_word_separate() {
        let matcher = NameMatcher::Detailed(NameMatcherDetailed {
            contains: None,
            starts_with: Some("get_user".to_string()),
            ends_with: None,
            regex: None,
            glob: None,
            ignore_case: None,
            ignore_word_separate: Some(true),
        });
        assert!(matcher.matches("get_user_name"));
        assert!(matcher.matches("getUserName"));
        assert!(matcher.matches("GetUserName"));
        assert!(!matcher.matches("fetch_user_name"));
    }

    #[test]
    fn test_parse_literal_query() {
        let yaml = r#"
kind: Literal
match:
  pattern: "*error*"
  lit_type: String
"#;
        let query: Query = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(query.kind, QueryKind::Literal);
        let m = query.r#match.unwrap();
        assert_eq!(m.pattern, Some("*error*".to_string()));
        assert_eq!(m.lit_type, Some(LiteralType::String));
    }

    #[test]
    fn test_parse_literal_query_int() {
        let yaml = r#"
kind: Literal
match:
  pattern: "0x*"
  lit_type: Int
"#;
        let query: Query = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(query.kind, QueryKind::Literal);
        let m = query.r#match.unwrap();
        assert_eq!(m.lit_type, Some(LiteralType::Int));
    }

    #[test]
    fn test_literal_type_all_variants() {
        let types = [
            ("String", LiteralType::String),
            ("ByteStr", LiteralType::ByteStr),
            ("Char", LiteralType::Char),
            ("Byte", LiteralType::Byte),
            ("Int", LiteralType::Int),
            ("Float", LiteralType::Float),
            ("Bool", LiteralType::Bool),
        ];
        for (s, expected) in types {
            let json = format!(r#""{s}""#);
            let parsed: LiteralType = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, expected, "Failed for {s}");
        }
    }

    #[test]
    fn test_parse_query_with_body() {
        let yaml = r#"
kind: Function
match:
  name: "process"
body:
  contains:
    - node: MethodCall
      capture: "call"
"#;
        let query: Query = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(query.kind, QueryKind::Function);
        let body = query.body.unwrap();
        let contains = body.contains.unwrap();
        assert_eq!(contains.len(), 1);
        assert_eq!(contains[0].node, ryo_pattern::NodeKind::MethodCall);
        assert_eq!(contains[0].capture, Some("call".to_string()));
    }

    #[test]
    fn test_deny_unknown_fields_rejects_top_level_is_async() {
        // BUG#1 regression: is_async at top level was silently ignored
        let json = r#"{"kind":"Function","is_async":true}"#;
        let result: Result<Query, _> = serde_json::from_str(json);
        assert!(
            result.is_err(),
            "top-level is_async must be rejected by deny_unknown_fields"
        );
    }

    #[test]
    fn test_is_async_in_match_accepted() {
        // Correct format: is_async nested inside match
        let json = r#"{"kind":"Function","match":{"is_async":true}}"#;
        let query: Query = serde_json::from_str(json).unwrap();
        assert_eq!(query.r#match.unwrap().is_async, Some(true));
    }

    #[test]
    fn test_parse_query_with_relations() {
        use ryo_pattern::RelationKind;

        let yaml = r#"
kind: Function
match:
  name: "handler"
relations:
  any:
    - kind: Calls
      target: {}
      transitive: true
      max_depth: 3
  none:
    - kind: TypeReferences
      target: {}
"#;
        let query: Query = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(query.kind, QueryKind::Function);
        let relations = query.relations.unwrap();

        // any: Calls with transitive
        let any = relations.any.unwrap();
        assert_eq!(any.len(), 1);
        assert_eq!(any[0].kind, RelationKind::Calls);
        assert!(any[0].transitive);
        assert_eq!(any[0].max_depth, Some(3));

        // none: TypeReferences
        let none = relations.none.unwrap();
        assert_eq!(none.len(), 1);
        assert_eq!(none[0].kind, RelationKind::TypeReferences);
    }
}