gitorii 0.1.4

A human-first Git client with simplified commands, snapshots, multi-platform mirrors and built-in secret scanning
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
use serde::{Deserialize, Serialize};
use crate::config::ToriiConfig;
use crate::error::{Result, ToriiError};

/// Remote repository visibility
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Visibility {
    Public,
    Private,
    Internal, // GitLab only
}

/// Remote repository information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RemoteRepo {
    pub name: String,
    pub description: Option<String>,
    pub visibility: Visibility,
    pub default_branch: String,
    pub url: String,
    pub ssh_url: String,
    pub clone_url: String,
}

/// Platform-specific API client trait
pub trait PlatformClient {
    /// Create a new repository
    fn create_repo(&self, name: &str, description: Option<&str>, visibility: Visibility) -> Result<RemoteRepo>;
    
    /// Delete a repository
    fn delete_repo(&self, owner: &str, repo: &str) -> Result<()>;
    
    /// Update repository settings
    fn update_repo(&self, owner: &str, repo: &str, settings: RepoSettings) -> Result<RemoteRepo>;
    
    /// Get repository information
    fn get_repo(&self, owner: &str, repo: &str) -> Result<RemoteRepo>;
    
    /// List user repositories
    fn list_repos(&self) -> Result<Vec<RemoteRepo>>;
    
    /// Set repository visibility
    fn set_visibility(&self, owner: &str, repo: &str, visibility: Visibility) -> Result<()>;
    
    /// Enable/disable features
    fn configure_features(&self, owner: &str, repo: &str, features: RepoFeatures) -> Result<()>;
}

/// Repository settings for updates
#[derive(Debug, Clone, Default)]
#[allow(dead_code)]
pub struct RepoSettings {
    pub description: Option<String>,
    pub homepage: Option<String>,
    pub visibility: Option<Visibility>,
    pub default_branch: Option<String>,
    pub has_issues: Option<bool>,
    pub has_wiki: Option<bool>,
    pub has_downloads: Option<bool>,
    pub allow_squash_merge: Option<bool>,
    pub allow_merge_commit: Option<bool>,
    pub allow_rebase_merge: Option<bool>,
}

/// Repository features configuration
#[derive(Debug, Clone, Default)]
#[allow(dead_code)]
pub struct RepoFeatures {
    pub issues: Option<bool>,
    pub wiki: Option<bool>,
    pub downloads: Option<bool>,
    pub projects: Option<bool>,
    pub discussions: Option<bool>,
}

/// GitHub API client (placeholder - requires reqwest)
#[allow(dead_code)]
pub struct GitHubClient {
    token: String,
    base_url: String,
}

impl GitHubClient {
    pub fn new(token: String) -> Self {
        Self {
            token,
            base_url: "https://api.github.com".to_string(),
        }
    }
    
    fn get_token() -> Result<String> {
        // 1. Environment variable
        if let Ok(token) = std::env::var("GITHUB_TOKEN") {
            return Ok(token);
        }
        if let Ok(token) = std::env::var("GH_TOKEN") {
            return Ok(token);
        }

        // 2. Torii global config
        if let Ok(config) = ToriiConfig::load_global() {
            if let Some(token) = config.auth.github_token {
                return Ok(token);
            }
        }

        Err(ToriiError::InvalidConfig(
            "GitHub token not found. Run: torii config set auth.github_token YOUR_TOKEN".to_string()
        ))
    }
}

