wyre 0.2.16

wyre serialization and deserialization library
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
/*
# **Project Requirements: WYRE Framework**

## **1. Project Overview**

The **WYRE Framework** is designed to generate a fully functional application backend and API, as well as necessary frontend communication, using a user-friendly scripting language called **WYRE Script**. The goal is to allow users to define the complete backend architecture, including database schemas, validation, APIs, and business logic, using a simple and concise language. WYRE Framework will generate both the backend (written in Rust) and establish an API connection for the frontend (using WebSocket for communication). The framework will also allow inline business logic scripting in **JavaScript** or **Dart** for flexibility, especially for operations like validation, authorization, and custom logic.

---

## **2. Core Functionalities**

### **2.1 WYRE Script Definition**
The WYRE Script will serve as the user interface for defining backend application structure. The language will allow users to define:

- **Data Models (Database Schema)**: Ability to define database entities (tables) and their relationships (e.g., one-to-one, one-to-many, many-to-many).
- **CRUD Operations**: Automatic generation of Create, Read, Update, and Delete (CRUD) functions for all models defined in the script.
- **API Endpoints**: Define API routes corresponding to CRUD operations or any custom functions/services.
- **Fine-Grained Access Control**: Control access at both the **column level** and **item level**, ensuring granular permissions on individual fields and records.
- **Custom Business Logic**: Inline support for embedding JavaScript or Dart business logic that is triggered during various lifecycle events (before-save, after-create, etc.).
- **Validations**: Users can specify model-level and field-level validation rules.
- **Authentication and Authorization**: Define authentication mechanisms (e.g., JWT) and authorization rules (e.g., role-based access control).
- **Services and Hooks**: Ability to define custom services (e.g., email sending, notifications) and lifecycle hooks (e.g., on data changes, before/after validation, etc.).

---

### **2.2 Backend Code Generation**
The WYRE Script will be compiled into a full Rust backend. Key features of the backend:

#### **2.2.1 Database Model Generation**
- **Schema Generation**: Automatic generation of SQL (or other database) schemas for data models. The system will select an optimal database solution (e.g., SLED, SQLite) to match the application’s requirements.
- **Column-Level and Item-Level Access Control**: Control and enforce permissions on specific fields and records in the database.
- **Relationships**: Support for various relationships between models (e.g., foreign keys, joins, one-to-one, one-to-many, many-to-many).
- **Database Queries**: CRUD operations will be generated automatically, ensuring efficient querying and data manipulation.

#### **2.2.2 API Generation**
- **REST or WebSocket API**: For every data model, corresponding CRUD routes will be generated. A WebSocket connection will be used to enable a real-time API connection between the client and server.
- **RPC Mechanism**: API calls can be made like Remote Procedure Calls (RPC) from the frontend, allowing seamless communication.
- **Real-Time Data**: Using WebSockets, real-time data updates (push notifications) should be supported for certain API calls.

#### **2.2.3 Custom Business Logic Layer**
- **JavaScript or Dart Support**: The framework should support the inclusion of business logic using JavaScript or Dart, depending on what is deemed optimal for the scenario.
- **Inline Scripting**: WYRE Script should allow users to write JavaScript or Dart code inline to handle custom business logic (e.g., validation, transformation, hooks). The generated Rust backend will then embed this logic using serialization/deserialization through **MessagePack**.
- **Lifecycle Hooks**: The user should be able to define logic for events like:
    - Before saving data
    - After updating a record
    - Before deleting data
    - After creating a new entity
- **MessagePack Serialization**: All data communication between JavaScript/Dart and Rust should use MessagePack for efficient binary serialization and deserialization.

#### **2.2.4 Validation and Authorization**
- **Field-Level Validation**: Users can define validation rules for each model field (e.g., length constraints, format validation).
- **Model-Level Validation**: Define business rules that span across multiple fields (e.g., ensure one field is dependent on another).
- **Role-Based Authorization**: Define access rules based on user roles. Granular access can be applied at both the column and item level.
- **Custom Validation Logic**: Custom validation logic can be embedded using JavaScript or Dart and applied before data is persisted to the database.

#### **2.2.5 WebSocket-Based Communication Layer**
- **Real-Time WebSocket API**: Instead of traditional HTTP requests, a WebSocket layer should be implemented to allow real-time communication between the client and server.
- **Session Management**: Handle authentication (e.g., JWT token management) over WebSocket, allowing for persistent sessions and secure communication.
- **Stateful RPC Communication**: Frontend clients should be able to invoke backend functions through RPC-like mechanisms over WebSocket, ensuring smooth and interactive real-time updates.

---

### **2.3 Frontend Code Generation**
The WYRE framework will also generate frontend code to facilitate communication with the generated backend:

#### **2.3.1 API Client Generation**
- **RPC Client**: Generate a frontend client (JavaScript/TypeScript) that allows the frontend to call the backend’s API as if it were a local function using the WebSocket connection.
- **Data Serialization/Deserialization**: Ensure smooth serialization and deserialization of data between the frontend and backend, using MessagePack.
- **Authentication Management**: The generated frontend code should include functionality to manage JWT-based authentication (e.g., token storage, renewal).
- **Real-Time Updates**: The WebSocket-based communication should allow real-time updates from the backend to be pushed to the frontend (e.g., live data sync).

---

### **2.4 Scripting and Customization Features**
The framework should provide customizable scripting capabilities for end users:

#### **2.4.1 JavaScript/Dart Integration**
- **Business Logic Integration**: Allow the user to write custom business logic (e.g., custom validation, field transformations, data authorization) directly inside WYRE scripts. This logic will be embedded into the generated Rust backend using JavaScript or Dart.
- **Selection of JavaScript or Dart**: The system should allow the developer to choose between JavaScript or Dart for embedding business logic. The developer should evaluate which is more optimal for the use case.
- **Seamless Integration with Rust**: The business logic code written in JavaScript or Dart should seamlessly integrate with Rust, utilizing serialization (MessagePack) for efficient data transfer between Rust and JavaScript/Dart code.

#### **2.4.2 Validation Hooks**
- **Custom Validation Logic**: Users should be able to define custom validation logic in JavaScript or Dart for fields and models.
- **Field-Level Hooks**: Ability to add hooks that trigger custom logic before data is validated, saved, or retrieved.
- **Model-Level Hooks**: Add lifecycle hooks that trigger custom logic before or after model-level operations (e.g., before saving, after creating).

---

## **3. Non-Functional Requirements**

### **3.1 Performance**
- **Efficient Data Access**: The database should be chosen based on performance requirements (e.g., SLED or SQLite). The framework should optimize CRUD operations for minimal latency.
- **Real-Time Capabilities**: Use WebSocket for all API communications to enable real-time, bidirectional communication between client and server.

### **3.2 Security**
- **JWT Authentication**: Use JSON Web Tokens (JWT) for stateless user authentication and authorization.
- **Granular Access Control**: Implement fine-grained access control mechanisms at the column and row level.
- **Secure WebSocket Communication**: Ensure WebSocket communication is encrypted (wss://) for secure real-time data transfer.

### **3.3 Extensibility**
- **Pluggable Business Logic**: Allow easy extension of business logic in JavaScript or Dart, with future support for additional languages if necessary.
- **Customizable API**: The framework should be flexible enough to allow developers to customize or extend the generated APIs.

### **3.4 Maintainability**
- **Code Modularity**: The generated code should be well-structured and modular, making it easy for developers to maintain and extend.
- **Well-Defined Documentation**: Ensure that the generated backend and frontend code are well-documented.

---

## **4. Developer Responsibilities**

### **4.1 Rust Backend**
- **Database Integration**: Integrate a lightweight, performant database such as SLED or SQLite. Ensure it supports CRUD operations, relationships, and granular access control.
- **API Generation**: Develop logic to automatically generate REST/WebSocket APIs based on the WYRE script definitions.
- **MessagePack Integration**: Implement serialization/deserialization between Rust and JavaScript/Dart using MessagePack for efficient data exchange.
- **WebSocket Communication**: Build a WebSocket-based communication layer to allow real-time interactions between the client and server.

### **4.2 JavaScript/Dart Integration**
- **Inline Script Embedding**: Embed JavaScript/Dart code into the Rust backend, using MessagePack for communication between the two languages.
- **Lifecycle Hooks**: Implement support for lifecycle hooks (before-create, after-save, etc.) that trigger custom JavaScript/Dart logic.

### **4.3 Frontend Integration**
- **Frontend API Client**: Generate a WebSocket-based RPC client for the frontend to interact with the backend.
- **Real-Time Data Handling**: Ensure the frontend is capable of handling real-time updates from the backend
*/

