cctakt 0.1.1

TUI orchestrator for multiple Claude Code agents using Git Worktree
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
//! GitHub Issues integration for cctakt
//!
//! Provides functionality to fetch issues from GitHub and use them as agent tasks.

use anyhow::{anyhow, Context, Result};
use serde::{Deserialize, Serialize};
use std::process::Command;

#[cfg(test)]
use mockall::automock;

/// GitHub Issue representation
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Issue {
    /// Issue number
    pub number: u64,

    /// Issue title
    pub title: String,

    /// Issue body (description)
    pub body: Option<String>,

    /// Labels attached to the issue
    pub labels: Vec<Label>,

    /// Issue state ("open" or "closed")
    pub state: String,

    /// URL to the issue on GitHub
    pub html_url: String,
}

/// GitHub Label representation
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Label {
    /// Label name
    pub name: String,

    /// Label color (hex without #)
    pub color: String,
}

/// GitHub Pull Request representation
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PullRequest {
    /// PR number
    pub number: u64,

    /// PR title
    pub title: String,

    /// PR body (description)
    pub body: Option<String>,

    /// PR state ("open", "closed", "merged")
    pub state: String,

    /// URL to the PR on GitHub
    pub html_url: String,

    /// Head branch name
    pub head: PullRequestRef,

    /// Base branch name
    pub base: PullRequestRef,

    /// Whether the PR is a draft
    #[serde(default)]
    pub draft: bool,
}

/// Pull Request branch reference
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PullRequestRef {
    /// Branch name
    #[serde(rename = "ref")]
    pub branch: String,

    /// SHA of the commit
    pub sha: String,
}

/// Parameters for creating a pull request
#[derive(Debug, Clone)]
pub struct CreatePullRequest {
    /// PR title
    pub title: String,

    /// PR body/description
    pub body: Option<String>,

    /// Head branch (the branch with changes)
    pub head: String,

    /// Base branch (the branch to merge into)
    pub base: String,

    /// Whether to create as draft
    pub draft: bool,
}

/// HTTP response abstraction for testing
#[derive(Debug, Clone)]
pub struct HttpResponse {
    pub status: u16,
    pub body: String,
}

/// HTTP headers type
pub type Headers = Vec<(String, String)>;

/// Trait for HTTP operations (allows mocking)
#[cfg_attr(test, automock)]
pub trait HttpClient: Send + Sync {
    /// Send a GET request
    fn get(&self, url: &str, headers: Headers) -> Result<HttpResponse>;

    /// Send a POST request with JSON body
    fn post(&self, url: &str, headers: Headers, body: String) -> Result<HttpResponse>;

    /// Send a PATCH request with JSON body
    fn patch(&self, url: &str, headers: Headers, body: String) -> Result<HttpResponse>;
}

/// Real HTTP client using ureq
pub struct UreqHttpClient {
    agent: ureq::Agent,
}

impl Default for UreqHttpClient {
    fn default() -> Self {
        Self::new()
    }
}

impl UreqHttpClient {
    /// Create a new HTTP client with proxy support from environment variables
    pub fn new() -> Self {
        use std::time::Duration;

        let mut builder = ureq::AgentBuilder::new()
            .timeout(Duration::from_secs(10));

        // Check for HTTPS_PROXY or HTTP_PROXY environment variable
        if let Ok(proxy_url) = std::env::var("HTTPS_PROXY")
            .or_else(|_| std::env::var("https_proxy"))
            .or_else(|_| std::env::var("HTTP_PROXY"))
            .or_else(|_| std::env::var("http_proxy"))
        {
            if let Ok(proxy) = ureq::Proxy::new(&proxy_url) {
                builder = builder.proxy(proxy);
            }
        }

        Self {
            agent: builder.build(),
        }
    }
}

impl HttpClient for UreqHttpClient {
    fn get(&self, url: &str, headers: Headers) -> Result<HttpResponse> {
        let mut request = self.agent.get(url);
        for (key, value) in &headers {
            request = request.set(key, value);
        }
        let response = request.call().context("HTTP GET failed")?;
        let status = response.status();
        let body = response.into_string().context("Failed to read response body")?;
        Ok(HttpResponse { status, body })
    }