impl PlatformClient for GitHubClient {
    fn create_repo(&self, name: &str, description: Option<&str>, visibility: Visibility) -> Result<RemoteRepo> {
        let private = matches!(visibility, Visibility::Private | Visibility::Internal);

        let mut body = serde_json::json!({
            "name": name,
            "private": private,
            "auto_init": false,
        });
        if let Some(desc) = description {
            body["description"] = serde_json::Value::String(desc.to_string());
        }

        let client = reqwest::blocking::Client::new();
        let resp = client
            .post("https://api.github.com/user/repos")
            .header("Authorization", format!("token {}", self.token))
            .header("Accept", "application/vnd.github.v3+json")
            .header("User-Agent", "torii-cli")
            .json(&body)
            .send()
            .map_err(|e| ToriiError::InvalidConfig(format!("GitHub API error: {}", e)))?;

        if !resp.status().is_success() {
            let msg = resp.text().unwrap_or_default();
            return Err(ToriiError::InvalidConfig(format!("GitHub API error: {}", msg)));
        }

        let json: serde_json::Value = resp.json()
            .map_err(|e| ToriiError::InvalidConfig(format!("Failed to parse GitHub response: {}", e)))?;

        let repo_name = json["name"].as_str().unwrap_or(name).to_string();
        let owner = json["owner"]["login"].as_str().unwrap_or("unknown").to_string();

        Ok(RemoteRepo {
            name: repo_name.clone(),
            description: description.map(|s| s.to_string()),
            visibility,
            default_branch: "main".to_string(),
            url: format!("https://github.com/{}/{}", owner, repo_name),
            ssh_url: format!("git@github.com:{}/{}.git", owner, repo_name),
            clone_url: format!("https://github.com/{}/{}.git", owner, repo_name),
        })
    }
    
    fn delete_repo(&self, owner: &str, repo: &str) -> Result<()> {
        let output = std::process::Command::new("gh")
            .args(&["repo", "delete", &format!("{}/{}", owner, repo), "--yes"])
            .output();
        
        match output {
            Ok(out) if out.status.success() => {
                println!("✅ Repository deleted from GitHub");
                Ok(())
            }
            _ => {
                Err(ToriiError::InvalidConfig(
                    "Failed to delete repository. Install GitHub CLI (gh)".to_string()
                ))
            }
        }
    }
    
    fn update_repo(&self, owner: &str, repo: &str, settings: RepoSettings) -> Result<RemoteRepo> {
        let repo_name = format!("{}/{}", owner, repo);
        let mut args = vec!["repo", "edit", &repo_name];
        
        let mut temp_args = Vec::new();
        
        if let Some(desc) = &settings.description {
            temp_args.push("--description".to_string());
            temp_args.push(desc.clone());
        }
        
        if let Some(homepage) = &settings.homepage {
            temp_args.push("--homepage".to_string());
            temp_args.push(homepage.clone());
        }
        
        if let Some(vis) = &settings.visibility {
            match vis {
                Visibility::Public => temp_args.push("--visibility=public".to_string()),
                Visibility::Private => temp_args.push("--visibility=private".to_string()),
                Visibility::Internal => temp_args.push("--visibility=private".to_string()),
            }
        }
        
        if let Some(branch) = &settings.default_branch {
            temp_args.push("--default-branch".to_string());
            temp_args.push(branch.clone());
        }
        
        // Convert temp_args to string slices
        let arg_refs: Vec<&str> = temp_args.iter().map(|s| s.as_str()).collect();
        args.extend(arg_refs);
        
        let output = std::process::Command::new("gh")
            .args(&args)
            .output();
        
        match output {
            Ok(out) if out.status.success() => {
                println!("✅ Repository settings updated");
                self.get_repo(owner, repo)
            }
            _ => {
                Err(ToriiError::InvalidConfig(
                    "Failed to update repository settings".to_string()
                ))
            }
        }
    }
    
    fn get_repo(&self, owner: &str, repo: &str) -> Result<RemoteRepo> {
        let repo_name = format!("{}/{}", owner, repo);
        let output = std::process::Command::new("gh")
            .args(&["repo", "view", &repo_name, "--json", "name,description,visibility,defaultBranchRef,url,sshUrl"])
            .output();
        
        match output {
            Ok(out) if out.status.success() => {
                // Parse JSON output (simplified)
                Ok(RemoteRepo {
                    name: repo.to_string(),
                    description: None,
                    visibility: Visibility::Private,
                    default_branch: "main".to_string(),
                    url: format!("https://github.com/{}/{}", owner, repo),
                    ssh_url: format!("git@github.com:{}/{}.git", owner, repo),
                    clone_url: format!("https://github.com/{}/{}.git", owner, repo),
                })
            }
            _ => {
                Err(ToriiError::InvalidConfig(
                    "Failed to get repository information".to_string()
                ))
            }
        }
    }
    