use pest::Parser;
use pest_derive::Parser;
use std::collections::HashMap;
use std::fs::{self, File};
use std::io::Write;
use std::path::Path;

#[derive(Parser)]
#[grammar = "wyre_script.pest"]
struct WyreScript;


const SAMPLE_WYRE_SCRIPT: &str = r#"
// Sample WYRE script
// Custom enums
enum UserRole {
    ADMIN,
    USER,
    GUEST
}

enum ListingStatus {
    ACTIVE,
    INACTIVE,
    SOLD
}

// Models with optional fields and default values
model User {
    id: uuid
    name: string
    email: string & unique
    password: string
    role: UserRole = UserRole.USER
    bio: string | null
    created_at: timestamp = now()
    updated_at: timestamp | null
}

model Listing {
    id: uuid
    title: string
    description: string | null
    price: decimal
    status: ListingStatus = ListingStatus.ACTIVE
    created_at: timestamp = now()
    updated_at: timestamp | null
    created_by: one<User>
    watching: many<User>
    tags: many<Tag>
    views: int = 0
}

model Tag {
    id: uuid
    name: string & unique
    description: string | null
    parent: one<Tag> | null
}

// Custom function with optional and default parameters
function generateSlug(title: string, separator: string = "-", maxLength: int? = 100): string {
    let slug = title.toLowerCase().replace(/\s+/g, separator);
    return maxLength ? slug.slice(0, maxLength) : slug;
}:ts