    fn post(&self, url: &str, headers: Headers, body: String) -> Result<HttpResponse> {
        let mut request = self.agent.post(url);
        for (key, value) in &headers {
            request = request.set(key, value);
        }
        let response = request.send_string(&body).context("HTTP POST failed")?;
        let status = response.status();
        let body = response.into_string().context("Failed to read response body")?;
        Ok(HttpResponse { status, body })
    }

    fn patch(&self, url: &str, headers: Headers, body: String) -> Result<HttpResponse> {
        let mut request = self.agent.patch(url);
        for (key, value) in &headers {
            request = request.set(key, value);
        }
        let response = request.send_string(&body).context("HTTP PATCH failed")?;
        let status = response.status();
        let body = response.into_string().context("Failed to read response body")?;
        Ok(HttpResponse { status, body })
    }
}

/// GitHub API client
pub struct GitHubClient<H: HttpClient = UreqHttpClient> {
    /// Repository in "owner/repo" format
    repository: String,

    /// Authentication token (optional for public repos)
    token: Option<String>,

    /// HTTP client
    http: H,
}

impl GitHubClient<UreqHttpClient> {
    /// Create a new GitHub client
    ///
    /// Authentication is obtained from:
    /// 1. Environment variable `GITHUB_TOKEN`
    /// 2. `gh auth token` command output (GitHub CLI)
    pub fn new(repository: &str) -> Result<Self> {
        let token = Self::get_token();

        Ok(Self {
            repository: repository.to_string(),
            token,
            http: UreqHttpClient::new(),
        })
    }

    /// Create a new GitHub client with explicit token
    pub fn with_token(repository: &str, token: Option<String>) -> Self {
        Self {
            repository: repository.to_string(),
            token,
            http: UreqHttpClient::new(),
        }
    }

    /// Get authentication token from environment or gh CLI
    fn get_token() -> Option<String> {
        // First try environment variable
        if let Ok(token) = std::env::var("GITHUB_TOKEN") {
            if !token.is_empty() {
                return Some(token);
            }
        }

        // Fall back to gh CLI
        Self::get_token_from_gh_cli()
    }

    /// Get token from GitHub CLI
    fn get_token_from_gh_cli() -> Option<String> {
        let output = Command::new("gh")
            .args(["auth", "token"])
            .output()
            .ok()?;

        if output.status.success() {
            let token = String::from_utf8_lossy(&output.stdout)
                .trim()
                .to_string();
            if !token.is_empty() {
                return Some(token);
            }
        }

        None
    }
}

impl<H: HttpClient> GitHubClient<H> {
    /// Create client with custom HTTP client (for testing)
    pub fn with_http_client(repository: &str, token: Option<String>, http: H) -> Self {
        Self {
            repository: repository.to_string(),
            token,
            http,
        }
    }

    /// Build common headers for requests
    fn build_headers(&self) -> Headers {
        let mut headers = vec![
            ("Accept".to_string(), "application/vnd.github.v3+json".to_string()),
            ("User-Agent".to_string(), "cctakt".to_string()),
        ];

        if let Some(ref token) = self.token {
            headers.push(("Authorization".to_string(), format!("Bearer {token}")));
        }

        headers
    }

    /// Fetch issues with optional label and state filters
    ///
    /// # Arguments
    /// * `labels` - Labels to filter by (issues must have at least one of these labels)
    /// * `state` - Issue state: "open", "closed", or "all"
    ///
    /// # Returns
    /// List of issues matching the criteria
    pub fn fetch_issues(&self, labels: &[&str], state: &str) -> Result<Vec<Issue>> {
        let labels_param = labels.join(",");

        let url = if labels.is_empty() {
            format!(
                "https://api.github.com/repos/{}/issues?state={}",
                self.repository, state
            )
        } else {
            format!(
                "https://api.github.com/repos/{}/issues?labels={}&state={}",
                self.repository, labels_param, state
            )
        };

        let headers = self.build_headers();
        let response = self.http.get(&url, headers)
            .with_context(|| format!("Failed to fetch issues from {}", self.repository))?;

        let issues: Vec<Issue> = serde_json::from_str(&response.body)
            .context("Failed to parse issues response")?;

        Ok(issues)
    }

