nautilus-orm-schema 0.1.3

Schema parsing and validation for Nautilus ORM
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
//! Completion suggestions for `.nautilus` schema files.

use super::{analyze, span_contains};
use crate::ast::Declaration;
use crate::token::{Token, TokenKind};

/// The kind of a completion item.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompletionKind {
    /// A language keyword (`model`, `enum`, …).
    Keyword,
    /// A scalar or user-defined field type.
    Type,
    /// A field-level attribute (`@id`, `@unique`, …).
    FieldAttribute,
    /// A model-level attribute (`@@id`, `@@map`, …).
    ModelAttribute,
    /// A reference to a model name.
    ModelName,
    /// A reference to an enum name.
    EnumName,
    /// A field name inside a model or datasource.
    FieldName,
}

/// A single completion suggestion.
#[derive(Debug, Clone, PartialEq)]
pub struct CompletionItem {
    /// The text displayed in the completion popup.
    pub label: String,
    /// The text to actually insert (defaults to `label` when `None`).
    pub insert_text: Option<String>,
    /// Whether `insert_text` uses LSP snippet syntax (`$1`, `${1:placeholder}`, etc.).
    pub is_snippet: bool,
    /// What kind of thing this item represents.
    pub kind: CompletionKind,
    /// Optional extra description shown in the completion popup.
    pub detail: Option<String>,
}

impl CompletionItem {
    pub(super) fn new(
        label: impl Into<String>,
        kind: CompletionKind,
        detail: impl Into<Option<String>>,
    ) -> Self {
        Self {
            label: label.into(),
            insert_text: None,
            is_snippet: false,
            kind,
            detail: detail.into(),
        }
    }

    pub(super) fn with_insert(
        label: impl Into<String>,
        insert_text: impl Into<String>,
        kind: CompletionKind,
        detail: impl Into<Option<String>>,
    ) -> Self {
        Self {
            label: label.into(),
            insert_text: Some(insert_text.into()),
            is_snippet: false,
            kind,
            detail: detail.into(),
        }
    }

    pub(super) fn with_snippet(
        label: impl Into<String>,
        snippet: impl Into<String>,
        kind: CompletionKind,
        detail: impl Into<Option<String>>,
    ) -> Self {
        Self {
            label: label.into(),
            insert_text: Some(snippet.into()),
            is_snippet: true,
            kind,
            detail: detail.into(),
        }
    }
}