// Services with optional and default parameters
service UserService {
    #[allow(admin)]
    create_user(user: User): User

    #[allow(admin, owner)]
    get_user(id: uuid): User

    #[allow(admin, owner)]
    update_user(id: uuid, user: User): User

    #[allow(admin)]
    delete_user(id: uuid): boolean

    #[allow(all)]
    search_users(query: string = "", role: UserRole = UserRole.USER, page: int = 1, limit: int = 20): many<User>
}

service AuthService {
    #[allow(all)]
    login(email: string, password: string): string

    #[allow(authenticated)]
    logout(token: string): boolean

    #[allow(all)]
    register(name: string, email: string, password: string, role: UserRole = UserRole.USER): User
}

service ListingService {
    #[allow(authenticated)]
    create_listing(listing: Listing): Listing

    #[allow(owner, admin)]
    update_listing(id: uuid, listing: Listing): Listing

    #[allow(owner, admin)]
    delete_listing(id: uuid): boolean

    #[allow(all)]
    get_listing(id: uuid): Listing

    #[allow(all)]
    search_listings(query: string = "", category: string = "", status: ListingStatus = ListingStatus.ACTIVE, page: int = 1, limit: int = 20): many<Listing>
}

service TagService {
    #[allow(admin)]
    create_tag(tag: Tag): Tag

    #[allow(all)]
    get_tag(id: uuid): Tag

    #[allow(admin)]
    update_tag(id: uuid, tag: Tag): Tag

    #[allow(admin)]
    delete_tag(id: uuid): boolean

    #[allow(all)]
    search_tags(query: string | null, page: int = 1, limit: int = 20): many<Tag>
}

// Hooks with explicit types
hook User.before_create(user: User) {
    user.password = bcrypt.hash(user.password, 10);
    user.email = user.email.toLowerCase();
}:ts

hook User.before_update(user: User) {
    if (user.password) {
        user.password = bcrypt.hash(user.password, 10);
    }
    user.updated_at = new Date();
}:ts

hook Listing.before_create(listing: Listing) {
    listing.slug = generateSlug(listing.title);
    listing.views = 0;
}:ts

hook Listing.after_update(listing: Listing) {
    if (listing.status === ListingStatus.SOLD) {
        for (const watcher of listing.watching) {
            sendNotification(watcher.id, `The listing "${listing.title}" has been sold.`);
        }
    }
}:ts

// Realtime with optional parameter and explicit return type
realtime listen_new_listings(category: string?): Stream<Listing> {
    let stream = Listing.stream().filter(listing => listing.status === ListingStatus.ACTIVE);
    if (category) {
        stream = stream.filter(listing => listing.tags.some(tag => tag.name === category));
    }
    return stream.map(listing => ({
        id: listing.id,
        title: listing.title,
        price: listing.price,
        slug: listing.slug,
        views: listing.views
    }));
}:js

