motto 0.4.3

Compiler-as-a-Service: Turn Rust schema.rs into multi-platform SDK toolkits
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
//! Unity/C# Backend Emitter
//!
//! Generates C# SDK for Unity with:
//! - Unsafe pointers for memory-efficient DllImport
//! - WebAssembly.instantiate support
//! - Zero-copy packet framing

use crate::emitters::{Emitter, EmitterConfig, GeneratedFile, TransportMode, utils};
use crate::ir::manifest::*;
use anyhow::Result;
use std::path::PathBuf;

/// C# reserved words
const CSHARP_RESERVED: &[&str] = &[
    "abstract",
    "as",
    "base",
    "bool",
    "break",
    "byte",
    "case",
    "catch",
    "char",
    "checked",
    "class",
    "const",
    "continue",
    "decimal",
    "default",
    "delegate",
    "do",
    "double",
    "else",
    "enum",
    "event",
    "explicit",
    "extern",
    "false",
    "finally",
    "fixed",
    "float",
    "for",
    "foreach",
    "goto",
    "if",
    "implicit",
    "in",
    "int",
    "interface",
    "internal",
    "is",
    "lock",
    "long",
    "namespace",
    "new",
    "null",
    "object",
    "operator",
    "out",
    "override",
    "params",
    "private",
    "protected",
    "public",
    "readonly",
    "ref",
    "return",
    "sbyte",
    "sealed",
    "short",
    "sizeof",
    "stackalloc",
    "static",
    "string",
    "struct",
    "switch",
    "this",
    "throw",
    "true",
    "try",
    "typeof",
    "uint",
    "ulong",
    "unchecked",
    "unsafe",
    "ushort",
    "using",
    "virtual",
    "void",
    "volatile",
    "while",
];

pub struct UnityEmitter;

impl Emitter for UnityEmitter {
    fn platform(&self) -> &'static str {
        "unity"
    }

    fn extension(&self) -> &'static str {
        "cs"
    }

    fn emit(&self, config: &EmitterConfig) -> Result<Vec<GeneratedFile>> {
        let files = vec![
            generate_types(&config.manifest)?,
            generate_codec(&config.manifest)?,
            generate_runtime(&config.manifest, config.transport_mode)?,
            generate_native_bridge(&config.manifest)?,
            generate_asmdef(&config.manifest)?,
            generate_dotnet_sdk_project()?,
            generate_dotnet_test_project()?,
            generate_tests(&config.manifest)?,
        ];

        Ok(files)
    }
}

/// Emit Unity SDK
pub fn emit(config: &EmitterConfig) -> Result<()> {
    let emitter = UnityEmitter;
    let files = emitter.emit(config)?;

    let unity_dir = config.output_dir.join("unity").join("MottoSDK");
    std::fs::create_dir_all(&unity_dir)?;

    for file in files {
        let path = unity_dir.join(&file.path);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(&path, &file.content)?;
    }

    Ok(())
}

fn csharp_header(manifest: &SchemaManifest) -> String {
    format!(
        r#"/*
 * MOTTO GENERATED CODE - DO NOT EDIT
 *
 * Protocol Version: 0x{:02X}
 * Schema Fingerprint: {}
 * Generated At: {}
 */

using System;
using System.Runtime.InteropServices;
using System.Text;
"#,
        manifest.meta.version_byte,
        &manifest.meta.fingerprint[..16],
        manifest.meta.generated_at
    )
}

fn generate_types(manifest: &SchemaManifest) -> Result<GeneratedFile> {
    let mut content = csharp_header(manifest);

    content.push_str("\nnamespace Motto.SDK\n{\n");

    // Generate enums
    for e in &manifest.enums {
        content.push_str(&generate_enum_type(e));
        content.push('\n');
    }

    // Generate structs
    for msg in &manifest.messages {
        content.push_str(&generate_struct(msg));
        content.push('\n');
    }

    content.push_str("}\n");

    Ok(GeneratedFile {
        path: PathBuf::from("Runtime/Types.cs"),
        content,
    })
}