    fn list_repos(&self) -> Result<Vec<RemoteRepo>> {
        let output = std::process::Command::new("gh")
            .args(&["repo", "list", "--json", "name,description,visibility", "--limit", "100"])
            .output();
        
        match output {
            Ok(out) if out.status.success() => {
                // Return empty list for now (would parse JSON in full implementation)
                Ok(Vec::new())
            }
            _ => {
                Err(ToriiError::InvalidConfig(
                    "Failed to list repositories".to_string()
                ))
            }
        }
    }
    
    fn set_visibility(&self, owner: &str, repo: &str, visibility: Visibility) -> Result<()> {
        let mut settings = RepoSettings::default();
        settings.visibility = Some(visibility);
        self.update_repo(owner, repo, settings)?;
        Ok(())
    }
    
    fn configure_features(&self, owner: &str, repo: &str, features: RepoFeatures) -> Result<()> {
        let repo_name = format!("{}/{}", owner, repo);
        let mut args = vec!["repo", "edit", &repo_name];
        
        let mut temp_args = Vec::new();
        
        if let Some(issues) = features.issues {
            temp_args.push(if issues { "--enable-issues".to_string() } else { "--disable-issues".to_string() });
        }
        
        if let Some(wiki) = features.wiki {
            temp_args.push(if wiki { "--enable-wiki".to_string() } else { "--disable-wiki".to_string() });
        }
        
        if let Some(projects) = features.projects {
            temp_args.push(if projects { "--enable-projects".to_string() } else { "--disable-projects".to_string() });
        }
        
        let arg_refs: Vec<&str> = temp_args.iter().map(|s| s.as_str()).collect();
        args.extend(arg_refs);
        
        let output = std::process::Command::new("gh")
            .args(&args)
            .output();
        
        match output {
            Ok(out) if out.status.success() => {
                println!("✅ Repository features configured");
                Ok(())
            }
            _ => {
                Err(ToriiError::InvalidConfig(
                    "Failed to configure repository features".to_string()
                ))
            }
        }
    }
}

/// GitLab API client (placeholder)
pub struct GitLabClient {
    token: Option<String>,
    base_url: String,
}

impl GitLabClient {
    pub fn new(token: Option<String>, base_url: Option<String>) -> Self {
        Self { 
            token,
            base_url: base_url.unwrap_or_else(|| "https://gitlab.com/api/v4".to_string()),
        }
    }
    
    #[allow(dead_code)]
    pub fn with_url(token: String, base_url: String) -> Self {
        Self {
            token: Some(token),
            base_url,
        }
    }
}

impl PlatformClient for GitLabClient {
    fn create_repo(&self, name: &str, description: Option<&str>, visibility: Visibility) -> Result<RemoteRepo> {
        let token = self.token.as_ref()
            .ok_or_else(|| ToriiError::InvalidConfig(
                "GitLab token not found. Set GITLAB_TOKEN environment variable".to_string()
            ))?;

        let visibility_str = match visibility {
            Visibility::Public => "public",
            Visibility::Private => "private",
            Visibility::Internal => "internal",
        };

        let mut body = serde_json::json!({
            "name": name,
            "visibility": visibility_str,
        });

        if let Some(desc) = description {
            body["description"] = serde_json::json!(desc);
        }

        let client = reqwest::blocking::Client::new();
        let response = client
            .post(format!("{}/projects", self.base_url))
            .header("PRIVATE-TOKEN", token)
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .map_err(|e| ToriiError::InvalidConfig(format!("GitLab API request failed: {}", e)))?;

        if !response.status().is_success() {
            let error_text = response.text().unwrap_or_else(|_| "Unknown error".to_string());
            return Err(ToriiError::InvalidConfig(
                format!("GitLab API error: {}", error_text)
            ));
        }

        let project: serde_json::Value = response.json()
            .map_err(|e| ToriiError::InvalidConfig(format!("Failed to parse GitLab response: {}", e)))?;

        Ok(RemoteRepo {
            name: project["name"].as_str().unwrap_or(name).to_string(),
            description: project["description"].as_str().map(|s| s.to_string()),
            visibility,
            default_branch: project["default_branch"].as_str().unwrap_or("main").to_string(),
            url: project["web_url"].as_str().unwrap_or("").to_string(),
            ssh_url: project["ssh_url_to_repo"].as_str().unwrap_or("").to_string(),
            clone_url: project["http_url_to_repo"].as_str().unwrap_or("").to_string(),
        })
    }
    