realtime listen_user_activity(userId: uuid): Stream<User> {
    return User.stream()
        .filter(user => user.id === userId)
        .map(user => ({
            id: user.id,
            name: user.name,
            email: user.email,
            role: user.role,
            lastActive: new Date()
        }));
}:js

"#;


#[derive(Debug, Clone)]
struct Enum {
    name: String,
    variants: Vec<String>,
}

#[derive(Debug, Clone)]
struct Model {
    name: String,
    fields: Vec<Field>,
}

#[derive(Debug, Clone)]
struct Field {
    name: String,
    field_type: String,
    is_optional: bool,
    default_value: Option<String>,
}

#[derive(Debug, Clone)]
struct Function {
    name: String,
    params: Vec<Parameter>,
    return_type: String,
    body: String,
    language: String,
}

#[derive(Debug, Clone)]
struct Parameter {
    name: String,
    param_type: String,
    is_optional: bool,
    default_value: Option<String>,
}

#[derive(Debug, Clone)]
struct Service {
    name: String,
    methods: Vec<Method>,
}

#[derive(Debug, Clone)]
struct Method {
    name: String,
    params: Vec<Parameter>,
    return_type: String,
    allowed_roles: Vec<String>,
}

#[derive(Debug, Clone)]
struct Hook {
    model: String,
    event: String,
    params: Vec<Parameter>,
    body: String,
    language: String,
}

#[derive(Debug, Clone)]
struct Realtime {
    name: String,
    params: Vec<Parameter>,
    return_type: String,
    body: String,
    language: String,
}

struct CodeGenerator {
    enums: Vec<Enum>,
    models: Vec<Model>,
    functions: Vec<Function>,
    services: Vec<Service>,
    hooks: Vec<Hook>,
    realtimes: Vec<Realtime>,
}

impl CodeGenerator {
    fn new() -> Self {
        CodeGenerator {
            enums: Vec::new(),
            models: Vec::new(),
            functions: Vec::new(),
            services: Vec::new(),
            hooks: Vec::new(),
            realtimes: Vec::new(),
        }
    }

    fn parse_wyre_script(&mut self, pairs: pest::iterators::Pairs<Rule>) {
        for pair in pairs {
            match pair.as_rule() {
                Rule::enum_definition => self.parse_enum(pair),
                Rule::model_definition => self.parse_model(pair),
                Rule::function_definition => self.parse_function(pair),
                Rule::service_definition => self.parse_service(pair),
                Rule::hook_definition => self.parse_hook(pair),
                Rule::realtime_definition => self.parse_realtime(pair),
                _ => {}
            }
        }
    }

    fn parse_enum(&mut self, pair: pest::iterators::Pair<Rule>) {
        let mut inner = pair.into_inner();
        let name = inner.next().unwrap().as_str().to_string();
        let variants = inner.map(|p| p.as_str().to_string()).collect();
        self.enums.push(Enum { name, variants });
    }

    fn parse_model(&mut self, pair: pest::iterators::Pair<Rule>) {
        let mut inner = pair.into_inner();
        let name = inner.next().unwrap().as_str().to_string();
        let fields = inner.map(|p| self.parse_field(p)).collect();
        self.models.push(Model { name, fields });
    }

    fn parse_field(&self, pair: pest::iterators::Pair<Rule>) -> Field {
        let mut inner = pair.into_inner();
        let name = inner.next().unwrap().as_str().to_string();
        let field_type = inner.next().unwrap().as_str().to_string();
        let is_optional = inner.any(|p| p.as_rule() == Rule::null_option);
        let default_value = inner.find(|p| p.as_rule() == Rule::default_value)
            .map(|p| p.into_inner().next().unwrap().as_str().to_string());
        Field { name, field_type, is_optional, default_value }
    }

    fn parse_function(&mut self, pair: pest::iterators::Pair<Rule>) {
        let mut inner = pair.into_inner();
        let name = inner.next().unwrap().as_str().to_string();
        let params = inner.next().unwrap().into_inner().map(|p| self.parse_parameter(p)).collect();
        let return_type = inner.next().unwrap().as_str().to_string();
        let body = inner.next().unwrap().as_str().to_string();
        let language = inner.next().unwrap().as_str().to_string();
        self.functions.push(Function { name, params, return_type, body, language });
    }