/// Returns completions appropriate at `offset` (byte offset) in `source`.
///
/// Uses the parsed AST to determine context:
/// - Outside all declarations → top-level keywords.
/// - Inside a `datasource` or `generator` block → config key suggestions.
/// - Inside a `model` block:
///   - After `@` → field attribute names.
///   - After `@@` → model attribute names.
///   - Otherwise → scalar types, user-defined model/enum names, and common
///     field attributes as a convenience.
pub fn completion(source: &str, offset: usize) -> Vec<CompletionItem> {
    let result = analyze(source);
    let tokens = &result.tokens;

    // Extract provider once for all provider-aware completions.
    let provider: Option<String> = extract_provider_from_tokens(tokens);

    if let Some(attr_name) = inside_attr_args_at(tokens, offset) {
        let arg_index = attr_arg_index_at(tokens, offset).unwrap_or(0);
        return attr_argument_completions(&attr_name, provider.as_deref(), arg_index);
    }

    let attr_ctx = attribute_context_at(tokens, offset);
    if attr_ctx == AttributeContext::FieldAttr {
        return field_attribute_completions();
    }
    if attr_ctx == AttributeContext::ModelAttr {
        return model_attribute_completions();
    }

    if let Some(key) = config_value_context_at(tokens, offset) {
        let block_kind = config_block_kind_at(tokens, offset);
        let completions = config_value_completions(&key, block_kind);
        if !completions.is_empty() {
            return completions;
        }
    }

    let ast = match &result.ast {
        Some(a) => a,
        None => {
            // AST unavailable (e.g. fatal parse error).  Use the raw token
            // stream to make a best-effort guess about the enclosing block.
            return if is_inside_model_tokens(tokens, offset) {
                scalar_type_completions(provider.as_deref())
            } else {
                top_level_completions()
            };
        }
    };

    // Gather user-defined names for cross-ref completions.
    let user_models: Vec<String> = ast
        .declarations
        .iter()
        .filter_map(|d| {
            if let Declaration::Model(m) = d {
                Some(m.name.value.clone())
            } else {
                None
            }
        })
        .collect();

    let user_enums: Vec<String> = ast
        .declarations
        .iter()
        .filter_map(|d| {
            if let Declaration::Enum(e) = d {
                Some(e.name.value.clone())
            } else {
                None
            }
        })
        .collect();

    // Determine which top-level declaration contains the cursor.
    let containing_decl = ast
        .declarations
        .iter()
        .find(|d| span_contains(d.span(), offset));

    match containing_decl {
        None => {
            // The offset isn't inside any parsed declaration. This can happen
            // when error recovery dropped the enclosing block.  Fall back to
            // the token stream to make a best-effort guess.
            if is_inside_model_tokens(tokens, offset) {
                let mut items = scalar_type_completions(provider.as_deref());
                for name in &user_models {
                    items.push(CompletionItem::new(
                        name.clone(),
                        CompletionKind::ModelName,
                        Some("Model reference".to_string()),
                    ));
                }
                for name in &user_enums {
                    items.push(CompletionItem::new(
                        name.clone(),
                        CompletionKind::EnumName,
                        Some("Enum reference".to_string()),
                    ));
                }
                items
            } else {
                top_level_completions()
            }
        }

        Some(Declaration::Datasource(_)) | Some(Declaration::Generator(_)) => {
            datasource_generator_completions()
        }

        Some(Declaration::Enum(_)) => {
            // Inside an enum body: only enum variants are meaningful here,
            // nothing to complete (they are user-defined identifiers).
            Vec::new()
        }

        Some(Declaration::Model(_)) | Some(Declaration::Type(_)) => {
            let mut items = scalar_type_completions(provider.as_deref());
            for name in &user_models {
                items.push(CompletionItem::new(
                    name.clone(),
                    CompletionKind::ModelName,
                    Some("Model reference".to_string()),
                ));
            }
            for name in &user_enums {
                items.push(CompletionItem::new(
                    name.clone(),
                    CompletionKind::EnumName,
                    Some("Enum reference".to_string()),
                ));
            }
            items
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ConfigBlockKind {
    Datasource,
    Generator,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AttributeContext {
    FieldAttr,
    ModelAttr,
    None,
}

/// Returns the name of the attribute whose argument list contains `offset`,
/// e.g. `"store"` when the cursor is inside `@store(|)`, `"relation"` for
/// `@relation(|)`, etc.  Returns `None` when `offset` is not inside any
/// attribute argument list.
fn inside_attr_args_at(tokens: &[Token], offset: usize) -> Option<String> {
    // Collect non-newline tokens that end at or before `offset`.
    let relevant: Vec<&Token> = tokens
        .iter()
        .filter(|t| t.span.end <= offset && !matches!(t.kind, TokenKind::Newline))
        .collect();

    let mut depth: i32 = 0;
    for tok in relevant.iter().rev() {
        match tok.kind {
            TokenKind::RParen => depth += 1,
            TokenKind::LParen => {
                if depth == 0 {
                    // This unmatched `(` — check what precedes it.
                    let lparen_start = tok.span.start;
                    let before: Vec<&Token> = tokens
                        .iter()
                        .filter(|t| {
                            t.span.end <= lparen_start && !matches!(t.kind, TokenKind::Newline)
                        })
                        .collect();
                    if let Some(name_tok) = before.last() {
                        if let TokenKind::Ident(attr_name) = &name_tok.kind {
                            let attr_name = attr_name.clone();
                            // Verify it is preceded by `@` or `@@`.
                            let before_name: Vec<&Token> = tokens
                                .iter()
                                .filter(|t| {
                                    t.span.end <= name_tok.span.start
                                        && !matches!(t.kind, TokenKind::Newline)
                                })
                                .collect();
                            if let Some(at_tok) = before_name.last() {
                                if matches!(at_tok.kind, TokenKind::At | TokenKind::AtAt) {
                                    return Some(attr_name);
                                }
                            }
                        }
                    }
                    return None;
                }
                depth -= 1;
            }
            _ => {}
        }
    }
    None
}

/// Detects whether `offset` sits in a config value position (`key = <cursor>`)
/// within a datasource or generator block. Returns the key name if so.
fn config_value_context_at(tokens: &[Token], offset: usize) -> Option<String> {
    let mut eq_pos: Option<usize> = None;
    let mut key_pos: Option<usize> = None;

    for (i, tok) in tokens.iter().enumerate() {
        if tok.span.end > offset {
            break;
        }
        if tok.kind == TokenKind::Newline {
            eq_pos = None;
            key_pos = None;
        } else if tok.kind == TokenKind::Equal {
            eq_pos = Some(i);
        } else if let TokenKind::Ident(_) = tok.kind {
            if eq_pos.is_none() {
                key_pos = Some(i);
            }
        }
    }

    let eq_idx = eq_pos?;
    let key_idx = key_pos?;

    if eq_idx != key_idx + 1 {
        return None;
    }

    if let TokenKind::Ident(key) = &tokens[key_idx].kind {
        return Some(key.clone());
    }
    None
}

/// Detect whether `offset` immediately follows a `@` or `@@` token.
fn attribute_context_at(tokens: &[Token], offset: usize) -> AttributeContext {
    // Find the last token whose span ends at or before `offset`.
    let last = tokens
        .iter()
        .rfind(|t| t.span.end <= offset && !matches!(t.kind, TokenKind::Newline));

    match last {
        Some(t) if t.kind == TokenKind::AtAt => AttributeContext::ModelAttr,
        Some(t) if t.kind == TokenKind::At => AttributeContext::FieldAttr,
        // The cursor might be in the middle of an identifier that started
        // after `@` — look one token further back.
        Some(t) if matches!(t.kind, TokenKind::Ident(_)) => {
            let before = tokens.iter().rfind(|tok| tok.span.end <= t.span.start);
            match before {
                Some(b) if b.kind == TokenKind::AtAt => AttributeContext::ModelAttr,
                Some(b) if b.kind == TokenKind::At => AttributeContext::FieldAttr,
                _ => AttributeContext::None,
            }
        }
        _ => AttributeContext::None,
    }
}

/// Returns `true` if `offset` appears to be inside a `model { … }` block,
/// based purely on the token stream (no AST required).
///
/// Algorithm: scan backwards from `offset`, counting unmatched `}` / `{`.
/// When we find an unmatched `{`, check if the two tokens before it are
/// `<Ident>` and `model`.
fn is_inside_model_tokens(tokens: &[Token], offset: usize) -> bool {
    // Only consider tokens whose span ends at or before offset.
    let relevant: Vec<&Token> = tokens.iter().filter(|t| t.span.end <= offset).collect();

    let mut depth: i32 = 0;
    for tok in relevant.iter().rev() {
        match tok.kind {
            TokenKind::RBrace => depth += 1,
            TokenKind::LBrace => {
                if depth == 0 {
                    // This is the unmatched `{` enclosing `offset`.
                    // Walk backwards past it to find the block header.
                    let idx = tokens
                        .iter()
                        .position(|t| std::ptr::eq(t, *tok))
                        .unwrap_or(0);
                    // Find the last non-newline token before this `{`.
                    let before: Vec<&Token> = tokens[..idx]
                        .iter()
                        .filter(|t| !matches!(t.kind, TokenKind::Newline))
                        .collect();
                    if let Some(name_tok) = before.last() {
                        if matches!(name_tok.kind, TokenKind::Ident(_)) {
                            let before_name: Vec<&Token> = tokens[..idx]
                                .iter()
                                .filter(|t| !matches!(t.kind, TokenKind::Newline))
                                .rev()
                                .skip(1)
                                .take(1)
                                .collect();
                            if let Some(kw) = before_name.first() {
                                return kw.kind == TokenKind::Model || kw.kind == TokenKind::Type;
                            }
                        }
                    }
                    return false;
                }
                depth -= 1;
            }
            _ => {}
        }
    }
    false
}

/// Extract the datasource `provider` value from a token stream.
///
/// Looks for the pattern:  `datasource <ident> { … provider = "<value>" … }`
/// Returns `Some("postgresql" | "mysql" | "sqlite")` when found, `None` otherwise.
fn extract_provider_from_tokens(tokens: &[Token]) -> Option<String> {
    let n = tokens.len();
    for i in 0..n {
        // Match `provider`
        if let TokenKind::Ident(ref kw) = tokens[i].kind {
            if kw != "provider" {
                continue;
            }
        } else {
            continue;
        }
        // Skip newlines to find `=`
        let mut j = i + 1;
        while j < n && matches!(tokens[j].kind, TokenKind::Newline) {
            j += 1;
        }
        if j >= n || tokens[j].kind != TokenKind::Equal {
            continue;
        }
        j += 1;
        while j < n && matches!(tokens[j].kind, TokenKind::Newline) {
            j += 1;
        }
        if j < n {
            if let TokenKind::String(ref val) = tokens[j].kind {
                let v = val.as_str();
                if matches!(v, "postgresql" | "mysql" | "sqlite") {
                    return Some(v.to_string());
                }
            }
        }
    }
    None
}

/// Returns context-sensitive completions for the arguments of a specific attribute.
///
/// Called when the cursor is detected to be inside `@attr(|)` argument parens.
/// Returns the 0-based argument index of `offset` inside the innermost
/// unmatched `(...)`, scanning backwards through `tokens`.
/// Returns `None` if not inside any parentheses.
fn attr_arg_index_at(tokens: &[Token], offset: usize) -> Option<usize> {
    let relevant: Vec<&Token> = tokens
        .iter()
        .filter(|t| t.span.end <= offset && !matches!(t.kind, TokenKind::Newline))
        .collect();
    let mut depth: i32 = 0;
    let mut commas: usize = 0;
    for tok in relevant.iter().rev() {
        match tok.kind {
            TokenKind::RParen => depth += 1,
            TokenKind::LParen => {
                if depth == 0 {
                    return Some(commas);
                }
                depth -= 1;
            }
            TokenKind::Comma if depth == 0 => commas += 1,
            _ => {}
        }
    }
    None
}

fn attr_argument_completions(
    attr_name: &str,
    provider: Option<&str>,
    arg_index: usize,
) -> Vec<CompletionItem> {
    match attr_name {
        "store" => vec![CompletionItem::new(
            "json",
            CompletionKind::FieldAttribute,
            Some("Serialize array as JSON in the database".to_string()),
        )],
        "relation" => vec![
            CompletionItem::new(
                "fields: []",
                CompletionKind::FieldName,
                Some("Local FK field(s) on this model".to_string()),
            ),
            CompletionItem::new(
                "references: []",
                CompletionKind::FieldName,
                Some("Referenced field(s) on the target model".to_string()),
            ),
            CompletionItem::new(
                "name: \"\"",
                CompletionKind::FieldName,
                Some(
                    "Relation name (required when multiple relations to the same model)"
                        .to_string(),
                ),
            ),
            CompletionItem::new(
                "onDelete: Cascade",
                CompletionKind::FieldName,
                Some("Referential action on parent record delete".to_string()),
            ),
            CompletionItem::new(
                "onUpdate: Cascade",
                CompletionKind::FieldName,
                Some("Referential action on parent record update".to_string()),
            ),
        ],
        "default" => vec![
            CompletionItem::new(
                "autoincrement()",
                CompletionKind::Keyword,
                Some("Auto-incrementing integer sequence".to_string()),
            ),
            CompletionItem::new(
                "now()",
                CompletionKind::Keyword,
                Some("Current timestamp at insert time".to_string()),
            ),
            CompletionItem::new(
                "uuid()",
                CompletionKind::Keyword,
                Some("Randomly generated UUID".to_string()),
            ),
            CompletionItem::new(
                "cuid()",
                CompletionKind::Keyword,
                Some("Randomly generated CUID".to_string()),
            ),
            CompletionItem::new(
                "dbgenerated(\"expr\")",
                CompletionKind::Keyword,
                Some("Database-level default expression".to_string()),
            ),
        ],
        "computed" => match arg_index {
            // First argument: the SQL expression — no predefined choices, but
            // show a hint so the user knows what's expected.
            0 => vec![CompletionItem::new(
                "SQL expression",
                CompletionKind::Keyword,
                Some("e.g. price * quantity  or  first_name || ' ' || last_name".to_string()),
            )],
            // Second argument: storage kind.
            _ => vec![
                CompletionItem::new(
                    "Stored",
                    CompletionKind::Keyword,
                    Some("Computed on write, persisted on disk (all databases)".to_string()),
                ),
                CompletionItem::new(
                    "Virtual",
                    CompletionKind::Keyword,
                    Some("Computed on read, never stored (MySQL / SQLite only)".to_string()),
                ),
            ],
        },
        "index" => index_argument_completions(provider),
        _ => vec![],
    }
}

fn top_level_completions() -> Vec<CompletionItem> {
    vec![
        CompletionItem::new(
            "model",
            CompletionKind::Keyword,
            Some("Define a data model".to_string()),
        ),
        CompletionItem::new(
            "enum",
            CompletionKind::Keyword,
            Some("Define an enumeration".to_string()),
        ),
        CompletionItem::new(
            "type",
            CompletionKind::Keyword,
            Some("Define a composite type".to_string()),
        ),
        CompletionItem::new(
            "datasource",
            CompletionKind::Keyword,
            Some("Configure a data source".to_string()),
        ),
        CompletionItem::new(
            "generator",
            CompletionKind::Keyword,
            Some("Configure code generation".to_string()),
        ),
    ]
}

/// Return argument completions for `@@index(…)`, filtered by DB provider when known.
///
/// All DB types:   BTree (default, always shown)
/// PG + MySQL:     Hash
/// PG only:        Gin, Gist, Brin
/// MySQL only:     FullText
fn index_argument_completions(provider: Option<&str>) -> Vec<CompletionItem> {
    // Helper — (label, description) pairs for index type options.
    struct TypeEntry {
        label: &'static str,
        desc: &'static str,
        providers: &'static [&'static str],
    }
    let type_entries = [
        TypeEntry {
            label: "type: BTree",
            desc: "B-Tree index — default on all databases",
            providers: &["postgresql", "mysql", "sqlite"],
        },
        TypeEntry {
            label: "type: Hash",
            desc: "Hash index — PostgreSQL and MySQL 8+",
            providers: &["postgresql", "mysql"],
        },
        TypeEntry {
            label: "type: Gin",
            desc: "GIN index — PostgreSQL only (arrays, JSONB, full-text)",
            providers: &["postgresql"],
        },
        TypeEntry {
            label: "type: Gist",
            desc: "GiST index — PostgreSQL only (geometry, range types)",
            providers: &["postgresql"],
        },
        TypeEntry {
            label: "type: Brin",
            desc: "BRIN index — PostgreSQL only (ordered large tables)",
            providers: &["postgresql"],
        },
        TypeEntry {
            label: "type: FullText",
            desc: "FULLTEXT index — MySQL only",
            providers: &["mysql"],
        },
    ];

    let mut items: Vec<CompletionItem> = type_entries
        .iter()
        .filter(|e| {
            // When provider is known, only show compatible types.
            // When unknown, show all.
            match provider {
                Some(p) => e.providers.contains(&p),
                None => true,
            }
        })
        .map(|e| CompletionItem::new(e.label, CompletionKind::Keyword, Some(e.desc.to_string())))
        .collect();

    // Named-argument helpers.
    items.push(CompletionItem::new(
        "name: \"\"",
        CompletionKind::FieldName,
        Some("Logical developer name for this index".to_string()),
    ));
    items.push(CompletionItem::new(
        "map: \"\"",
        CompletionKind::FieldName,
        Some("Physical DDL index name (overrides auto-generated idx_… name)".to_string()),
    ));

    items
}

fn scalar_type_completions(provider: Option<&str>) -> Vec<CompletionItem> {
    let pg = matches!(provider, Some("postgresql") | None);
    let pg_or_mysql = matches!(provider, Some("postgresql") | Some("mysql") | None);

    let mut items = vec![
        CompletionItem::new(
            "String",
            CompletionKind::Type,
            Some("UTF-8 text → VARCHAR / TEXT".to_string()),
        ),
        CompletionItem::new(
            "Boolean",
            CompletionKind::Type,
            Some("true / false → BOOLEAN".to_string()),
        ),
        CompletionItem::new(
            "Int",
            CompletionKind::Type,
            Some("32-bit integer → INTEGER".to_string()),
        ),
        CompletionItem::new(
            "BigInt",
            CompletionKind::Type,
            Some("64-bit integer → BIGINT".to_string()),
        ),
        CompletionItem::new(
            "Float",
            CompletionKind::Type,
            Some("64-bit float → DOUBLE PRECISION".to_string()),
        ),
        CompletionItem::new(
            "Decimal",
            CompletionKind::Type,
            Some("Exact decimal → NUMERIC".to_string()),
        ),
        CompletionItem::new(
            "DateTime",
            CompletionKind::Type,
            Some("Timestamp with time zone → TIMESTAMPTZ".to_string()),
        ),
        CompletionItem::new(
            "Bytes",
            CompletionKind::Type,
            Some("Binary data → BYTEA".to_string()),
        ),
        CompletionItem::new(
            "Json",
            CompletionKind::Type,
            Some("JSON document → JSONB".to_string()),
        ),
        CompletionItem::new(
            "Uuid",
            CompletionKind::Type,
            Some("UUID → UUID".to_string()),
        ),
    ];

    if pg {
        items.push(CompletionItem::new(
            "Jsonb",
            CompletionKind::Type,
            Some("JSONB document → JSONB (PostgreSQL only)".to_string()),
        ));
        items.push(CompletionItem::new(
            "Xml",
            CompletionKind::Type,
            Some("XML document → XML (PostgreSQL only)".to_string()),
        ));
    }

    if pg_or_mysql {
        items.push(CompletionItem::with_snippet(
            "Char(n)",
            "Char(${1:n})",
            CompletionKind::Type,
            Some("Fixed-length string → CHAR(n) (PostgreSQL and MySQL)".to_string()),
        ));
        items.push(CompletionItem::with_snippet(
            "VarChar(n)",
            "VarChar(${1:n})",
            CompletionKind::Type,
            Some("Variable-length string → VARCHAR(n) (PostgreSQL and MySQL)".to_string()),
        ));
    }

    items
}

fn field_attribute_completions() -> Vec<CompletionItem> {
    vec![
        CompletionItem::new(
            "id",
            CompletionKind::FieldAttribute,
            Some("Mark as primary key".to_string()),
        ),
        CompletionItem::new(
            "unique",
            CompletionKind::FieldAttribute,
            Some("Add a unique constraint".to_string()),
        ),
        CompletionItem::new(
            "default()",
            CompletionKind::FieldAttribute,
            Some("Set a default value".to_string()),
        ),
        CompletionItem::new(
            "relation()",
            CompletionKind::FieldAttribute,
            Some("Define a relation".to_string()),
        ),
        CompletionItem::new(
            "map(\"\")",
            CompletionKind::FieldAttribute,
            Some("Override the column name".to_string()),
        ),
        CompletionItem::new(
            "store(json)",
            CompletionKind::FieldAttribute,
            Some("Store as JSON column".to_string()),
        ),
        CompletionItem::new(
            "updatedAt",
            CompletionKind::FieldAttribute,
            Some("Auto-set to current timestamp on every write".to_string()),
        ),
        CompletionItem::with_snippet(
            "computed(…, Stored)",
            "computed(${1:expr}, ${2|Stored,Virtual|})",
            CompletionKind::FieldAttribute,
            Some("Database-generated column (Stored or Virtual)".to_string()),
        ),
        CompletionItem::with_snippet(
            "check(…)",
            "check(${1:expr})",
            CompletionKind::FieldAttribute,
            Some("Add a CHECK constraint on this field".to_string()),
        ),
    ]
}

fn model_attribute_completions() -> Vec<CompletionItem> {
    vec![
        CompletionItem::new(
            "id([])",
            CompletionKind::ModelAttribute,
            Some("Composite primary key".to_string()),
        ),
        CompletionItem::new(
            "unique([])",
            CompletionKind::ModelAttribute,
            Some("Composite unique constraint".to_string()),
        ),
        CompletionItem::new(
            "index([])",
            CompletionKind::ModelAttribute,
            Some(
                "Add a database index — optionally with type: BTree|Hash|Gin|Gist|Brin|FullText"
                    .to_string(),
            ),
        ),
        CompletionItem::new(
            "map(\"\")",
            CompletionKind::ModelAttribute,
            Some("Override the table name".to_string()),
        ),
        CompletionItem::with_snippet(
            "check(…)",
            "check(${1:expr})",
            CompletionKind::ModelAttribute,
            Some("Add a table-level CHECK constraint".to_string()),
        ),
    ]
}

fn datasource_generator_completions() -> Vec<CompletionItem> {
    vec![
        CompletionItem::new(
            "provider",
            CompletionKind::FieldName,
            Some("Database / generator provider".to_string()),
        ),
        CompletionItem::new(
            "url",
            CompletionKind::FieldName,
            Some("Connection URL".to_string()),
        ),
        CompletionItem::new(
            "output",
            CompletionKind::FieldName,
            Some("Output path for generated files".to_string()),
        ),
        CompletionItem::new(
            "interface",
            CompletionKind::FieldName,
            Some("Client interface style: \"sync\" (default) or \"async\"".to_string()),
        ),
        CompletionItem::new(
            "recursive_type_depth",
            CompletionKind::FieldName,
            Some(
                "Depth of recursive include TypedDicts — Python client only (default: 5)"
                    .to_string(),
            ),
        ),
    ]
}

/// Detects whether `offset` is inside a `datasource` or `generator` block,
/// by scanning the token stream backwards to find the enclosing block keyword.
fn config_block_kind_at(tokens: &[Token], offset: usize) -> Option<ConfigBlockKind> {
    let relevant: Vec<&Token> = tokens.iter().filter(|t| t.span.end <= offset).collect();

    let mut depth: i32 = 0;
    for tok in relevant.iter().rev() {
        match tok.kind {
            TokenKind::RBrace => depth += 1,
            TokenKind::LBrace => {
                if depth == 0 {
                    let idx = tokens
                        .iter()
                        .position(|t| std::ptr::eq(t, *tok))
                        .unwrap_or(0);
                    // Block structure: keyword name { … }
                    // The token before the name is the keyword.
                    let before: Vec<&Token> = tokens[..idx]
                        .iter()
                        .filter(|t| !matches!(t.kind, TokenKind::Newline))
                        .collect();
                    if before.len() >= 2 {
                        let kw_tok = &before[before.len() - 2];
                        return match kw_tok.kind {
                            TokenKind::Datasource => Some(ConfigBlockKind::Datasource),
                            TokenKind::Generator => Some(ConfigBlockKind::Generator),
                            _ => None,
                        };
                    }
                    return None;
                }
                depth -= 1;
            }
            _ => {}
        }
    }
    None
}

fn config_value_completions(key: &str, block_kind: Option<ConfigBlockKind>) -> Vec<CompletionItem> {
    match key {
        "provider" => match block_kind {
            Some(ConfigBlockKind::Datasource) => vec![
                CompletionItem::with_insert(
                    "postgresql",
                    "\"postgresql\"",
                    CompletionKind::Keyword,
                    Some("PostgreSQL database".to_string()),
                ),
                CompletionItem::with_insert(
                    "mysql",
                    "\"mysql\"",
                    CompletionKind::Keyword,
                    Some("MySQL database".to_string()),
                ),
                CompletionItem::with_insert(
                    "sqlite",
                    "\"sqlite\"",
                    CompletionKind::Keyword,
                    Some("SQLite database".to_string()),
                ),
            ],
            Some(ConfigBlockKind::Generator) => vec![
                CompletionItem::with_insert(
                    "nautilus-client-rs",
                    "\"nautilus-client-rs\"",
                    CompletionKind::Keyword,
                    Some("Rust client generator".to_string()),
                ),
                CompletionItem::with_insert(
                    "nautilus-client-py",
                    "\"nautilus-client-py\"",
                    CompletionKind::Keyword,
                    Some("Python client generator".to_string()),
                ),
                CompletionItem::with_insert(
                    "nautilus-client-js",
                    "\"nautilus-client-js\"",
                    CompletionKind::Keyword,
                    Some("JavaScript/TypeScript client generator".to_string()),
                ),
            ],
            None => vec![
                CompletionItem::with_insert(
                    "postgresql",
                    "\"postgresql\"",
                    CompletionKind::Keyword,
                    Some("PostgreSQL database".to_string()),
                ),
                CompletionItem::with_insert(
                    "mysql",
                    "\"mysql\"",
                    CompletionKind::Keyword,
                    Some("MySQL database".to_string()),
                ),
                CompletionItem::with_insert(
                    "sqlite",
                    "\"sqlite\"",
                    CompletionKind::Keyword,
                    Some("SQLite database".to_string()),
                ),
                CompletionItem::with_insert(
                    "nautilus-client-rs",
                    "\"nautilus-client-rs\"",
                    CompletionKind::Keyword,
                    Some("Rust client generator".to_string()),
                ),
                CompletionItem::with_insert(
                    "nautilus-client-py",
                    "\"nautilus-client-py\"",
                    CompletionKind::Keyword,
                    Some("Python client generator".to_string()),
                ),
                CompletionItem::with_insert(
                    "nautilus-client-js",
                    "\"nautilus-client-js\"",
                    CompletionKind::Keyword,
                    Some("JavaScript/TypeScript client generator".to_string()),
                ),
            ],
        },
        "interface" => vec![
            CompletionItem::with_insert(
                "sync",
                "\"sync\"",
                CompletionKind::Keyword,
                Some("Synchronous client interface (default)".to_string()),
            ),
            CompletionItem::with_insert(
                "async",
                "\"async\"",
                CompletionKind::Keyword,
                Some("Asynchronous client interface".to_string()),
            ),
        ],
        _ => Vec::new(),
    }
}