specta-swift 0.0.2

Export your Rust types to Swift
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
//! Primitive type conversion from Rust to Swift.

use std::borrow::Cow;

use specta::{
    Types,
    datatype::{DataType, Enum, Fields, GenericReference, Primitive, Reference, Variant},
};

use crate::error::{Error, Result};
use crate::swift::Swift;

fn enum_string_raw_value(variant: &Variant) -> Option<&str> {
    let Fields::Unnamed(fields) = variant.fields() else {
        return None;
    };

    let [field] = fields.fields() else {
        return None;
    };

    let DataType::Enum(literal_enum) = field.ty()? else {
        return None;
    };

    let [(raw_value, literal_variant)] = literal_enum.variants() else {
        return None;
    };

    matches!(literal_variant.fields(), Fields::Unit).then_some(raw_value.as_ref())
}

fn resolved_string_enum(e: &Enum) -> Option<Vec<(&str, &str)>> {
    e.variants()
        .iter()
        .map(|(variant_name, variant)| {
            enum_string_raw_value(variant).map(|raw| (variant_name.as_ref(), raw))
        })
        .collect()
}

/// Export a single type to Swift.
pub fn export_type(
    swift: &Swift,
    types: &Types,
    ndt: &specta::datatype::NamedDataType,
) -> Result<String> {
    if !matches!(ndt.ty(), DataType::Struct(_) | DataType::Enum(_)) {
        return Ok(String::new());
    }

    let mut result = String::new();

    // Add JSDoc-style comments if present
    if !ndt.docs().is_empty() {
        let docs = ndt.docs();
        // Handle multi-line comments properly
        for line in docs.lines() {
            result.push_str("/// ");
            // Trim leading whitespace from the line to avoid extra spaces
            result.push_str(line.trim_start());
            result.push('\n');
        }
    }

    // Add deprecated annotation if present
    if let Some(deprecated) = ndt.deprecated() {
        let message = deprecated
            .note()
            .filter(|note| !note.trim().is_empty())
            .map(ToString::to_string)
            .unwrap_or_else(|| "This type is deprecated".to_string());
        result.push_str(&format!(
            "@available(*, deprecated, message: \"{}\")\n",
            message
        ));
    }

    let generic_scope = ndt.generics().to_vec();

    // Format based on type
    match ndt.ty() {
        DataType::Struct(_) => {
            let type_def =
                datatype_to_swift(swift, types, ndt.ty(), generic_scope.clone(), false, None)?;
            let name = swift.naming.convert(ndt.name());
            let generics = if ndt.generics().is_empty() {
                String::new()
            } else {
                format!(
                    "<{}>",
                    ndt.generics()
                        .iter()
                        .map(|(_, g)| g.as_ref().to_string())
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            };

            result.push_str(&format!("public struct {}{}: Codable {{\n", name, generics));
            result.push_str(&type_def);
            result.push('}');
        }
        DataType::Enum(e) => {
            let name = swift.naming.convert(ndt.name());
            let generics = if ndt.generics().is_empty() {
                String::new()
            } else {
                format!(
                    "<{}>",
                    ndt.generics()
                        .iter()
                        .map(|(_, g)| g.as_ref().to_string())
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            };

            // Check if this is a string enum
            let is_string_enum_val = resolved_string_enum(e).is_some();

            // Check if this enum has struct-like variants (needs custom Codable)
            let has_struct_variants = e.variants().iter().any(|(_, variant)| {
                matches!(variant.fields(), specta::datatype::Fields::Named(fields) if !fields.fields().is_empty())
            });

            // Determine protocols based on whether we'll generate custom Codable
            let protocols = if is_string_enum_val {
                if has_struct_variants {
                    "String" // Custom Codable will be generated
                } else {
                    "String, Codable"
                }
            } else if has_struct_variants {
                "" // Custom Codable will be generated
            } else {
                "Codable"
            };

            let protocol_part = if protocols.is_empty() {
                String::new()
            } else {
                format!(": {}", protocols)
            };

            result.push_str(&format!(
                "public enum {}{}{} {{\n",
                name, generics, protocol_part
            ));
            let enum_body = enum_to_swift(
                swift,
                types,
                e,
                generic_scope.clone(),
                false,
                None,
                Some(&name),
            )?;
            result.push_str(&enum_body);
            result.push('}');

            // Generate struct definitions for named field variants
            let struct_definitions =
                generate_enum_structs(swift, types, e, generic_scope, false, None, &name)?;
            result.push_str(&struct_definitions);

            // Generate custom Codable implementation for enums with struct variants
            if has_struct_variants {
                let codable_impl = generate_enum_codable_impl(swift, e, &name)?;
                result.push_str(&codable_impl);
            }
        }
        _ => {
            return Ok(String::new());
        }
    }

    Ok(result)
}

/// Convert a DataType to Swift syntax.
pub fn datatype_to_swift(
    swift: &Swift,
    types: &Types,
    dt: &DataType,
    generic_scope: Vec<(GenericReference, Cow<'static, str>)>,
    is_export: bool,
    reference: Option<&specta::datatype::Reference>,
) -> Result<String> {
    // Check for special standard library types first
    if let Some(special_type) = is_special_std_type(types, reference) {
        return Ok(special_type);
    }

    match dt {
        DataType::Primitive(p) => primitive_to_swift(p),
        // DataType::Literal(l) => literal_to_swift(l),
        DataType::List(l) => list_to_swift(swift, types, l, generic_scope.clone()),
        DataType::Map(m) => map_to_swift(swift, types, m, generic_scope.clone()),
        DataType::Nullable(def) => {
            let inner = datatype_to_swift(swift, types, def, generic_scope, is_export, None)?;
            Ok(match swift.optionals {
                crate::swift::OptionalStyle::QuestionMark => format!("{}?", inner),
                crate::swift::OptionalStyle::Optional => format!("Optional<{}>", inner),
            })
        }
        DataType::Struct(s) => {
            // Check if this is a Duration struct by looking at its fields
            if is_duration_struct(s) {
                return Ok("RustDuration".to_string());
            }
            struct_to_swift(swift, types, s, generic_scope, is_export, None)
        }
        DataType::Enum(e) => enum_to_swift(swift, types, e, generic_scope, is_export, None, None),
        DataType::Tuple(t) => tuple_to_swift(swift, types, t, generic_scope.clone()),
        DataType::Reference(r) => reference_to_swift(swift, types, r, &generic_scope),
    }
}

/// Check if a struct is a Duration by examining its fields
pub fn is_duration_struct(s: &specta::datatype::Struct) -> bool {
    match s.fields() {
        specta::datatype::Fields::Named(fields) => {
            let field_names: Vec<String> = fields
                .fields()
                .iter()
                .map(|(name, _)| name.to_string())
                .collect();
            // Duration has exactly two fields: "secs" (u64) and "nanos" (u32)
            field_names.len() == 2
                && field_names.contains(&"secs".to_string())
                && field_names.contains(&"nanos".to_string())
        }
        _ => false,
    }
}

/// Check if a type is a special standard library type that needs special handling
fn is_special_std_type(
    types: &Types,
    reference: Option<&specta::datatype::Reference>,
) -> Option<String> {
    if let Some(Reference::Named(r)) = reference
        && let Some(ndt) = r.get(types)
    {
        // Check for std::time::Duration
        if ndt.name() == "Duration" {
            return Some("RustDuration".to_string());
        }
        // Check for std::time::SystemTime
        if ndt.name() == "SystemTime" {
            return Some("Date".to_string());
        }
    }
    None
}

/// Convert primitive types to Swift.
fn primitive_to_swift(primitive: &Primitive) -> Result<String> {
    Ok(match primitive {
        Primitive::i8 => "Int8".to_string(),
        Primitive::i16 => "Int16".to_string(),
        Primitive::i32 => "Int32".to_string(),
        Primitive::i64 => "Int64".to_string(),
        Primitive::isize => "Int".to_string(),
        Primitive::u8 => "UInt8".to_string(),
        Primitive::u16 => "UInt16".to_string(),
        Primitive::u32 => "UInt32".to_string(),
        Primitive::u64 => "UInt64".to_string(),
        Primitive::usize => "UInt".to_string(),
        Primitive::f32 => "Float".to_string(),
        Primitive::f64 => "Double".to_string(),
        Primitive::bool => "Bool".to_string(),
        Primitive::char => "Character".to_string(),
        Primitive::str => "String".to_string(),
        Primitive::i128 | Primitive::u128 => {
            return Err(Error::UnsupportedType(
                "Swift does not support 128-bit integers".to_string(),
            ));
        }
        Primitive::f16 => {
            return Err(Error::UnsupportedType(
                "Swift does not support f16".to_string(),
            ));
        }
        Primitive::f128 => {
            return Err(Error::UnsupportedType(
                "Swift does not support f128".to_string(),
            ));
        }
    })
}

// /// Convert literal types to Swift.
// fn literal_to_swift(literal: &specta::datatype::Literal) -> Result<String> {
//     Ok(match literal {
//         specta::datatype::Literal::i8(v) => v.to_string(),
//         specta::datatype::Literal::i16(v) => v.to_string(),
//         specta::datatype::Literal::i32(v) => v.to_string(),
//         specta::datatype::Literal::u8(v) => v.to_string(),
//         specta::datatype::Literal::u16(v) => v.to_string(),
//         specta::datatype::Literal::u32(v) => v.to_string(),
//         specta::datatype::Literal::f32(v) => v.to_string(),
//         specta::datatype::Literal::f64(v) => v.to_string(),
//         specta::datatype::Literal::bool(v) => v.to_string(),
//         specta::datatype::Literal::String(s) => format!("\"{}\"", s),
//         specta::datatype::Literal::char(c) => format!("\"{}\"", c),
//         specta::datatype::Literal::None => "nil".to_string(),
//         _ => {
//             return Err(Error::UnsupportedType(
//                 "Unsupported literal type".to_string(),
//             ));
//         }
//     })
// }

/// Convert list types to Swift arrays.
fn list_to_swift(
    swift: &Swift,
    types: &Types,
    list: &specta::datatype::List,
    generic_scope: Vec<(GenericReference, Cow<'static, str>)>,
) -> Result<String> {
    let element_type = datatype_to_swift(swift, types, list.ty(), generic_scope, false, None)?;
    Ok(format!("[{}]", element_type))
}

/// Convert map types to Swift dictionaries.
fn map_to_swift(
    swift: &Swift,
    types: &Types,
    map: &specta::datatype::Map,
    generic_scope: Vec<(GenericReference, Cow<'static, str>)>,
) -> Result<String> {
    let key_type = datatype_to_swift(
        swift,
        types,
        map.key_ty(),
        generic_scope.clone(),
        false,
        None,
    )?;
    let value_type = datatype_to_swift(swift, types, map.value_ty(), generic_scope, false, None)?;
    Ok(format!("[{}: {}]", key_type, value_type))
}

/// Convert struct types to Swift.
fn struct_to_swift(
    swift: &Swift,
    types: &Types,
    s: &specta::datatype::Struct,
    generic_scope: Vec<(GenericReference, Cow<'static, str>)>,
    is_export: bool,
    _reference: Option<&specta::datatype::Reference>,
) -> Result<String> {
    match s.fields() {
        specta::datatype::Fields::Unit => Ok("Void".to_string()),
        specta::datatype::Fields::Unnamed(fields) => {
            if fields.fields().is_empty() {
                Ok("Void".to_string())
            } else if fields.fields().len() == 1 {
                // Single field tuple struct - convert to a proper struct with a 'value' field
                let field_type = datatype_to_swift(
                    swift,
                    types,
                    fields.fields()[0]
                        .ty()
                        .expect("tuple field should have a type"),
                    generic_scope,
                    is_export,
                    None,
                )?;
                Ok(format!("    let value: {}\n", field_type))
            } else {
                // Multiple field tuple struct - convert to a proper struct with numbered fields
                let mut result = String::new();
                for (i, field) in fields.fields().iter().enumerate() {
                    let field_type = datatype_to_swift(
                        swift,
                        types,
                        field.ty().expect("tuple field should have a type"),
                        generic_scope.clone(),
                        is_export,
                        None,
                    )?;
                    result.push_str(&format!("    public let field{}: {}\n", i, field_type));
                }
                Ok(result)
            }
        }
        specta::datatype::Fields::Named(fields) => {
            let mut result = String::new();
            let mut field_mappings = Vec::new();

            for (original_field_name, field) in fields.fields() {
                let field_type = if let Some(ty) = field.ty() {
                    datatype_to_swift(swift, types, ty, generic_scope.clone(), is_export, None)?
                } else {
                    continue;
                };

                let optional_marker = if field.optional() { "?" } else { "" };
                let swift_field_name = swift.naming.convert_field(original_field_name);

                result.push_str(&format!(
                    "    public let {}: {}{}\n",
                    swift_field_name, field_type, optional_marker
                ));

                field_mappings.push((swift_field_name, original_field_name.to_string()));
            }

            // Generate custom CodingKeys if field names were converted
            let needs_custom_coding_keys = field_mappings
                .iter()
                .any(|(swift_name, rust_name)| swift_name != rust_name);
            if needs_custom_coding_keys {
                result.push_str("\n    private enum CodingKeys: String, CodingKey {\n");
                for (swift_name, rust_name) in &field_mappings {
                    result.push_str(&format!(
                        "        case {} = \"{}\"\n",
                        swift_name, rust_name
                    ));
                }
                result.push_str("    }\n");
            }

            Ok(result)
        }
    }
}

/// Convert enum types to Swift.
fn enum_to_swift(
    swift: &Swift,
    types: &Types,
    e: &specta::datatype::Enum,
    generic_scope: Vec<(GenericReference, Cow<'static, str>)>,
    is_export: bool,
    _reference: Option<&specta::datatype::Reference>,
    enum_name: Option<&str>,
) -> Result<String> {
    let mut result = String::new();

    // Check if this is a string enum
    let is_string_enum = resolved_string_enum(e).is_some();

    for (original_variant_name, variant) in e.variants() {
        if variant.skip() {
            continue;
        }

        let variant_name = swift.naming.convert_enum_case(original_variant_name);

        match variant.fields() {
            specta::datatype::Fields::Unit => {
                if is_string_enum {
                    let raw_value = enum_string_raw_value(variant)
                        .expect("string enum variants should have string literal payloads");
                    result.push_str(&format!("    case {} = \"{}\"\n", variant_name, raw_value));
                } else {
                    result.push_str(&format!("    case {}\n", variant_name));
                }
            }
            specta::datatype::Fields::Unnamed(fields) => {
                if is_string_enum && let Some(raw_value) = enum_string_raw_value(variant) {
                    result.push_str(&format!("    case {} = \"{}\"\n", variant_name, raw_value));
                } else if fields.fields().is_empty() {
                    result.push_str(&format!("    case {}\n", variant_name));
                } else {
                    let types_str = fields
                        .fields()
                        .iter()
                        .map(|f| {
                            datatype_to_swift(
                                swift,
                                types,
                                f.ty().expect("enum variant field should have a type"),
                                generic_scope.clone(),
                                is_export,
                                None,
                            )
                        })
                        .collect::<std::result::Result<Vec<_>, _>>()?
                        .join(", ");
                    result.push_str(&format!("    case {}({})\n", variant_name, types_str));
                }
            }
            specta::datatype::Fields::Named(fields) => {
                if fields.fields().is_empty() {
                    result.push_str(&format!("    case {}\n", variant_name));
                } else {
                    // Generate struct for named fields
                    // Use the original variant name for PascalCase struct name
                    let pascal_variant_name = to_pascal_case(original_variant_name);
                    let struct_name = if let Some(enum_name) = enum_name {
                        format!("{}{}Data", enum_name, pascal_variant_name)
                    } else {
                        format!("{}Data", pascal_variant_name)
                    };

                    // Generate enum case that references the struct
                    result.push_str(&format!("    case {}({})\n", variant_name, struct_name));
                }
            }
        }
    }

    Ok(result)
}

/// Generate struct definitions for enum variants with named fields
fn generate_enum_structs(
    swift: &Swift,
    types: &Types,
    e: &specta::datatype::Enum,
    generic_scope: Vec<(GenericReference, Cow<'static, str>)>,
    is_export: bool,
    _reference: Option<&specta::datatype::Reference>,
    enum_name: &str,
) -> Result<String> {
    let mut result = String::new();

    for (original_variant_name, variant) in e.variants() {
        if variant.skip() {
            continue;
        }

        if let specta::datatype::Fields::Named(fields) = variant.fields()
            && !fields.fields().is_empty()
        {
            let pascal_variant_name = to_pascal_case(original_variant_name);
            let struct_name = format!("{}{}Data", enum_name, pascal_variant_name);

            // Generate struct definition with custom CodingKeys for field name mapping
            result.push_str(&format!("\npublic struct {}: Codable {{\n", struct_name));

            // Generate struct fields
            let mut field_mappings = Vec::new();
            for (original_field_name, field) in fields.fields() {
                if let Some(ty) = field.ty() {
                    let field_type = datatype_to_swift(
                        swift,
                        types,
                        ty,
                        generic_scope.clone(),
                        is_export,
                        None,
                    )?;
                    let optional_marker = if field.optional() { "?" } else { "" };
                    let swift_field_name = swift.naming.convert_field(original_field_name);
                    result.push_str(&format!(
                        "    public let {}: {}{}\n",
                        swift_field_name, field_type, optional_marker
                    ));
                    field_mappings.push((swift_field_name, original_field_name.to_string()));
                }
            }

            // Generate custom CodingKeys if field names were converted
            let needs_custom_coding_keys = field_mappings
                .iter()
                .any(|(swift_name, rust_name)| swift_name != rust_name);
            if needs_custom_coding_keys {
                result.push_str("\n    private enum CodingKeys: String, CodingKey {\n");
                for (swift_name, rust_name) in &field_mappings {
                    result.push_str(&format!(
                        "        case {} = \"{}\"\n",
                        swift_name, rust_name
                    ));
                }
                result.push_str("    }\n");
            }

            result.push_str("}\n");
        }
    }

    Ok(result)
}

/// Convert a string to PascalCase
fn to_pascal_case(s: &str) -> String {
    // If it's already PascalCase (starts with uppercase), return as-is
    if s.chars().next().is_some_and(|c| c.is_uppercase()) {
        return s.to_string();
    }

    // Otherwise, convert snake_case to PascalCase
    let mut result = String::new();
    let mut capitalize_next = true;

    for c in s.chars() {
        if c == '_' || c == '-' {
            capitalize_next = true;
        } else if capitalize_next {
            result.push(c.to_uppercase().next().unwrap_or(c));
            capitalize_next = false;
        } else {
            result.push(c.to_lowercase().next().unwrap_or(c));
        }
    }

    result
}

/// Convert tuple types to Swift.
fn tuple_to_swift(
    swift: &Swift,
    types: &Types,
    t: &specta::datatype::Tuple,
    generic_scope: Vec<(GenericReference, Cow<'static, str>)>,
) -> Result<String> {
    if t.elements().is_empty() {
        Ok("Void".to_string())
    } else if t.elements().len() == 1 {
        datatype_to_swift(swift, types, &t.elements()[0], generic_scope, false, None)
    } else {
        let types_str = t
            .elements()
            .iter()
            .map(|e| datatype_to_swift(swift, types, e, generic_scope.clone(), false, None))
            .collect::<std::result::Result<Vec<_>, _>>()?
            .join(", ");
        Ok(format!("({})", types_str))
    }
}

/// Convert reference types to Swift.
fn reference_to_swift(
    swift: &Swift,
    types: &Types,
    r: &specta::datatype::Reference,
    generic_scope: &[(GenericReference, Cow<'static, str>)],
) -> Result<String> {
    match r {
        Reference::Named(r) => {
            let Some(ndt) = r.get(types) else {
                return Err(Error::InvalidIdentifier(
                    "Reference to unknown type".to_string(),
                ));
            };

            if ndt.name() == "String" {
                return Ok("String".to_string());
            }

            if matches!(ndt.name().as_ref(), "Uuid" | "DateTime" | "NaiveDateTime") {
                return Ok("String".to_string());
            }

            if ndt.name() == "Vec"
                && let Some((_, inner_ty)) = r.generics().first()
            {
                let inner =
                    datatype_to_swift(swift, types, inner_ty, generic_scope.to_vec(), false, None)?;
                return Ok(format!("[{inner}]"));
            }

            let name = swift.naming.convert(ndt.name());

            if r.generics().is_empty() {
                Ok(name)
            } else {
                let generics = r
                    .generics()
                    .iter()
                    .map(|(_, t)| {
                        datatype_to_swift(swift, types, t, generic_scope.to_vec(), false, None)
                    })
                    .collect::<std::result::Result<Vec<_>, _>>()?
                    .join(", ");
                Ok(format!("{}<{}>", name, generics))
            }
        }
        Reference::Opaque(_) => Err(Error::UnsupportedType(
            "Opaque references are not supported by Swift exporter".to_string(),
        )),
        Reference::Generic(g) => generic_to_swift(swift, g, generic_scope),
    }
}

/// Convert generic types to Swift.
fn generic_to_swift(
    _swift: &Swift,
    g: &specta::datatype::GenericReference,
    generic_scope: &[(GenericReference, Cow<'static, str>)],
) -> Result<String> {
    generic_scope
        .iter()
        .find_map(|(candidate, name)| (candidate == g).then(|| name.to_string()))
        .ok_or_else(|| Error::GenericConstraint(format!("Unresolved generic reference: {g:?}")))
}

/// Generate custom Codable implementation for enums with struct-like variants
fn generate_enum_codable_impl(
    swift: &Swift,
    e: &specta::datatype::Enum,
    enum_name: &str,
) -> Result<String> {
    let mut result = String::new();

    result.push_str(&format!(
        "\n// MARK: - {} Codable Implementation\n",
        enum_name
    ));
    result.push_str(&format!("extension {}: Codable {{\n", enum_name));

    // Generate CodingKeys enum
    result.push_str("    private enum CodingKeys: String, CodingKey {\n");
    for (original_variant_name, variant) in e.variants() {
        if variant.skip() {
            continue;
        }
        let swift_case_name = swift.naming.convert_enum_case(original_variant_name);
        result.push_str(&format!(
            "        case {} = \"{}\"\n",
            swift_case_name, original_variant_name
        ));
    }
    result.push_str("    }\n\n");

    // Generate init(from decoder:)
    result.push_str("    public init(from decoder: Decoder) throws {\n");
    result.push_str("        let container = try decoder.container(keyedBy: CodingKeys.self)\n");
    result.push_str("        \n");
    result.push_str("        if container.allKeys.count != 1 {\n");
    result.push_str("            throw DecodingError.dataCorrupted(\n");
    result.push_str("                DecodingError.Context(codingPath: decoder.codingPath, debugDescription: \"Invalid number of keys found, expected one.\")\n");
    result.push_str("            )\n");
    result.push_str("        }\n\n");
    result.push_str("        let key = container.allKeys.first!\n");
    result.push_str("        switch key {\n");

    for (original_variant_name, variant) in e.variants() {
        if variant.skip() {
            continue;
        }

        let swift_case_name = swift.naming.convert_enum_case(original_variant_name);

        match variant.fields() {
            specta::datatype::Fields::Unit => {
                result.push_str(&format!("        case .{}:\n", swift_case_name));
                result.push_str(&format!("            self = .{}\n", swift_case_name));
            }
            specta::datatype::Fields::Unnamed(fields) => {
                if fields.fields().is_empty() {
                    result.push_str(&format!("        case .{}:\n", swift_case_name));
                    result.push_str(&format!("            self = .{}\n", swift_case_name));
                } else {
                    // For tuple variants, decode as array
                    result.push_str(&format!("        case .{}:\n", swift_case_name));
                    result.push_str(&format!(
                        "            // TODO: Implement tuple variant decoding for {}\n",
                        swift_case_name
                    ));
                    result.push_str(
                        "            fatalError(\"Tuple variant decoding not implemented\")\n",
                    );
                }
            }
            specta::datatype::Fields::Named(_) => {
                let pascal_variant_name = to_pascal_case(original_variant_name);
                let struct_name = format!("{}{}Data", enum_name, pascal_variant_name);

                result.push_str(&format!("        case .{}:\n", swift_case_name));
                result.push_str(&format!(
                    "            let data = try container.decode({}.self, forKey: .{})\n",
                    struct_name, swift_case_name
                ));
                result.push_str(&format!("            self = .{}(data)\n", swift_case_name));
            }
        }
    }

    result.push_str("        }\n");
    result.push_str("    }\n\n");

    // Generate encode(to encoder:)
    result.push_str("    public func encode(to encoder: Encoder) throws {\n");
    result.push_str("        var container = encoder.container(keyedBy: CodingKeys.self)\n");
    result.push_str("        \n");
    result.push_str("        switch self {\n");

    for (original_variant_name, variant) in e.variants() {
        if variant.skip() {
            continue;
        }

        let swift_case_name = swift.naming.convert_enum_case(original_variant_name);

        match variant.fields() {
            specta::datatype::Fields::Unit => {
                result.push_str(&format!("        case .{}:\n", swift_case_name));
                result.push_str(&format!(
                    "            try container.encodeNil(forKey: .{})\n",
                    swift_case_name
                ));
            }
            specta::datatype::Fields::Unnamed(_) => {
                // TODO: Handle tuple variants
                result.push_str(&format!("        case .{}:\n", swift_case_name));
                result.push_str(&format!(
                    "            // TODO: Implement tuple variant encoding for {}\n",
                    swift_case_name
                ));
                result.push_str(
                    "            fatalError(\"Tuple variant encoding not implemented\")\n",
                );
            }
            specta::datatype::Fields::Named(_) => {
                result.push_str(&format!("        case .{}(let data):\n", swift_case_name));
                result.push_str(&format!(
                    "            try container.encode(data, forKey: .{})\n",
                    swift_case_name
                ));
            }
        }
    }

    result.push_str("        }\n");
    result.push_str("    }\n");
    result.push_str("}\n");

    Ok(result)
}