    fn delete_repo(&self, owner: &str, repo: &str) -> Result<()> {
        let token = self.token.as_ref()
            .ok_or_else(|| ToriiError::InvalidConfig(
                "GitLab token not found. Set GITLAB_TOKEN environment variable".to_string()
            ))?;

        let path_str = format!("{}/{}", owner, repo);
        let project_path = urlencoding::encode(&path_str);
        let client = reqwest::blocking::Client::new();
        let response = client
            .delete(format!("{}/projects/{}", self.base_url, project_path))
            .header("PRIVATE-TOKEN", token)
            .send()
            .map_err(|e| ToriiError::InvalidConfig(format!("GitLab API request failed: {}", e)))?;

        if !response.status().is_success() {
            let error_text = response.text().unwrap_or_else(|_| "Unknown error".to_string());
            return Err(ToriiError::InvalidConfig(
                format!("GitLab API error: {}", error_text)
            ));
        }

        Ok(())
    }
    
    fn update_repo(&self, owner: &str, repo: &str, settings: RepoSettings) -> Result<RemoteRepo> {
        let token = self.token.as_ref()
            .ok_or_else(|| ToriiError::InvalidConfig(
                "GitLab token not found. Set GITLAB_TOKEN environment variable".to_string()
            ))?;

        let path_str = format!("{}/{}", owner, repo);
        let project_path = urlencoding::encode(&path_str);
        let mut body = serde_json::json!({});

        if let Some(desc) = settings.description {
            body["description"] = serde_json::json!(desc);
        }
        if let Some(vis) = settings.visibility {
            let vis_str = match vis {
                Visibility::Public => "public",
                Visibility::Private => "private",
                Visibility::Internal => "internal",
            };
            body["visibility"] = serde_json::json!(vis_str);
        }
        if let Some(branch) = settings.default_branch {
            body["default_branch"] = serde_json::json!(branch);
        }

        let client = reqwest::blocking::Client::new();
        let response = client
            .put(format!("{}/projects/{}", self.base_url, project_path))
            .header("PRIVATE-TOKEN", token)
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .map_err(|e| ToriiError::InvalidConfig(format!("GitLab API request failed: {}", e)))?;

        if !response.status().is_success() {
            let error_text = response.text().unwrap_or_else(|_| "Unknown error".to_string());
            return Err(ToriiError::InvalidConfig(
                format!("GitLab API error: {}", error_text)
            ));
        }

        let project: serde_json::Value = response.json()
            .map_err(|e| ToriiError::InvalidConfig(format!("Failed to parse GitLab response: {}", e)))?;

        let visibility = match project["visibility"].as_str() {
            Some("public") => Visibility::Public,
            Some("internal") => Visibility::Internal,
            _ => Visibility::Private,
        };

        Ok(RemoteRepo {
            name: project["name"].as_str().unwrap_or(repo).to_string(),
            description: project["description"].as_str().map(|s| s.to_string()),
            visibility,
            default_branch: project["default_branch"].as_str().unwrap_or("main").to_string(),
            url: project["web_url"].as_str().unwrap_or("").to_string(),
            ssh_url: project["ssh_url_to_repo"].as_str().unwrap_or("").to_string(),
            clone_url: project["http_url_to_repo"].as_str().unwrap_or("").to_string(),
        })
    }
    