    /// Get a single issue by number
    pub fn get_issue(&self, number: u64) -> Result<Issue> {
        let url = format!(
            "https://api.github.com/repos/{}/issues/{}",
            self.repository, number
        );

        let headers = self.build_headers();
        let response = self.http.get(&url, headers)
            .with_context(|| format!("Failed to fetch issue #{number}"))?;

        let issue: Issue = serde_json::from_str(&response.body)
            .context("Failed to parse issue response")?;

        Ok(issue)
    }

    /// Add a comment to an issue
    pub fn add_comment(&self, number: u64, body: &str) -> Result<()> {
        let url = format!(
            "https://api.github.com/repos/{}/issues/{}/comments",
            self.repository, number
        );

        self.token.as_ref()
            .ok_or_else(|| anyhow!("Authentication required to add comments"))?;

        let mut headers = self.build_headers();
        headers.push(("Content-Type".to_string(), "application/json".to_string()));
        let json_body = serde_json::json!({ "body": body }).to_string();

        let response = self.http.post(&url, headers, json_body)
            .with_context(|| format!("Failed to add comment to issue #{number}"))?;

        if response.status != 201 {
            return Err(anyhow!(
                "Failed to add comment: HTTP {}",
                response.status
            ));
        }

        Ok(())
    }

    /// Close an issue
    pub fn close_issue(&self, number: u64) -> Result<()> {
        let url = format!(
            "https://api.github.com/repos/{}/issues/{}",
            self.repository, number
        );

        self.token.as_ref()
            .ok_or_else(|| anyhow!("Authentication required to close issues"))?;

        let mut headers = self.build_headers();
        headers.push(("Content-Type".to_string(), "application/json".to_string()));
        let json_body = serde_json::json!({ "state": "closed" }).to_string();

        let response = self.http.patch(&url, headers, json_body)
            .with_context(|| format!("Failed to close issue #{number}"))?;

        if response.status != 200 {
            return Err(anyhow!(
                "Failed to close issue: HTTP {}",
                response.status
            ));
        }

        Ok(())
    }

    /// Create a pull request
    ///
    /// # Arguments
    /// * `params` - Pull request parameters
    ///
    /// # Returns
    /// The created pull request
    pub fn create_pull_request(&self, params: &CreatePullRequest) -> Result<PullRequest> {
        let url = format!(
            "https://api.github.com/repos/{}/pulls",
            self.repository
        );

        self.token.as_ref()
            .ok_or_else(|| anyhow!("Authentication required to create pull requests"))?;

        let mut json_body = serde_json::json!({
            "title": params.title,
            "head": params.head,
            "base": params.base,
            "draft": params.draft,
        });

        if let Some(ref body) = params.body {
            json_body["body"] = serde_json::Value::String(body.clone());
        }

        let mut headers = self.build_headers();
        headers.push(("Content-Type".to_string(), "application/json".to_string()));

        let response = self.http.post(&url, headers, json_body.to_string())
            .context("Failed to create pull request")?;

        if response.status != 201 {
            return Err(anyhow!(
                "Failed to create pull request: HTTP {}",
                response.status
            ));
        }

        let pr: PullRequest = serde_json::from_str(&response.body)
            .context("Failed to parse pull request response")?;

        Ok(pr)
    }

    /// Get a pull request by number
    pub fn get_pull_request(&self, number: u64) -> Result<PullRequest> {
        let url = format!(
            "https://api.github.com/repos/{}/pulls/{}",
            self.repository, number
        );

        let headers = self.build_headers();
        let response = self.http.get(&url, headers)
            .with_context(|| format!("Failed to fetch pull request #{number}"))?;

        let pr: PullRequest = serde_json::from_str(&response.body)
            .context("Failed to parse pull request response")?;

        Ok(pr)
    }

    /// List pull requests
    ///
    /// # Arguments
    /// * `state` - PR state: "open", "closed", or "all"
    /// * `head` - Filter by head branch (format: "owner:branch" or just "branch")
    /// * `base` - Filter by base branch
    pub fn list_pull_requests(
        &self,
        state: &str,
        head: Option<&str>,
        base: Option<&str>,
    ) -> Result<Vec<PullRequest>> {
        let mut url = format!(
            "https://api.github.com/repos/{}/pulls?state={}",
            self.repository, state
        );

        if let Some(head_branch) = head {
            url.push_str(&format!("&head={head_branch}"));
        }

        if let Some(base_branch) = base {
            url.push_str(&format!("&base={base_branch}"));
        }

        let headers = self.build_headers();
        let response = self.http.get(&url, headers)
            .context("Failed to fetch pull requests")?;

        let prs: Vec<PullRequest> = serde_json::from_str(&response.body)
            .context("Failed to parse pull requests response")?;

        Ok(prs)
    }