    fn parse_parameter(&self, pair: pest::iterators::Pair<Rule>) -> Parameter {
        let mut inner = pair.into_inner();
        let name = inner.next().unwrap().as_str().to_string();
        let param_type = inner.next().unwrap().as_str().to_string();
        let is_optional = inner.any(|p| p.as_rule() == Rule::null_option);
        let default_value = inner.find(|p| p.as_rule() == Rule::default_value)
            .map(|p| p.into_inner().next().unwrap().as_str().to_string());
        Parameter { name, param_type, is_optional, default_value }
    }

    fn parse_service(&mut self, pair: pest::iterators::Pair<Rule>) {
        let mut inner = pair.into_inner();
        let name = inner.next().unwrap().as_str().to_string();
        let methods = inner.map(|p| self.parse_method(p)).collect();
        self.services.push(Service { name, methods });
    }

    fn parse_method(&self, pair: pest::iterators::Pair<Rule>) -> Method {
        let mut inner = pair.into_inner();
        let allowed_roles = inner.next().unwrap().into_inner()
            .map(|p| p.as_str().to_string()).collect();
        let name = inner.next().unwrap().as_str().to_string();
        let params = inner.next().unwrap().into_inner().map(|p| self.parse_parameter(p)).collect();
        let return_type = inner.next().unwrap().as_str().to_string();
        Method { name, params, return_type, allowed_roles }
    }

    fn parse_hook(&mut self, pair: pest::iterators::Pair<Rule>) {
        let mut inner = pair.into_inner();
        let model = inner.next().unwrap().as_str().to_string();
        let event = inner.next().unwrap().as_str().to_string();
        let params = inner.next().unwrap().into_inner().map(|p| self.parse_parameter(p)).collect();
        let body = inner.next().unwrap().as_str().to_string();
        let language = inner.next().unwrap().as_str().to_string();
        self.hooks.push(Hook { model, event, params, body, language });
    }

    fn parse_realtime(&mut self, pair: pest::iterators::Pair<Rule>) {
        let mut inner = pair.into_inner();
        let name = inner.next().unwrap().as_str().to_string();
        let params = inner.next().unwrap().into_inner().map(|p| self.parse_parameter(p)).collect();
        let return_type = inner.next().unwrap().as_str().to_string();
        let body = inner.next().unwrap().as_str().to_string();
        let language = inner.next().unwrap().as_str().to_string();
        self.realtimes.push(Realtime { name, params, return_type, body, language });
    }

    fn generate_code(&self) -> String {
        let mut code = String::new();

        code.push_str(&self.generate_imports());
        code.push_str(&self.generate_enums());
        code.push_str(&self.generate_models());
        code.push_str(&self.generate_functions());
        code.push_str(&self.generate_services());
        code.push_str(&self.generate_hooks());
        code.push_str(&self.generate_realtimes());
        code.push_str(&self.generate_main());

        code
    }

    fn generate_imports(&self) -> String {
        r#"use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use std::collections::HashSet;
use bigdecimal::BigDecimal;
use async_trait::async_trait;
use bcrypt;
use tokio::sync::mpsc;
use tokio::time::{interval, Duration};
use warp::Filter;
use sled;
use anyhow::{Result, Error};

"#
        .to_string()
    }

    fn generate_enums(&self) -> String {
        let mut code = String::new();
        for enum_def in &self.enums {
            code.push_str(&format!(
                "#[derive(Debug, Clone, PartialEq)]\npub enum {} {{\n",
                enum_def.name
            ));
            for variant in &enum_def.variants {
                code.push_str(&format!("    {},\n", variant));
            }
            code.push_str("}\n\n");
        }
        code
    }

    fn generate_models(&self) -> String {
        let mut code = String::new();
        for model in &self.models {
            code.push_str(&format!(
                "#[derive(Debug, Clone)]\npub struct {} {{\n",
                model.name
            ));
            for field in &model.fields {
                let field_type = if field.is_optional {
                    format!("Option<{}>", field.field_type)
                } else {
                    field.field_type.clone()
                };
                code.push_str(&format!("    pub {}: {},\n", field.name, field_type));
            }
            code.push_str("}\n\n");

            // Generate CRUD operations
            code.push_str(&self.generate_crud_operations(model));
        }
        code
    }