fn generate_enum_type(e: &EnumManifest) -> String {
    let mut s = String::new();

    if let Some(docs) = &e.docs {
        s.push_str(&format!("    /// <summary>{}</summary>\n", docs));
    }

    if e.is_simple {
        // C-style enum
        let base_type = rust_to_csharp_type(&e.repr);
        s.push_str(&format!(
            "    public enum {} : {}\n    {{\n",
            e.name, base_type
        ));
        for v in &e.variants {
            if let Some(docs) = &v.docs {
                s.push_str(&format!("        /// <summary>{}</summary>\n", docs));
            }
            s.push_str(&format!("        {} = {},\n", v.name, v.discriminant));
        }
        s.push_str("    }\n");
    } else {
        // Tagged union -> abstract base class with derived types
        s.push_str(&format!("    public abstract class {}\n    {{\n", e.name));
        s.push_str("        public abstract byte Tag { get; }\n");
        s.push_str("    }\n\n");

        for (idx, v) in e.variants.iter().enumerate() {
            if let Some(docs) = &v.docs {
                s.push_str(&format!("    /// <summary>{}</summary>\n", docs));
            }
            match &v.data {
                VariantData::Unit => {
                    s.push_str(&format!(
                        "    public sealed class {}_{} : {}\n    {{\n        public override byte Tag => {};\n    }}\n\n",
                        e.name, v.name, e.name, idx
                    ));
                }
                VariantData::Tuple { types } => {
                    s.push_str(&format!(
                        "    public sealed class {}_{} : {}\n    {{\n        public override byte Tag => {};\n",
                        e.name, v.name, e.name, idx
                    ));
                    for (i, t) in types.iter().enumerate() {
                        s.push_str(&format!(
                            "        public {} Item{} {{ get; set; }}\n",
                            rust_to_csharp_type(t),
                            i + 1
                        ));
                    }
                    s.push_str("    }\n\n");
                }
                VariantData::Struct { fields } => {
                    s.push_str(&format!(
                        "    public sealed class {}_{} : {}\n    {{\n        public override byte Tag => {};\n",
                        e.name, v.name, e.name, idx
                    ));
                    for f in fields {
                        s.push_str(&format!(
                            "        public {} {} {{ get; set; }}\n",
                            rust_to_csharp_type(&f.type_ref),
                            utils::to_pascal_case(&f.name)
                        ));
                    }
                    s.push_str("    }\n\n");
                }
            }
        }
    }

    s
}