    /// Check if client has authentication
    pub fn has_auth(&self) -> bool {
        self.token.is_some()
    }

    /// Get the repository name
    pub fn repository(&self) -> &str {
        &self.repository
    }
}

impl Issue {
    /// Get a short description of the issue
    pub fn short_description(&self) -> String {
        format!("#{}: {}", self.number, self.title)
    }

    /// Get label names as a comma-separated string
    pub fn label_names(&self) -> String {
        self.labels
            .iter()
            .map(|l| l.name.as_str())
            .collect::<Vec<_>>()
            .join(", ")
    }

    /// Check if issue has a specific label
    pub fn has_label(&self, name: &str) -> bool {
        self.labels.iter().any(|l| l.name == name)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_issue_short_description() {
        let issue = Issue {
            number: 123,
            title: "Test issue".to_string(),
            body: Some("Body text".to_string()),
            labels: vec![],
            state: "open".to_string(),
            html_url: "https://github.com/test/repo/issues/123".to_string(),
        };

        assert_eq!(issue.short_description(), "#123: Test issue");
    }

    #[test]
    fn test_issue_label_names() {
        let issue = Issue {
            number: 1,
            title: "Test".to_string(),
            body: None,
            labels: vec![
                Label {
                    name: "bug".to_string(),
                    color: "d73a4a".to_string(),
                },
                Label {
                    name: "enhancement".to_string(),
                    color: "a2eeef".to_string(),
                },
            ],
            state: "open".to_string(),
            html_url: "https://github.com/test/repo/issues/1".to_string(),
        };

        assert_eq!(issue.label_names(), "bug, enhancement");
    }

    #[test]
    fn test_issue_has_label() {
        let issue = Issue {
            number: 1,
            title: "Test".to_string(),
            body: None,
            labels: vec![Label {
                name: "bug".to_string(),
                color: "d73a4a".to_string(),
            }],
            state: "open".to_string(),
            html_url: "https://github.com/test/repo/issues/1".to_string(),
        };

        assert!(issue.has_label("bug"));
        assert!(!issue.has_label("enhancement"));
    }

    #[test]
    fn test_github_client_with_token() {
        let client = GitHubClient::with_token("owner/repo", Some("test-token".to_string()));

        assert_eq!(client.repository(), "owner/repo");
        assert!(client.has_auth());
    }

    #[test]
    fn test_github_client_without_token() {
        let client = GitHubClient::with_token("owner/repo", None);

        assert_eq!(client.repository(), "owner/repo");
        assert!(!client.has_auth());
    }

    #[test]
    fn test_create_pull_request_params() {
        let params = CreatePullRequest {
            title: "Add new feature".to_string(),
            body: Some("This PR adds a new feature".to_string()),
            head: "feature-branch".to_string(),
            base: "main".to_string(),
            draft: false,
        };

        assert_eq!(params.title, "Add new feature");
        assert_eq!(params.head, "feature-branch");
        assert_eq!(params.base, "main");
        assert!(!params.draft);
    }

    #[test]
    fn test_create_pull_request_params_without_body() {
        let params = CreatePullRequest {
            title: "Quick fix".to_string(),
            body: None,
            head: "fix-branch".to_string(),
            base: "main".to_string(),
            draft: true,
        };

        assert!(params.body.is_none());
        assert!(params.draft);
    }

    #[test]
    fn test_pull_request_ref() {
        let json = r#"{
            "ref": "feature-branch",
            "sha": "abc123def456"
        }"#;

        let pr_ref: PullRequestRef = serde_json::from_str(json).unwrap();
        assert_eq!(pr_ref.branch, "feature-branch");
        assert_eq!(pr_ref.sha, "abc123def456");
    }

    #[test]
    fn test_pull_request_deserialize() {
        let json = r#"{
            "number": 42,
            "title": "Add authentication",
            "body": "This PR adds JWT authentication",
            "state": "open",
            "html_url": "https://github.com/test/repo/pull/42",
            "head": {
                "ref": "feature/auth",
                "sha": "abc123"
            },
            "base": {
                "ref": "main",
                "sha": "def456"
            },
            "draft": false
        }"#;