    fn get_repo(&self, owner: &str, repo: &str) -> Result<RemoteRepo> {
        let token = self.token.as_ref()
            .ok_or_else(|| ToriiError::InvalidConfig(
                "GitLab token not found. Set GITLAB_TOKEN environment variable".to_string()
            ))?;

        let path_str = format!("{}/{}", owner, repo);
        let project_path = urlencoding::encode(&path_str);
        let client = reqwest::blocking::Client::new();
        let response = client
            .get(format!("{}/projects/{}", self.base_url, project_path))
            .header("PRIVATE-TOKEN", token)
            .send()
            .map_err(|e| ToriiError::InvalidConfig(format!("GitLab API request failed: {}", e)))?;

        if !response.status().is_success() {
            let error_text = response.text().unwrap_or_else(|_| "Unknown error".to_string());
            return Err(ToriiError::InvalidConfig(
                format!("GitLab API error: {}", error_text)
            ));
        }

        let project: serde_json::Value = response.json()
            .map_err(|e| ToriiError::InvalidConfig(format!("Failed to parse GitLab response: {}", e)))?;

        let visibility = match project["visibility"].as_str() {
            Some("public") => Visibility::Public,
            Some("internal") => Visibility::Internal,
            _ => Visibility::Private,
        };

        Ok(RemoteRepo {
            name: project["name"].as_str().unwrap_or(repo).to_string(),
            description: project["description"].as_str().map(|s| s.to_string()),
            visibility,
            default_branch: project["default_branch"].as_str().unwrap_or("main").to_string(),
            url: project["web_url"].as_str().unwrap_or("").to_string(),
            ssh_url: project["ssh_url_to_repo"].as_str().unwrap_or("").to_string(),
            clone_url: project["http_url_to_repo"].as_str().unwrap_or("").to_string(),
        })
    }
    
    fn list_repos(&self) -> Result<Vec<RemoteRepo>> {
        let token = self.token.as_ref()
            .ok_or_else(|| ToriiError::InvalidConfig(
                "GitLab token not found. Set GITLAB_TOKEN environment variable".to_string()
            ))?;

        let client = reqwest::blocking::Client::new();
        let response = client
            .get(format!("{}/projects?membership=true&per_page=100", self.base_url))
            .header("PRIVATE-TOKEN", token)
            .send()
            .map_err(|e| ToriiError::InvalidConfig(format!("GitLab API request failed: {}", e)))?;

        if !response.status().is_success() {
            let error_text = response.text().unwrap_or_else(|_| "Unknown error".to_string());
            return Err(ToriiError::InvalidConfig(
                format!("GitLab API error: {}", error_text)
            ));
        }

        let projects: Vec<serde_json::Value> = response.json()
            .map_err(|e| ToriiError::InvalidConfig(format!("Failed to parse GitLab response: {}", e)))?;

        Ok(projects.iter().map(|project| {
            let visibility = match project["visibility"].as_str() {
                Some("public") => Visibility::Public,
                Some("internal") => Visibility::Internal,
                _ => Visibility::Private,
            };

            RemoteRepo {
                name: project["name"].as_str().unwrap_or("").to_string(),
                description: project["description"].as_str().map(|s| s.to_string()),
                visibility,
                default_branch: project["default_branch"].as_str().unwrap_or("main").to_string(),
                url: project["web_url"].as_str().unwrap_or("").to_string(),
                ssh_url: project["ssh_url_to_repo"].as_str().unwrap_or("").to_string(),
                clone_url: project["http_url_to_repo"].as_str().unwrap_or("").to_string(),
            }
        }).collect())
    }
    
    fn set_visibility(&self, owner: &str, repo: &str, visibility: Visibility) -> Result<()> {
        let token = self.token.as_ref()
            .ok_or_else(|| ToriiError::InvalidConfig(
                "GitLab token not found. Set GITLAB_TOKEN environment variable".to_string()
            ))?;

        let path_str = format!("{}/{}", owner, repo);
        let project_path = urlencoding::encode(&path_str);
        let visibility_str = match visibility {
            Visibility::Public => "public",
            Visibility::Private => "private",
            Visibility::Internal => "internal",
        };

        let body = serde_json::json!({
            "visibility": visibility_str,
        });

        let client = reqwest::blocking::Client::new();
        let response = client
            .put(format!("{}/projects/{}", self.base_url, project_path))
            .header("PRIVATE-TOKEN", token)
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .map_err(|e| ToriiError::InvalidConfig(format!("GitLab API request failed: {}", e)))?;

        if !response.status().is_success() {
            let error_text = response.text().unwrap_or_else(|_| "Unknown error".to_string());
            return Err(ToriiError::InvalidConfig(
                format!("GitLab API error: {}", error_text)
            ));
        }

        Ok(())
    }
    