fn generate_struct(msg: &MessageDef) -> String {
    let mut s = String::new();

    if let Some(docs) = &msg.docs {
        s.push_str(&format!("    /// <summary>{}</summary>\n", docs));
    }

    // Use struct for fixed-size, class for variable-size
    let type_keyword = if msg.fixed_size.is_some() {
        "struct"
    } else {
        "class"
    };
    let struct_layout = if msg.fixed_size.is_some() {
        format!(
            "    [StructLayout(LayoutKind.Sequential, Pack = {})]\n",
            msg.alignment
        )
    } else {
        String::new()
    };

    let generics = if msg.generics.is_empty() {
        String::new()
    } else {
        format!("<{}>", msg.generics.join(", "))
    };

    s.push_str(&struct_layout);
    s.push_str(&format!(
        "    public {} {}{}\n    {{\n",
        type_keyword, msg.name, generics
    ));

    for field in &msg.fields {
        if let Some(docs) = &field.docs {
            s.push_str(&format!("        /// <summary>{}</summary>\n", docs));
        }
        let field_name = utils::to_pascal_case(&escape_csharp(&field.name));
        let field_type = rust_to_csharp_type(&field.type_ref);
        let nullable = if field.optional && !is_value_type(&field.type_ref) {
            "?"
        } else {
            ""
        };
        s.push_str(&format!(
            "        public {}{} {} {{ get; set; }}\n",
            field_type, nullable, field_name
        ));
    }

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

fn generate_codec(manifest: &SchemaManifest) -> Result<GeneratedFile> {
    let mut content = csharp_header(manifest);

    content.push_str(&format!(
        r#"
namespace Motto.SDK
{{
    /// <summary>Protocol version byte embedded in all packets</summary>
    public static class Protocol
    {{
        public const byte VersionByte = 0x{:02X};
        public const string Fingerprint = "{}";
    }}

    /// <summary>Zero-copy packet reader using Span</summary>
    public ref struct PacketReader
    {{
        private ReadOnlySpan<byte> _data;
        private int _offset;

        public PacketReader(ReadOnlySpan<byte> data)
        {{
            _data = data;
            _offset = 0;
        }}

        public bool ValidateVersion()
        {{
            return _data.Length > 0 && _data[0] == Protocol.VersionByte;
        }}

        public void SkipVersionByte()
        {{
            _offset = 1;
        }}

        public byte ReadU8()
        {{
            return _data[_offset++];
        }}

        public ushort ReadU16()
        {{
            var value = BitConverter.ToUInt16(_data.Slice(_offset, 2));
            _offset += 2;
            return value;
        }}

        public uint ReadU32()
        {{
            var value = BitConverter.ToUInt32(_data.Slice(_offset, 4));
            _offset += 4;
            return value;
        }}

        public ulong ReadU64()
        {{
            var value = BitConverter.ToUInt64(_data.Slice(_offset, 8));
            _offset += 8;
            return value;
        }}

        public float ReadF32()
        {{
            var value = BitConverter.ToSingle(_data.Slice(_offset, 4));
            _offset += 4;
            return value;
        }}

        public double ReadF64()
        {{
            var value = BitConverter.ToDouble(_data.Slice(_offset, 8));
            _offset += 8;
            return value;
        }}

        public bool ReadBool()
        {{
            return ReadU8() != 0;
        }}

        public string ReadString()
        {{
            var length = (int)ReadU32();
            var str = Encoding.UTF8.GetString(_data.Slice(_offset, length));
            _offset += length;
            return str;
        }}

        public int Remaining => _data.Length - _offset;
    }}

    /// <summary>Packet builder for encoding</summary>
    public class PacketBuilder
    {{
        private byte[] _buffer;
        private int _offset;

        public PacketBuilder(int initialCapacity = 256)
        {{
            _buffer = new byte[initialCapacity];
            // Write version byte header
            WriteU8(Protocol.VersionByte);
        }}

        private void EnsureCapacity(int need)
        {{
            if (_offset + need > _buffer.Length)
            {{
                var newSize = Math.Max(_buffer.Length * 2, _offset + need);
                Array.Resize(ref _buffer, newSize);
            }}
        }}

        public void WriteU8(byte value)
        {{
            EnsureCapacity(1);
            _buffer[_offset++] = value;
        }}

        public void WriteU16(ushort value)
        {{
            EnsureCapacity(2);
            BitConverter.TryWriteBytes(_buffer.AsSpan(_offset), value);
            _offset += 2;
        }}

        public void WriteU32(uint value)
        {{
            EnsureCapacity(4);
            BitConverter.TryWriteBytes(_buffer.AsSpan(_offset), value);
            _offset += 4;
        }}

        public void WriteU64(ulong value)
        {{
            EnsureCapacity(8);
            BitConverter.TryWriteBytes(_buffer.AsSpan(_offset), value);
            _offset += 8;
        }}

        public void WriteF32(float value)
        {{
            EnsureCapacity(4);
            BitConverter.TryWriteBytes(_buffer.AsSpan(_offset), value);
            _offset += 4;
        }}

        public void WriteF64(double value)
        {{
            EnsureCapacity(8);
            BitConverter.TryWriteBytes(_buffer.AsSpan(_offset), value);
            _offset += 8;
        }}

        public void WriteBool(bool value)
        {{
            WriteU8((byte)(value ? 1 : 0));
        }}

        public void WriteString(string value)
        {{
            var bytes = Encoding.UTF8.GetBytes(value);
            WriteU32((uint)bytes.Length);
            EnsureCapacity(bytes.Length);
            bytes.CopyTo(_buffer.AsSpan(_offset));
            _offset += bytes.Length;
        }}

        public byte[] Build()
        {{
            var result = new byte[_offset];
            Array.Copy(_buffer, result, _offset);
            return result;
        }}
    }}
"#,
        manifest.meta.version_byte,
        &manifest.meta.fingerprint[..16]
    ));

    // Generate encode/decode for each message
    for msg in &manifest.messages {
        content.push_str(&generate_message_codec(msg));
    }

    content.push_str("}\n");

    Ok(GeneratedFile {
        path: PathBuf::from("Runtime/Codec.cs"),
        content,
    })
}

fn generate_message_codec(msg: &MessageDef) -> String {
    let name = &msg.name;
    let mut s = String::new();

    s.push_str(&format!(
        r#"
    /// <summary>Codec extensions for {}</summary>
    public static class {}Codec
    {{
        public static byte[] Encode(this {} msg)
        {{
            var builder = new PacketBuilder();
"#,
        name, name, name
    ));

    for field in &msg.fields {
        let field_name = utils::to_pascal_case(&escape_csharp(&field.name));
        if field.optional {
            s.push_str(&format!(
                r#"            if (msg.{} != null)
            {{
                builder.WriteU8(1);
                {};
            }}
            else
            {{
                builder.WriteU8(0);
            }}
"#,
                field_name,
                encode_csharp_field(&format!("msg.{}", field_name), &field.type_ref)
            ));
        } else {
            s.push_str(&format!(
                "            {};\n",
                encode_csharp_field(&format!("msg.{}", field_name), &field.type_ref)
            ));
        }
    }

    s.push_str("            return builder.Build();\n        }\n\n");

    // Decode
    s.push_str(&format!(
        r#"        public static {} Decode(ReadOnlySpan<byte> data)
        {{
            var reader = new PacketReader(data);
            if (!reader.ValidateVersion()) return default;
            reader.SkipVersionByte();

            return new {}
            {{
"#,
        name, name
    ));

    for field in &msg.fields {
        let field_name = utils::to_pascal_case(&escape_csharp(&field.name));
        if field.optional {
            s.push_str(&format!(
                "                {} = reader.ReadU8() != 0 ? {} : default,\n",
                field_name,
                decode_csharp_field(&field.type_ref)
            ));
        } else {
            s.push_str(&format!(
                "                {} = {},\n",
                field_name,
                decode_csharp_field(&field.type_ref)
            ));
        }
    }

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

    s
}

fn encode_csharp_field(accessor: &str, type_ref: &str) -> String {
    match type_ref {
        "u8" => format!("builder.WriteU8({})", accessor),
        "u16" => format!("builder.WriteU16({})", accessor),
        "u32" => format!("builder.WriteU32({})", accessor),
        "u64" => format!("builder.WriteU64({})", accessor),
        "i8" => format!("builder.WriteU8((byte){})", accessor),
        "i16" => format!("builder.WriteU16((ushort){})", accessor),
        "i32" => format!("builder.WriteU32((uint){})", accessor),
        "i64" => format!("builder.WriteU64((ulong){})", accessor),
        "f32" => format!("builder.WriteF32({})", accessor),
        "f64" => format!("builder.WriteF64({})", accessor),
        "bool" => format!("builder.WriteBool({})", accessor),
        "String" => format!("builder.WriteString({})", accessor),
        _ => format!("/* TODO: encode {} */", type_ref),
    }
}

fn decode_csharp_field(type_ref: &str) -> String {
    match type_ref {
        "u8" => "reader.ReadU8()".to_string(),
        "u16" => "reader.ReadU16()".to_string(),
        "u32" => "reader.ReadU32()".to_string(),
        "u64" => "reader.ReadU64()".to_string(),
        "i8" => "(sbyte)reader.ReadU8()".to_string(),
        "i16" => "(short)reader.ReadU16()".to_string(),
        "i32" => "(int)reader.ReadU32()".to_string(),
        "i64" => "(long)reader.ReadU64()".to_string(),
        "f32" => "reader.ReadF32()".to_string(),
        "f64" => "reader.ReadF64()".to_string(),
        "bool" => "reader.ReadBool()".to_string(),
        "String" => "reader.ReadString()".to_string(),
        _ => format!("default /* TODO: decode {} */", type_ref),
    }
}

fn generate_runtime(
    manifest: &SchemaManifest,
    transport_mode: TransportMode,
) -> Result<GeneratedFile> {
    let ffi_transport = if transport_mode == TransportMode::Ffi {
        r#"

    /// <summary>FFI-backed transport using the motto native core via P/Invoke</summary>
    public class MottoFfiTransport : IMottoTransport
    {{
        [DllImport("motto_transport")]
        private static extern IntPtr motto_transport_new(string url);
        [DllImport("motto_transport")]
        private static extern void motto_transport_free(IntPtr handle);
        [DllImport("motto_transport")]
        private static extern int motto_transport_connect(IntPtr handle);
        [DllImport("motto_transport")]
        private static extern void motto_transport_close(IntPtr handle);
        [DllImport("motto_transport")]
        private static extern int motto_transport_send(IntPtr handle, byte[] data, int dataLen);
        [DllImport("motto_transport")]
        private static extern int motto_transport_recv(IntPtr handle, out IntPtr outData, out int outLen);
        [DllImport("motto_transport")]
        private static extern void motto_transport_recv_free(IntPtr data, int len);
        [DllImport("motto_transport")]
        private static extern byte motto_transport_state(IntPtr handle);
        [DllImport("motto_transport")]
        private static extern IntPtr motto_transport_last_error(IntPtr handle);

        private IntPtr _handle = IntPtr.Zero;
        private ConnectionState _state = ConnectionState.Disconnected;
        public ConnectionState State => _state;
        public event System.Action<byte[]> OnReceived;

        private readonly string _url;
        private readonly RetryConfig _retryConfig;

        public MottoFfiTransport(string url, RetryConfig retryConfig = null)
        {{
            _url = url;
            _retryConfig = retryConfig ?? new RetryConfig();
        }}

        public async Task ConnectAsync()
        {{
            _state = ConnectionState.Connecting;
            _handle = motto_transport_new(_url);
            if (_handle == IntPtr.Zero)
                throw new System.Exception("Failed to create FFI transport handle");
            int rc = motto_transport_connect(_handle);
            if (rc != 0)
            {{
                _state = ConnectionState.Error;
                throw new System.Exception(GetLastError());
            }}
            _state = ConnectionState.Connected;
        }}

        public async Task DisconnectAsync()
        {{
            if (_handle != IntPtr.Zero)
            {{
                motto_transport_close(_handle);
                motto_transport_free(_handle);
                _handle = IntPtr.Zero;
            }}
            _state = ConnectionState.Disconnected;
        }}

        public async Task SendAsync(byte[] data)
        {{
            if (_handle == IntPtr.Zero)
                throw new System.Exception("Not connected");
            int rc = motto_transport_send(_handle, data, data.Length);
            if (rc != 0)
                throw new System.Exception(GetLastError());
        }}

        private string GetLastError()
        {{
            IntPtr ptr = motto_transport_last_error(_handle);
            return ptr == IntPtr.Zero ? "Unknown error" : System.Runtime.InteropServices.Marshal.PtrToStringAnsi(ptr);
        }}

        ~MottoFfiTransport()
        {{
            if (_handle != IntPtr.Zero)
            {{
                motto_transport_close(_handle);
                motto_transport_free(_handle);
                _handle = IntPtr.Zero;
            }}
        }}
    }}
"#
    } else {
        ""
    };

    let content = format!(
        r#"{}
using System;
using System.Threading.Tasks;

namespace Motto.SDK
{{
    /// <summary>Connection state</summary>
    public enum ConnectionState
    {{
        Disconnected,
        Connecting,
        Connected,
        Reconnecting,
        Error
    }}

    /// <summary>Retry configuration</summary>
    [System.Serializable]
    public class RetryConfig
    {{
        public int MaxRetries = 5;
        public int InitialDelayMs = 100;
        public int MaxDelayMs = 30000;
        public float BackoffMultiplier = 2.0f;
    }}

    /// <summary>Calculate retry delay with exponential backoff</summary>
    public static class RetryHelper
    {{
        public static int CalculateDelay(int attempt, RetryConfig config)
        {{
            var delay = config.InitialDelayMs * Math.Pow(config.BackoffMultiplier, attempt);
            return Math.Min((int)delay, config.MaxDelayMs);
        }}
    }}

    /// <summary>Transport interface</summary>
    public interface IMottoTransport
    {{
        ConnectionState State {{ get; }}
        Task ConnectAsync();
        Task DisconnectAsync();
        Task SendAsync(byte[] data);
        event System.Action<byte[]> OnReceived;
    }}

    /// <summary>WebSocket transport for Unity</summary>
    public class MottoWebSocketTransport : IMottoTransport
    {{
        private readonly string _url;
        private readonly RetryConfig _retryConfig;
        private int _retryAttempt;

        public ConnectionState State {{ get; private set; }} = ConnectionState.Disconnected;
        public event System.Action<byte[]> OnReceived;

        public MottoWebSocketTransport(string url, RetryConfig retryConfig = null)
        {{
            _url = url;
            _retryConfig = retryConfig ?? new RetryConfig();
        }}

        public async Task ConnectAsync()
        {{
            State = ConnectionState.Connecting;

            try
            {{
                // TODO: Implement actual WebSocket connection
                // For Unity, consider using NativeWebSocket or UnityWebSocket
                await Task.Delay(100); // Placeholder
                State = ConnectionState.Connected;
                _retryAttempt = 0;
            }}
            catch (System.Exception)
            {{
                State = ConnectionState.Error;
                throw;
            }}
        }}

        public async Task ReconnectAsync()
        {{
            if (_retryAttempt >= _retryConfig.MaxRetries)
            {{
                throw new System.Exception("Max retry attempts exceeded");
            }}

            State = ConnectionState.Reconnecting;
            var delay = RetryHelper.CalculateDelay(_retryAttempt, _retryConfig);
            _retryAttempt++;

            await Task.Delay(delay);
            await ConnectAsync();
        }}

        public async Task DisconnectAsync()
        {{
            // TODO: Close WebSocket
            await Task.CompletedTask;
            State = ConnectionState.Disconnected;
        }}

        public async Task SendAsync(byte[] data)
        {{
            if (State != ConnectionState.Connected)
            {{
                throw new System.InvalidOperationException("Not connected");
            }}

            // TODO: Send via WebSocket
            await Task.CompletedTask;
        }}
    }}
{}}}
"#,
        csharp_header(manifest),
        ffi_transport
    );

    Ok(GeneratedFile {
        path: PathBuf::from("Runtime/Runtime.cs"),
        content,
    })
}

fn generate_native_bridge(manifest: &SchemaManifest) -> Result<GeneratedFile> {
    let content = format!(
        r#"{}
using System.Runtime.InteropServices;

namespace Motto.SDK
{{
    /// <summary>Native bridge for DllImport or WebAssembly</summary>
    public static unsafe class NativeBridge
    {{
        private const string DllName = "motto_native";

#if UNITY_WEBGL && !UNITY_EDITOR
        [DllImport("__Internal")]
        private static extern int motto_wasm_init(byte* wasmBytes, int wasmLength);

        [DllImport("__Internal")]
        private static extern int motto_wasm_encode(byte* input, int inputLength, byte* output, int outputCapacity);

        [DllImport("__Internal")]
        private static extern int motto_wasm_decode(byte* input, int inputLength, byte* output, int outputCapacity);
#else
        [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
        private static extern int motto_native_init();

        [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
        private static extern int motto_native_encode(byte* input, int inputLength, byte* output, int outputCapacity);

        [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
        private static extern int motto_native_decode(byte* input, int inputLength, byte* output, int outputCapacity);

        [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
        private static extern int motto_native_compress(byte* input, int inputLength, byte* output, int outputCapacity, int level);

        [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
        private static extern int motto_native_decompress(byte* input, int inputLength, byte* output, int outputCapacity);
#endif

        /// <summary>Initialize native library</summary>
        public static bool Initialize()
        {{
#if UNITY_WEBGL && !UNITY_EDITOR
            // WASM initialization handled by JavaScript
            return true;
#else
            return motto_native_init() == 0;
#endif
        }}

        /// <summary>Encode using native implementation (zero-copy)</summary>
        public static int Encode(ReadOnlySpan<byte> input, Span<byte> output)
        {{
            fixed (byte* inputPtr = input)
            fixed (byte* outputPtr = output)
            {{
#if UNITY_WEBGL && !UNITY_EDITOR
                return motto_wasm_encode(inputPtr, input.Length, outputPtr, output.Length);
#else
                return motto_native_encode(inputPtr, input.Length, outputPtr, output.Length);
#endif
            }}
        }}

        /// <summary>Decode using native implementation (zero-copy)</summary>
        public static int Decode(ReadOnlySpan<byte> input, Span<byte> output)
        {{
            fixed (byte* inputPtr = input)
            fixed (byte* outputPtr = output)
            {{
#if UNITY_WEBGL && !UNITY_EDITOR
                return motto_wasm_decode(inputPtr, input.Length, outputPtr, output.Length);
#else
                return motto_native_decode(inputPtr, input.Length, outputPtr, output.Length);
#endif
            }}
        }}

#if !UNITY_WEBGL || UNITY_EDITOR
        /// <summary>Compress with Zstd (native only)</summary>
        public static int Compress(ReadOnlySpan<byte> input, Span<byte> output, int level = 3)
        {{
            fixed (byte* inputPtr = input)
            fixed (byte* outputPtr = output)
            {{
                return motto_native_compress(inputPtr, input.Length, outputPtr, output.Length, level);
            }}
        }}

        /// <summary>Decompress with Zstd (native only)</summary>
        public static int Decompress(ReadOnlySpan<byte> input, Span<byte> output)
        {{
            fixed (byte* inputPtr = input)
            fixed (byte* outputPtr = output)
            {{
                return motto_native_decompress(inputPtr, input.Length, outputPtr, output.Length);
            }}
        }}
#endif
    }}
}}
"#,
        csharp_header(manifest)
    );

    Ok(GeneratedFile {
        path: PathBuf::from("Runtime/NativeBridge.cs"),
        content,
    })
}

fn generate_asmdef(_manifest: &SchemaManifest) -> Result<GeneratedFile> {
    let content = r#"{
    "name": "Motto.SDK",
    "rootNamespace": "Motto.SDK",
    "references": [],
    "includePlatforms": [],
    "excludePlatforms": [],
    "allowUnsafeCode": true,
    "overrideReferences": false,
    "precompiledReferences": [],
    "autoReferenced": true,
    "defineConstraints": [],
    "versionDefines": [],
    "noEngineReferences": false
}
"#
    .to_string();

    Ok(GeneratedFile {
        path: PathBuf::from("Motto.SDK.asmdef"),
        content,
    })
}

fn generate_dotnet_sdk_project() -> Result<GeneratedFile> {
    let content = r#"<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <LangVersion>latest</LangVersion>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
    <EnableDefaultCompileItems>false</EnableDefaultCompileItems>
  </PropertyGroup>

  <ItemGroup>
    <Compile Include="Runtime/Types.cs" />
    <Compile Include="Runtime/Codec.cs" />
    <Compile Include="Runtime/NativeBridge.cs" />
    <Compile Include="Runtime/Runtime.cs" />
  </ItemGroup>
</Project>
"#
    .to_string();

    Ok(GeneratedFile {
        path: PathBuf::from("Motto.SDK.csproj"),
        content,
    })
}

fn generate_dotnet_test_project() -> Result<GeneratedFile> {
    let content = r#"<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <IsPackable>false</IsPackable>
    <EnableDefaultCompileItems>false</EnableDefaultCompileItems>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
    <PackageReference Include="NUnit" Version="3.14.0" />
    <PackageReference Include="NUnit3TestAdapter" Version="4.6.0" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="Motto.SDK.csproj" />
    <Compile Include="Runtime/Tests/**/*.cs" />
  </ItemGroup>
</Project>
"#
    .to_string();

    Ok(GeneratedFile {
        path: PathBuf::from("Motto.SDK.Tests.csproj"),
        content,
    })
}

fn generate_tests(manifest: &SchemaManifest) -> Result<GeneratedFile> {
    let content = format!(
        r#"using NUnit.Framework;

namespace Motto.SDK.Tests
{{
    public class CodecTests
    {{
        [Test]
        public void ProtocolVersionMatchesManifest()
        {{
            Assert.AreEqual(0x{:02X}, Protocol.VersionByte);
        }}

        [Test]
        public void PacketBuilderWritesHeader()
        {{
            var builder = new PacketBuilder();
            var data = builder.Build();

            Assert.Greater(data.Length, 0);
            Assert.AreEqual(Protocol.VersionByte, data[0]);
        }}
    }}
}}
"#,
        manifest.meta.version_byte
    );

    Ok(GeneratedFile {
        path: PathBuf::from("Runtime/Tests/CodecTests.cs"),
        content,
    })
}

fn rust_to_csharp_type(rust_type: &str) -> String {
    if let Some(inner_start) = rust_type.find('<') {
        let name = &rust_type[..inner_start];
        let inner = &rust_type[inner_start + 1..rust_type.len() - 1];

        match name {
            "Vec" => format!("{}[]", rust_to_csharp_type(inner)),
            "Option" => {
                let inner_type = rust_to_csharp_type(inner);
                if is_value_type(inner) {
                    format!("{}?", inner_type)
                } else {
                    inner_type
                }
            }
            "HashMap" | "BTreeMap" => {
                let parts: Vec<&str> = inner.split(',').map(|s| s.trim()).collect();
                if parts.len() == 2 {
                    format!(
                        "System.Collections.Generic.Dictionary<{}, {}>",
                        rust_to_csharp_type(parts[0]),
                        rust_to_csharp_type(parts[1])
                    )
                } else {
                    "System.Collections.Generic.Dictionary<object, object>".to_string()
                }
            }
            "HashSet" | "BTreeSet" => {
                format!(
                    "System.Collections.Generic.HashSet<{}>",
                    rust_to_csharp_type(inner)
                )
            }
            _ => rust_type.to_string(),
        }
    } else {
        match rust_type {
            "u8" => "byte".to_string(),
            "u16" => "ushort".to_string(),
            "u32" => "uint".to_string(),
            "u64" => "ulong".to_string(),
            "i8" => "sbyte".to_string(),
            "i16" => "short".to_string(),
            "i32" => "int".to_string(),
            "i64" => "long".to_string(),
            "f32" => "float".to_string(),
            "f64" => "double".to_string(),
            "bool" => "bool".to_string(),
            "String" | "str" => "string".to_string(),
            "char" => "char".to_string(),
            "()" => "void".to_string(),
            _ => rust_type.to_string(),
        }
    }
}

fn is_value_type(rust_type: &str) -> bool {
    matches!(
        rust_type,
        "u8" | "u16"
            | "u32"
            | "u64"
            | "i8"
            | "i16"
            | "i32"
            | "i64"
            | "f32"
            | "f64"
            | "bool"
            | "char"
    )
}

fn escape_csharp(name: &str) -> String {
    if CSHARP_RESERVED.contains(&name) {
        format!("@{}", name)
    } else {
        name.to_string()
    }
}