        let pr: PullRequest = serde_json::from_str(json).unwrap();
        assert_eq!(pr.number, 42);
        assert_eq!(pr.title, "Add authentication");
        assert_eq!(pr.body, Some("This PR adds JWT authentication".to_string()));
        assert_eq!(pr.state, "open");
        assert_eq!(pr.head.branch, "feature/auth");
        assert_eq!(pr.base.branch, "main");
        assert!(!pr.draft);
    }

    #[test]
    fn test_pull_request_deserialize_draft_default() {
        let json = r#"{
            "number": 1,
            "title": "Test",
            "body": null,
            "state": "open",
            "html_url": "https://github.com/test/repo/pull/1",
            "head": {
                "ref": "test",
                "sha": "abc"
            },
            "base": {
                "ref": "main",
                "sha": "def"
            }
        }"#;

        let pr: PullRequest = serde_json::from_str(json).unwrap();
        // draft should default to false when not present
        assert!(!pr.draft);
    }
}

// Integration tests that require actual GitHub API access
#[cfg(test)]
mod integration_tests {
    use super::*;

    #[test]
    #[ignore] // Run with: cargo test github_integration -- --ignored
    fn test_fetch_issues_from_public_repo() {
        // Test against a known public repository
        let client = GitHubClient::new("rust-lang/rust").unwrap();
        let issues = client.fetch_issues(&[], "open").unwrap();

        // Should be able to fetch at least some issues
        assert!(!issues.is_empty());
    }

    #[test]
    #[ignore]
    fn test_get_single_issue() {
        let client = GitHubClient::new("rust-lang/rust").unwrap();
        // Issue #1 exists in rust-lang/rust
        let issue = client.get_issue(1).unwrap();

        assert_eq!(issue.number, 1);
    }
}

// Mock-based tests for GitHub API
#[cfg(test)]
mod mock_tests {
    use super::*;