    fn generate_crud_operations(&self, model: &Model) -> String {
        let model_name = &model.name;
        format!(
            r#"impl {0} {{
    pub async fn create(db: &sled::Db, item: &{0}) -> Result<()> {{
        let id = item.id.to_string();
        let data = bincode::serialize(item)?;
        db.insert(id.as_bytes(), data)?;
        Ok(())
    }}

    pub async fn read(db: &sled::Db, id: &Uuid) -> Result<Option<{0}>> {{
        if let Some(data) = db.get(id.to_string())? {{
            let item: {0} = bincode::deserialize(&data)?;
            Ok(Some(item))
        }} else {{
            Ok(None)
        }}
    }}

    pub async fn update(db: &sled::Db, id: &Uuid, item: &{0}) -> Result<()> {{
        let data = bincode::serialize(item)?;
        db.insert(id.to_string(), data)?;
        Ok(())
    }}

    pub async fn delete(db: &sled::Db, id: &Uuid) -> Result<()> {{
        db.remove(id.to_string())?;
        Ok(())
    }}
}}

"#,
            model_name
        )
    }

    fn generate_functions(&self) -> String {
        let mut code = String::new();
        for function in &self.functions {
            code.push_str(&format!("pub fn {}(", function.name));
            for (i, param) in function.params.iter().enumerate() {
                if i > 0 {
                    code.push_str(", ");
                }
                code.push_str(&format!("{}: {}", param.name, param.param_type));
                if param.is_optional {
                    code.push_str(" = None");
                } else if let Some(ref default) = param.default_value {
                    code.push_str(&format!(" = {}", default));
                }
            }
            code.push_str(&format!(") -> {} {{\n", function.return_type));
            code.push_str(&format!("    // Implementation in {}\n", function.language));
            code.push_str("    unimplemented!()\n");
            code.push_str("}\n\n");
        }
        code
    }

    fn generate_services(&self) -> String {
        let mut code = String::new();
        for service in &self.services {
            code.push_str(&format!("#[async_trait]\npub trait {} {{\n", service.name));
            for method in &service.methods {
                code.push_str(&format!("    #[allow({})]\n", method.allowed_roles.join(", ")));
                code.push_str(&format!("    async fn {}(", method.name));
                for (i, param) in method.params.iter().enumerate() {
                    if i > 0 {
                        code.push_str(", ");
                    }
                    code.push_str(&format!("{}: {}", param.name, param.param_type));
                }
                code.push_str(&format!(") -> Result<{}, Error>;\n", method.return_type));
            }
            code.push_str("}\n\n");

            // Generate a mock implementation
            code.push_str(&format!("pub struct Mock{};\n\n", service.name));
            code.push_str(&format!("#[async_trait]\nimpl {} for Mock{} {{\n", service.name, service.name));
            for method in &service.methods {
                code.push_str(&format!("    async fn {}(", method.name));
                for (i, param) in method.params.iter().enumerate() {
                    if i > 0 {
                        code.push_str(", ");
                    }
                    code.push_str(&format!("{}: {}", param.name, param.param_type));
                }
                code.push_str(&format!(") -> Result<{}, Error> {{\n", method.return_type));
                code.push_str("        unimplemented!()\n");
                code.push_str("    }\n\n");
            }
            code.push_str("}\n\n");
        }
        code
    }

    fn generate_hooks(&self) -> String {
        let mut code = String::new();
        for hook in &self.hooks {
            code.push_str(&format!("pub fn {}(", hook.model));
            for (i, param) in hook.params.iter().enumerate() {
                if i > 0 {
                    code.push_str(", ");
                }
                code.push_str(&format!("{}: {}", param.name, param.param_type));
            }
            code.push_str(&format!(") -> Result<(), Error> {{
                // Implementation in {}\n", hook.language));
            code.push_str("    unimplemented!()\n");
            code.push_str("}\n\n");
        }
        code
    }

    fn generate_realtimes(&self) -> String {
        let mut code = String::new();
        for realtime in &self.realtimes {
            code.push_str(&format!("pub fn {}(", realtime.name));
            for (i, param) in realtime.params.iter().enumerate() {
                if i > 0 {
                    code.push_str(", ");
                }
                code.push_str(&format!("{}: {}", param.name, param.param_type));
            }
            code.push_str(&format!(") -> Result<(), Error> {{
                // Implementation in {}\n", realtime.language));
            code.push_str("    unimplemented!()\n");
            code.push_str("}\n\n");
        }
        code
    }

    fn generate_main(&self) -> String {
        let mut code = String::new();
        code.push_str("fn main() -> Result<()> {\n");   
        code.push_str("    println!(\"Wyre backend started\");\n");
        code.push_str("    Ok(())");
        code.push_str("}\n");
        code
    }
}



fn main() -> Result<(), Box<dyn std::error::Error>> {
    let parser = WyreScript::parse(Rule::wyre_script, SAMPLE_WYRE_SCRIPT);
    match parser {
        Ok(parsed) => {
            println!("\n\x1b[1;36m┌────────────────────────────────────────────────────────────────────────────┐\x1b[0m");
            println!("\x1b[1;36m│\x1b[0m                   \x1b[1;32mParsed script\x1b[0m                                    \x1b[1;36m│\x1b[0m");
            println!("\x1b[1;36m└────────────────────────────────────────────────────────────────────────────┘\x1b[0m");
            for pair in parsed.clone() {
                print_pair(pair, 0);
            }

            let mut generator = CodeGenerator::new();
            generator.parse_wyre_script(parsed.into_iter());
            let generated_code = generator.generate_code();

            println!("\n\x1b[1;36m┌────────────────────────────────────────────────────────────────────────────┐\x1b[0m");
            println!("\x1b[1;36m│\x1b[0m                   \x1b[1;33mGenerated code\x1b[0m                                   \x1b[1;36m│\x1b[0m");
            println!("\x1b[1;36m└────────────────────────────────────────────────────────────────────────────┘\x1b[0m");
            println!("\x1b[0;37m{}\x1b[0m", generated_code);

            write_to_file("generated_code.rs", generated_code);
        }
        Err(e) => {
            println!("\n\x1b[1;36m┌────────────────────────────────────────────────────────────────────────────┐\x1b[0m");
            println!("\x1b[1;36m│\x1b[0m                   \x1b[1;31mError parsing script\x1b[0m                              \x1b[1;36m│\x1b[0m");
            println!("\x1b[1;36m└────────────────────────────────────────────────────────────────────────────┘\x1b[0m");
            println!("\x1b[1;31m{}\x1b[0m", e);
        }
    }

    Ok(())
}

fn print_pair(pair: pest::iterators::Pair<Rule>, indent: usize) {
    let indent_str = "  ".repeat(indent);
    println!("\x1b[1;34m{}├─ \x1b[1;35mRule:\x1b[0m {:?}", indent_str, pair.as_rule());
    println!("\x1b[1;34m{}│  ├─ \x1b[1;36mSpan:\x1b[0m {:?}", indent_str, pair.as_span());
    println!("\x1b[1;34m{}│  └─ \x1b[1;33mText:\x1b[0m {}", indent_str, pair.as_str());

    let inner_pairs: Vec<_> = pair.into_inner().collect();
    for (i, inner_pair) in inner_pairs.clone().into_iter().enumerate() {
        if i == inner_pairs.len() - 1 {
            println!("\x1b[1;34m{}└─\x1b[0m", indent_str);
        } else {
            println!("\x1b[1;34m{}│\x1b[0m", indent_str);
        }
        print_pair(inner_pair, indent + 1);
    }
}

fn write_to_file<T: AsRef<str>>(filename: &str, content: T) {
    ensure_dir_exists("workspace/src");
    let content = content.as_ref();
    let mut file = File::create(format!("workspace/src/{}", filename)).expect("Failed to create file");
    file.write_all(content.as_bytes()).expect("Failed to write to file");
    println!("\x1b[1;32m✔ File '{}' created successfully.\x1b[0m", filename);
}

fn ensure_dir_exists(path: &str) {
    if !Path::new(path).exists() {
        std::fs::create_dir_all(path).expect("Failed to create directory");
        println!("\x1b[1;33m➜ Directory '{}' created.\x1b[0m", path);
    }
}