    fn configure_features(&self, owner: &str, repo: &str, features: RepoFeatures) -> Result<()> {
        let token = self.token.as_ref()
            .ok_or_else(|| ToriiError::InvalidConfig(
                "GitLab token not found. Set GITLAB_TOKEN environment variable".to_string()
            ))?;

        let path_str = format!("{}/{}", owner, repo);
        let project_path = urlencoding::encode(&path_str);
        let mut body = serde_json::json!({});

        if let Some(issues) = features.issues {
            body["issues_enabled"] = serde_json::json!(issues);
        }
        if let Some(wiki) = features.wiki {
            body["wiki_enabled"] = serde_json::json!(wiki);
        }

        let client = reqwest::blocking::Client::new();
        let response = client
            .put(format!("{}/projects/{}", self.base_url, project_path))
            .header("PRIVATE-TOKEN", token)
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .map_err(|e| ToriiError::InvalidConfig(format!("GitLab API request failed: {}", e)))?;

        if !response.status().is_success() {
            let error_text = response.text().unwrap_or_else(|_| "Unknown error".to_string());
            return Err(ToriiError::InvalidConfig(
                format!("GitLab API error: {}", error_text)
            ));
        }

        Ok(())
    }
}

/// Get appropriate platform client based on platform name
pub fn get_platform_client(platform: &str) -> Result<Box<dyn PlatformClient>> {
    match platform.to_lowercase().as_str() {
        "github" => {
            let token = GitHubClient::get_token()?;
            Ok(Box::new(GitHubClient::new(token)))
        }
        "gitlab" => {
            let config = ToriiConfig::load_global().unwrap_or_default();
            let token = std::env::var("GITLAB_TOKEN").ok()
                .or(config.auth.gitlab_token)
                .ok_or_else(|| ToriiError::InvalidConfig(
                    "GitLab token not found. Run: torii config set auth.gitlab_token YOUR_TOKEN".to_string()
                ))?;
            let base_url = std::env::var("GITLAB_URL").ok();
            Ok(Box::new(GitLabClient::new(Some(token), base_url)))
        }
        "gitea" => {
            let config = ToriiConfig::load_global().unwrap_or_default();
            let token = std::env::var("GITEA_TOKEN").ok().or(config.auth.gitea_token);
            let base_url = std::env::var("GITEA_URL")
                .unwrap_or_else(|_| "https://gitea.com".to_string());
            Ok(Box::new(GiteaClient::new(token, base_url)))
        }
        "forgejo" => {
            let config = ToriiConfig::load_global().unwrap_or_default();
            let token = std::env::var("FORGEJO_TOKEN").ok().or(config.auth.forgejo_token);
            let base_url = std::env::var("FORGEJO_URL")
                .unwrap_or_else(|_| "https://codeberg.org".to_string());
            Ok(Box::new(ForgejoClient::new(token, base_url)))
        }
        "codeberg" => {
            let config = ToriiConfig::load_global().unwrap_or_default();
            let token = std::env::var("CODEBERG_TOKEN").ok().or(config.auth.codeberg_token);
            Ok(Box::new(CodebergClient::new(token)))
        }
        _ => Err(ToriiError::InvalidConfig(
            format!("Unsupported platform: {}. Supported: github, gitlab, gitea, forgejo, codeberg", platform)
        )),
    }
}

// ============================================================================
// Gitea/Forgejo/Codeberg Clients
// ============================================================================

#[allow(dead_code)]
pub struct GiteaClient {
    token: Option<String>,
    base_url: String,
}

impl GiteaClient {
    pub fn new(token: Option<String>, base_url: String) -> Self {
        Self { token, base_url }
    }
}

#[allow(dead_code)]
pub struct ForgejoClient {
    token: Option<String>,
    base_url: String,
}

impl ForgejoClient {
    pub fn new(token: Option<String>, base_url: String) -> Self {
        Self { token, base_url }
    }
}

#[allow(dead_code)]
pub struct CodebergClient {
    token: Option<String>,
}

impl CodebergClient {
    pub fn new(token: Option<String>) -> Self {
        Self { token }
    }
}