    fn mock_issue_json() -> String {
        r#"{
            "number": 42,
            "title": "Test issue",
            "body": "Issue body",
            "labels": [{"name": "bug", "color": "d73a4a"}],
            "state": "open",
            "html_url": "https://github.com/test/repo/issues/42"
        }"#.to_string()
    }

    fn mock_issues_json() -> String {
        format!("[{}]", mock_issue_json())
    }

    fn mock_pr_json() -> String {
        r#"{
            "number": 123,
            "title": "Test PR",
            "body": "PR body",
            "state": "open",
            "html_url": "https://github.com/test/repo/pull/123",
            "head": {"ref": "feature", "sha": "abc123"},
            "base": {"ref": "main", "sha": "def456"},
            "draft": false
        }"#.to_string()
    }

    fn mock_prs_json() -> String {
        format!("[{}]", mock_pr_json())
    }

    #[test]
    fn test_fetch_issues_with_mock() {
        let mut mock = MockHttpClient::new();
        mock.expect_get()
            .withf(|url: &str, _: &Headers| url.contains("/issues"))
            .returning(|_, _| Ok(HttpResponse {
                status: 200,
                body: mock_issues_json(),
            }));

        let client = GitHubClient::with_http_client("test/repo", None, mock);
        let issues = client.fetch_issues(&[], "open").unwrap();

        assert_eq!(issues.len(), 1);
        assert_eq!(issues[0].number, 42);
        assert_eq!(issues[0].title, "Test issue");
    }

    #[test]
    fn test_fetch_issues_with_labels() {
        let mut mock = MockHttpClient::new();
        mock.expect_get()
            .withf(|url: &str, _: &Headers| url.contains("labels=bug,enhancement"))
            .returning(|_, _| Ok(HttpResponse {
                status: 200,
                body: mock_issues_json(),
            }));

        let client = GitHubClient::with_http_client("test/repo", None, mock);
        let issues = client.fetch_issues(&["bug", "enhancement"], "open").unwrap();

        assert_eq!(issues.len(), 1);
    }

    #[test]
    fn test_get_issue_with_mock() {
        let mut mock = MockHttpClient::new();
        mock.expect_get()
            .withf(|url: &str, _: &Headers| url.contains("/issues/42"))
            .returning(|_, _| Ok(HttpResponse {
                status: 200,
                body: mock_issue_json(),
            }));

        let client = GitHubClient::with_http_client("test/repo", None, mock);
        let issue = client.get_issue(42).unwrap();

        assert_eq!(issue.number, 42);
        assert_eq!(issue.title, "Test issue");
        assert!(issue.has_label("bug"));
    }

    #[test]
    fn test_add_comment_with_mock() {
        let mut mock = MockHttpClient::new();
        mock.expect_post()
            .withf(|url: &str, _: &Headers, body: &String| {
                url.contains("/issues/42/comments") && body.contains("Test comment")
            })
            .returning(|_, _, _| Ok(HttpResponse {
                status: 201,
                body: "{}".to_string(),
            }));

        let client = GitHubClient::with_http_client(
            "test/repo",
            Some("test-token".to_string()),
            mock,
        );
        let result = client.add_comment(42, "Test comment");

        assert!(result.is_ok());
    }

    #[test]
    fn test_add_comment_requires_auth() {
        let mock = MockHttpClient::new();
        let client = GitHubClient::with_http_client("test/repo", None, mock);
        let result = client.add_comment(42, "Test comment");

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Authentication required"));
    }

    #[test]
    fn test_add_comment_http_error() {
        let mut mock = MockHttpClient::new();
        mock.expect_post()
            .returning(|_, _, _| Ok(HttpResponse {
                status: 403,
                body: "Forbidden".to_string(),
            }));

        let client = GitHubClient::with_http_client(
            "test/repo",
            Some("test-token".to_string()),
            mock,
        );
        let result = client.add_comment(42, "Test comment");

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("HTTP 403"));
    }

    #[test]
    fn test_close_issue_with_mock() {
        let mut mock = MockHttpClient::new();
        mock.expect_patch()
            .withf(|url: &str, _: &Headers, body: &String| {
                url.contains("/issues/42") && body.contains("closed")
            })
            .returning(|_, _, _| Ok(HttpResponse {
                status: 200,
                body: "{}".to_string(),
            }));

        let client = GitHubClient::with_http_client(
            "test/repo",
            Some("test-token".to_string()),
            mock,
        );
        let result = client.close_issue(42);

        assert!(result.is_ok());
    }

    #[test]
    fn test_close_issue_requires_auth() {
        let mock = MockHttpClient::new();
        let client = GitHubClient::with_http_client("test/repo", None, mock);
        let result = client.close_issue(42);

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Authentication required"));
    }

    #[test]
    fn test_close_issue_http_error() {
        let mut mock = MockHttpClient::new();
        mock.expect_patch()
            .returning(|_, _, _| Ok(HttpResponse {
                status: 404,
                body: "Not found".to_string(),
            }));

        let client = GitHubClient::with_http_client(
            "test/repo",
            Some("test-token".to_string()),
            mock,
        );
        let result = client.close_issue(42);

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("HTTP 404"));
    }

    #[test]
    fn test_create_pull_request_with_mock() {
        let mut mock = MockHttpClient::new();
        mock.expect_post()
            .withf(|url: &str, _: &Headers, body: &String| {
                url.contains("/pulls")
                    && body.contains("Test PR")
                    && body.contains("feature")
                    && body.contains("main")
            })
            .returning(|_, _, _| Ok(HttpResponse {
                status: 201,
                body: mock_pr_json(),
            }));

        let client = GitHubClient::with_http_client(
            "test/repo",
            Some("test-token".to_string()),
            mock,
        );
        let params = CreatePullRequest {
            title: "Test PR".to_string(),
            body: Some("PR description".to_string()),
            head: "feature".to_string(),
            base: "main".to_string(),
            draft: false,
        };
        let pr = client.create_pull_request(&params).unwrap();

        assert_eq!(pr.number, 123);
        assert_eq!(pr.title, "Test PR");
    }

    #[test]
    fn test_create_pull_request_requires_auth() {
        let mock = MockHttpClient::new();
        let client = GitHubClient::with_http_client("test/repo", None, mock);
        let params = CreatePullRequest {
            title: "Test PR".to_string(),
            body: None,
            head: "feature".to_string(),
            base: "main".to_string(),
            draft: false,
        };
        let result = client.create_pull_request(&params);

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Authentication required"));
    }

    #[test]
    fn test_create_pull_request_http_error() {
        let mut mock = MockHttpClient::new();
        mock.expect_post()
            .returning(|_, _, _| Ok(HttpResponse {
                status: 422,
                body: "Validation failed".to_string(),
            }));

        let client = GitHubClient::with_http_client(
            "test/repo",
            Some("test-token".to_string()),
            mock,
        );
        let params = CreatePullRequest {
            title: "Test PR".to_string(),
            body: None,
            head: "feature".to_string(),
            base: "main".to_string(),
            draft: false,
        };
        let result = client.create_pull_request(&params);

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("HTTP 422"));
    }

    #[test]
    fn test_get_pull_request_with_mock() {
        let mut mock = MockHttpClient::new();
        mock.expect_get()
            .withf(|url: &str, _: &Headers| url.contains("/pulls/123"))
            .returning(|_, _| Ok(HttpResponse {
                status: 200,
                body: mock_pr_json(),
            }));

        let client = GitHubClient::with_http_client("test/repo", None, mock);
        let pr = client.get_pull_request(123).unwrap();

        assert_eq!(pr.number, 123);
        assert_eq!(pr.head.branch, "feature");
        assert_eq!(pr.base.branch, "main");
    }

    #[test]
    fn test_list_pull_requests_with_mock() {
        let mut mock = MockHttpClient::new();
        mock.expect_get()
            .withf(|url: &str, _: &Headers| url.contains("/pulls?state=open"))
            .returning(|_, _| Ok(HttpResponse {
                status: 200,
                body: mock_prs_json(),
            }));

        let client = GitHubClient::with_http_client("test/repo", None, mock);
        let prs = client.list_pull_requests("open", None, None).unwrap();

        assert_eq!(prs.len(), 1);
        assert_eq!(prs[0].number, 123);
    }

    #[test]
    fn test_list_pull_requests_with_filters() {
        let mut mock = MockHttpClient::new();
        mock.expect_get()
            .withf(|url: &str, _: &Headers| {
                url.contains("state=open")
                    && url.contains("head=feature")
                    && url.contains("base=main")
            })
            .returning(|_, _| Ok(HttpResponse {
                status: 200,
                body: mock_prs_json(),
            }));

        let client = GitHubClient::with_http_client("test/repo", None, mock);
        let prs = client.list_pull_requests("open", Some("feature"), Some("main")).unwrap();

        assert_eq!(prs.len(), 1);
    }

    #[test]
    fn test_http_get_error() {
        let mut mock = MockHttpClient::new();
        mock.expect_get()
            .returning(|_, _| Err(anyhow!("Network error")));

        let client = GitHubClient::with_http_client("test/repo", None, mock);
        let result = client.fetch_issues(&[], "open");

        assert!(result.is_err());
    }

    #[test]
    fn test_json_parse_error() {
        let mut mock = MockHttpClient::new();
        mock.expect_get()
            .returning(|_, _| Ok(HttpResponse {
                status: 200,
                body: "invalid json".to_string(),
            }));

        let client = GitHubClient::with_http_client("test/repo", None, mock);
        let result = client.fetch_issues(&[], "open");

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("parse"));
    }

    #[test]
    fn test_build_headers_with_token() {
        let mock = MockHttpClient::new();
        let client = GitHubClient::with_http_client(
            "test/repo",
            Some("test-token".to_string()),
            mock,
        );
        let headers = client.build_headers();

        assert!(headers.iter().any(|(k, v)| k == "Authorization" && v.contains("Bearer")));
        assert!(headers.iter().any(|(k, _)| k == "Accept"));
        assert!(headers.iter().any(|(k, _)| k == "User-Agent"));
    }

    #[test]
    fn test_build_headers_without_token() {
        let mock = MockHttpClient::new();
        let client = GitHubClient::with_http_client("test/repo", None, mock);
        let headers = client.build_headers();

        assert!(!headers.iter().any(|(k, _)| k == "Authorization"));
        assert!(headers.iter().any(|(k, _)| k == "Accept"));
    }

    #[test]
    fn test_http_response_struct() {
        let response = HttpResponse {
            status: 200,
            body: "test body".to_string(),
        };
        assert_eq!(response.status, 200);
        assert_eq!(response.body, "test body");
    }
}