// Placeholder implementations - will be completed with API calls
impl PlatformClient for GiteaClient {
    fn create_repo(&self, _name: &str, _description: Option<&str>, _visibility: Visibility) -> Result<RemoteRepo> {
        Err(ToriiError::InvalidConfig("Gitea API not yet implemented".to_string()))
    }
    fn delete_repo(&self, _owner: &str, _repo: &str) -> Result<()> {
        Err(ToriiError::InvalidConfig("Gitea API not yet implemented".to_string()))
    }
    fn update_repo(&self, _owner: &str, _repo: &str, _settings: RepoSettings) -> Result<RemoteRepo> {
        Err(ToriiError::InvalidConfig("Gitea API not yet implemented".to_string()))
    }
    fn get_repo(&self, _owner: &str, _repo: &str) -> Result<RemoteRepo> {
        Err(ToriiError::InvalidConfig("Gitea API not yet implemented".to_string()))
    }
    fn list_repos(&self) -> Result<Vec<RemoteRepo>> {
        Err(ToriiError::InvalidConfig("Gitea API not yet implemented".to_string()))
    }
    fn set_visibility(&self, _owner: &str, _repo: &str, _visibility: Visibility) -> Result<()> {
        Err(ToriiError::InvalidConfig("Gitea API not yet implemented".to_string()))
    }
    fn configure_features(&self, _owner: &str, _repo: &str, _features: RepoFeatures) -> Result<()> {
        Err(ToriiError::InvalidConfig("Gitea API not yet implemented".to_string()))
    }
}

impl PlatformClient for ForgejoClient {
    fn create_repo(&self, _name: &str, _description: Option<&str>, _visibility: Visibility) -> Result<RemoteRepo> {
        Err(ToriiError::InvalidConfig("Forgejo API not yet implemented".to_string()))
    }
    fn delete_repo(&self, _owner: &str, _repo: &str) -> Result<()> {
        Err(ToriiError::InvalidConfig("Forgejo API not yet implemented".to_string()))
    }
    fn update_repo(&self, _owner: &str, _repo: &str, _settings: RepoSettings) -> Result<RemoteRepo> {
        Err(ToriiError::InvalidConfig("Forgejo API not yet implemented".to_string()))
    }
    fn get_repo(&self, _owner: &str, _repo: &str) -> Result<RemoteRepo> {
        Err(ToriiError::InvalidConfig("Forgejo API not yet implemented".to_string()))
    }
    fn list_repos(&self) -> Result<Vec<RemoteRepo>> {
        Err(ToriiError::InvalidConfig("Forgejo API not yet implemented".to_string()))
    }
    fn set_visibility(&self, _owner: &str, _repo: &str, _visibility: Visibility) -> Result<()> {
        Err(ToriiError::InvalidConfig("Forgejo API not yet implemented".to_string()))
    }
    fn configure_features(&self, _owner: &str, _repo: &str, _features: RepoFeatures) -> Result<()> {
        Err(ToriiError::InvalidConfig("Forgejo API not yet implemented".to_string()))
    }
}

impl PlatformClient for CodebergClient {
    fn create_repo(&self, _name: &str, _description: Option<&str>, _visibility: Visibility) -> Result<RemoteRepo> {
        Err(ToriiError::InvalidConfig("Codeberg API not yet implemented".to_string()))
    }
    fn delete_repo(&self, _owner: &str, _repo: &str) -> Result<()> {
        Err(ToriiError::InvalidConfig("Codeberg API not yet implemented".to_string()))
    }
    fn update_repo(&self, _owner: &str, _repo: &str, _settings: RepoSettings) -> Result<RemoteRepo> {
        Err(ToriiError::InvalidConfig("Codeberg API not yet implemented".to_string()))
    }
    fn get_repo(&self, _owner: &str, _repo: &str) -> Result<RemoteRepo> {
        Err(ToriiError::InvalidConfig("Codeberg API not yet implemented".to_string()))
    }
    fn list_repos(&self) -> Result<Vec<RemoteRepo>> {
        Err(ToriiError::InvalidConfig("Codeberg API not yet implemented".to_string()))
    }
    fn set_visibility(&self, _owner: &str, _repo: &str, _visibility: Visibility) -> Result<()> {
        Err(ToriiError::InvalidConfig("Codeberg API not yet implemented".to_string()))
    }
    fn configure_features(&self, _owner: &str, _repo: &str, _features: RepoFeatures) -> Result<()> {
        Err(ToriiError::InvalidConfig("Codeberg API not yet implemented".to_string()))
    }
}