aptu-core 0.2.20

Core library for Aptu - OSS issue triage with AI assistance
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
// SPDX-License-Identifier: Apache-2.0

//! AI provider trait and shared implementations.
//!
//! Defines the `AiProvider` trait that all AI providers must implement,
//! along with default implementations for shared logic like prompt building,
//! request sending, and response parsing.

use anyhow::{Context, Result};
use async_trait::async_trait;
use reqwest::Client;
use secrecy::SecretString;
use tracing::{debug, instrument};

use super::AiResponse;
use super::types::{
    ChatCompletionRequest, ChatCompletionResponse, ChatMessage, IssueDetails, ResponseFormat,
    TriageResponse,
};
use crate::history::AiStats;

/// Parses JSON response from AI provider, detecting truncated responses.
///
/// If the JSON parsing fails with an EOF error (indicating the response was cut off),
/// returns a `TruncatedResponse` error that can be retried. Other JSON errors are
/// wrapped as `InvalidAIResponse`.
///
/// # Arguments
///
/// * `text` - The JSON text to parse
/// * `provider` - The name of the AI provider (for error context)
///
/// # Returns
///
/// Parsed value of type T, or an error if parsing fails
fn parse_ai_json<T: serde::de::DeserializeOwned>(text: &str, provider: &str) -> Result<T> {
    match serde_json::from_str::<T>(text) {
        Ok(value) => Ok(value),
        Err(e) => {
            // Check if this is an EOF error (truncated response)
            if e.is_eof() {
                Err(anyhow::anyhow!(
                    crate::error::AptuError::TruncatedResponse {
                        provider: provider.to_string(),
                    }
                ))
            } else {
                Err(anyhow::anyhow!(crate::error::AptuError::InvalidAIResponse(
                    e
                )))
            }
        }
    }
}

/// Maximum length for issue body to stay within token limits.
pub const MAX_BODY_LENGTH: usize = 4000;

/// Maximum number of comments to include in the prompt.
pub const MAX_COMMENTS: usize = 5;

/// Maximum number of files to include in PR review prompt.
pub const MAX_FILES: usize = 20;

/// Maximum total diff size (in characters) for PR review prompt.
pub const MAX_TOTAL_DIFF_SIZE: usize = 50_000;

/// Maximum number of labels to include in the prompt.
pub const MAX_LABELS: usize = 30;

/// Maximum number of milestones to include in the prompt.
pub const MAX_MILESTONES: usize = 10;

/// AI provider trait for issue triage and creation.
///
/// Defines the interface that all AI providers must implement.
/// Default implementations are provided for shared logic.
#[async_trait]
pub trait AiProvider: Send + Sync {
    /// Returns the name of the provider (e.g., "gemini", "openrouter").
    fn name(&self) -> &str;

    /// Returns the API URL for this provider.
    fn api_url(&self) -> &str;

    /// Returns the environment variable name for the API key.
    fn api_key_env(&self) -> &str;

    /// Returns the HTTP client for making requests.
    fn http_client(&self) -> &Client;

    /// Returns the API key for authentication.
    fn api_key(&self) -> &SecretString;

    /// Returns the model name.
    fn model(&self) -> &str;

    /// Returns the maximum tokens for API responses.
    fn max_tokens(&self) -> u32;

    /// Returns the temperature for API requests.
    fn temperature(&self) -> f32;

    /// Returns the maximum retry attempts for rate-limited requests.
    ///
    /// Default implementation returns 3. Providers can override
    /// to use a different retry limit.
    fn max_attempts(&self) -> u32 {
        3
    }

    /// Returns the circuit breaker for this provider (optional).
    ///
    /// Default implementation returns None. Providers can override
    /// to provide circuit breaker functionality.
    fn circuit_breaker(&self) -> Option<&super::CircuitBreaker> {
        None
    }

    /// Builds HTTP headers for API requests.
    ///
    /// Default implementation includes Authorization and Content-Type headers.
    /// Providers can override to add custom headers.
    fn build_headers(&self) -> reqwest::header::HeaderMap {
        let mut headers = reqwest::header::HeaderMap::new();
        if let Ok(val) = "application/json".parse() {
            headers.insert("Content-Type", val);
        }
        headers
    }

    /// Validates the model configuration.
    ///
    /// Default implementation does nothing. Providers can override
    /// to enforce constraints (e.g., free tier validation).
    fn validate_model(&self) -> Result<()> {
        Ok(())
    }

    /// Sends a chat completion request to the provider's API (HTTP-only, no retry).
    ///
    /// Default implementation handles HTTP headers, error responses (401, 429).
    /// Does not include retry logic - use `send_and_parse()` for retry behavior.
    #[instrument(skip(self, request), fields(provider = self.name(), model = self.model()))]
    async fn send_request_inner(
        &self,
        request: &ChatCompletionRequest,
    ) -> Result<ChatCompletionResponse> {
        use secrecy::ExposeSecret;
        use tracing::warn;

        use crate::error::AptuError;

        let mut req = self.http_client().post(self.api_url());

        // Add Authorization header
        req = req.header(
            "Authorization",
            format!("Bearer {}", self.api_key().expose_secret()),
        );

        // Add custom headers from provider
        for (key, value) in &self.build_headers() {
            req = req.header(key.clone(), value.clone());
        }

        let response = req
            .json(request)
            .send()
            .await
            .context(format!("Failed to send request to {} API", self.name()))?;

        // Check for HTTP errors
        let status = response.status();
        if !status.is_success() {
            if status.as_u16() == 401 {
                anyhow::bail!(
                    "Invalid {} API key. Check your {} environment variable.",
                    self.name(),
                    self.api_key_env()
                );
            } else if status.as_u16() == 429 {
                warn!("Rate limited by {} API", self.name());
                // Parse Retry-After header (seconds), default to 0 if not present
                let retry_after = response
                    .headers()
                    .get("Retry-After")
                    .and_then(|h| h.to_str().ok())
                    .and_then(|s| s.parse::<u64>().ok())
                    .unwrap_or(0);
                debug!(retry_after, "Parsed Retry-After header");
                return Err(AptuError::RateLimited {
                    provider: self.name().to_string(),
                    retry_after,
                }
                .into());
            }
            let error_body = response.text().await.unwrap_or_default();
            anyhow::bail!(
                "{} API error (HTTP {}): {}",
                self.name(),
                status.as_u16(),
                error_body
            );
        }

        // Parse response
        let completion: ChatCompletionResponse = response
            .json()
            .await
            .context(format!("Failed to parse {} API response", self.name()))?;

        Ok(completion)
    }

    /// Sends a chat completion request and parses the response with retry logic.
    ///
    /// This method wraps both HTTP request and JSON parsing in a single retry loop,
    /// allowing truncated responses to be retried. Includes circuit breaker handling.
    ///
    /// # Arguments
    ///
    /// * `request` - The chat completion request to send
    ///
    /// # Returns
    ///
    /// A tuple of (parsed response, stats) extracted from the API response
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - API request fails (network, timeout, rate limit)
    /// - Response cannot be parsed as valid JSON (including truncated responses)
    #[instrument(skip(self, request), fields(provider = self.name(), model = self.model()))]
    async fn send_and_parse<T: serde::de::DeserializeOwned + Send>(
        &self,
        request: &ChatCompletionRequest,
    ) -> Result<(T, AiStats)> {
        use tracing::{info, warn};

        use crate::error::AptuError;
        use crate::retry::{extract_retry_after, is_retryable_anyhow};

        // Check circuit breaker before attempting request
        if let Some(cb) = self.circuit_breaker()
            && cb.is_open()
        {
            return Err(AptuError::CircuitOpen.into());
        }

        // Start timing (outside retry loop to measure total time including retries)
        let start = std::time::Instant::now();

        // Custom retry loop that respects retry_after from RateLimited errors
        let mut attempt: u32 = 0;
        let max_attempts: u32 = self.max_attempts();

        // Helper function to avoid closure-in-expression clippy warning
        #[allow(clippy::items_after_statements)]
        async fn try_request<T: serde::de::DeserializeOwned>(
            provider: &(impl AiProvider + ?Sized),
            request: &ChatCompletionRequest,
        ) -> Result<(T, ChatCompletionResponse)> {
            // Send HTTP request
            let completion = provider.send_request_inner(request).await?;

            // Extract message content
            let content = completion
                .choices
                .first()
                .map(|c| c.message.content.clone())
                .context("No response from AI model")?;

            debug!(response_length = content.len(), "Received AI response");

            // Parse JSON response (inside retry loop, so truncated responses are retried)
            let parsed: T = parse_ai_json(&content, provider.name())?;

            Ok((parsed, completion))
        }

        let (parsed, completion): (T, ChatCompletionResponse) = loop {
            attempt += 1;

            let result = try_request(self, request).await;

            match result {
                Ok(success) => break success,
                Err(err) => {
                    // Check if error is retryable
                    if !is_retryable_anyhow(&err) || attempt >= max_attempts {
                        return Err(err);
                    }

                    // Extract retry_after if present, otherwise use exponential backoff
                    let delay = if let Some(retry_after_duration) = extract_retry_after(&err) {
                        debug!(
                            retry_after_secs = retry_after_duration.as_secs(),
                            "Using Retry-After value from rate limit error"
                        );
                        retry_after_duration
                    } else {
                        // Use exponential backoff with jitter: 1s, 2s, 4s + 0-500ms
                        let backoff_secs = 2_u64.pow(attempt.saturating_sub(1));
                        let jitter_ms = fastrand::u64(0..500);
                        std::time::Duration::from_millis(backoff_secs * 1000 + jitter_ms)
                    };

                    let error_msg = err.to_string();
                    warn!(
                        error = %error_msg,
                        delay_secs = delay.as_secs(),
                        attempt,
                        max_attempts,
                        "Retrying after error"
                    );

                    // Drop err before await to avoid holding non-Send value across await
                    drop(err);
                    tokio::time::sleep(delay).await;
                }
            }
        };

        // Record success in circuit breaker
        if let Some(cb) = self.circuit_breaker() {
            cb.record_success();
        }

        // Calculate duration (total time including any retries)
        #[allow(clippy::cast_possible_truncation)]
        let duration_ms = start.elapsed().as_millis() as u64;

        // Build AI stats from usage info (trust API's cost field)
        let (input_tokens, output_tokens, cost_usd) = if let Some(usage) = completion.usage {
            (usage.prompt_tokens, usage.completion_tokens, usage.cost)
        } else {
            // If no usage info, default to 0
            debug!("No usage information in API response");
            (0, 0, None)
        };

        let ai_stats = AiStats {
            provider: self.name().to_string(),
            model: self.model().to_string(),
            input_tokens,
            output_tokens,
            duration_ms,
            cost_usd,
            fallback_provider: None,
        };

        // Emit structured metrics
        info!(
            duration_ms,
            input_tokens,
            output_tokens,
            cost_usd = ?cost_usd,
            model = %self.model(),
            "AI request completed"
        );

        Ok((parsed, ai_stats))
    }

    /// Analyzes a GitHub issue using the provider's API.
    ///
    /// Returns a structured triage response with summary, labels, questions, duplicates, and usage stats.
    ///
    /// # Arguments
    ///
    /// * `issue` - Issue details to analyze
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - API request fails (network, timeout, rate limit)
    /// - Response cannot be parsed as valid JSON
    #[instrument(skip(self, issue), fields(issue_number = issue.number, repo = %format!("{}/{}", issue.owner, issue.repo)))]
    async fn analyze_issue(&self, issue: &IssueDetails) -> Result<AiResponse> {
        debug!(model = %self.model(), "Calling {} API", self.name());

        // Build request
        let system_content = if let Some(override_prompt) =
            super::context::load_system_prompt_override("triage_system").await
        {
            override_prompt
        } else {
            Self::build_system_prompt(None)
        };

        let request = ChatCompletionRequest {
            model: self.model().to_string(),
            messages: vec![
                ChatMessage {
                    role: "system".to_string(),
                    content: system_content,
                },
                ChatMessage {
                    role: "user".to_string(),
                    content: Self::build_user_prompt(issue),
                },
            ],
            response_format: Some(ResponseFormat {
                format_type: "json_object".to_string(),
                json_schema: None,
            }),
            max_tokens: Some(self.max_tokens()),
            temperature: Some(self.temperature()),
        };

        // Send request and parse JSON with retry logic
        let (triage, ai_stats) = self.send_and_parse::<TriageResponse>(&request).await?;

        debug!(
            input_tokens = ai_stats.input_tokens,
            output_tokens = ai_stats.output_tokens,
            duration_ms = ai_stats.duration_ms,
            cost_usd = ?ai_stats.cost_usd,
            "AI analysis complete"
        );

        Ok(AiResponse {
            triage,
            stats: ai_stats,
        })
    }

    /// Creates a formatted GitHub issue using the provider's API.
    ///
    /// Takes raw issue title and body, formats them using AI (conventional commit style,
    /// structured body), and returns the formatted content with suggested labels.
    ///
    /// # Arguments
    ///
    /// * `title` - Raw issue title from user
    /// * `body` - Raw issue body/description from user
    /// * `repo` - Repository name for context (owner/repo format)
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - API request fails (network, timeout, rate limit)
    /// - Response cannot be parsed as valid JSON
    #[instrument(skip(self), fields(repo = %repo))]
    async fn create_issue(
        &self,
        title: &str,
        body: &str,
        repo: &str,
    ) -> Result<(super::types::CreateIssueResponse, AiStats)> {
        debug!(model = %self.model(), "Calling {} API for issue creation", self.name());

        // Build request
        let system_content = if let Some(override_prompt) =
            super::context::load_system_prompt_override("create_system").await
        {
            override_prompt
        } else {
            Self::build_create_system_prompt(None)
        };

        let request = ChatCompletionRequest {
            model: self.model().to_string(),
            messages: vec![
                ChatMessage {
                    role: "system".to_string(),
                    content: system_content,
                },
                ChatMessage {
                    role: "user".to_string(),
                    content: Self::build_create_user_prompt(title, body, repo),
                },
            ],
            response_format: Some(ResponseFormat {
                format_type: "json_object".to_string(),
                json_schema: None,
            }),
            max_tokens: Some(self.max_tokens()),
            temperature: Some(self.temperature()),
        };

        // Send request and parse JSON with retry logic
        let (create_response, ai_stats) = self
            .send_and_parse::<super::types::CreateIssueResponse>(&request)
            .await?;

        debug!(
            title_len = create_response.formatted_title.len(),
            body_len = create_response.formatted_body.len(),
            labels = create_response.suggested_labels.len(),
            input_tokens = ai_stats.input_tokens,
            output_tokens = ai_stats.output_tokens,
            duration_ms = ai_stats.duration_ms,
            "Issue formatting complete with stats"
        );

        Ok((create_response, ai_stats))
    }

    /// Builds the system prompt for issue triage.
    #[must_use]
    fn build_system_prompt(custom_guidance: Option<&str>) -> String {
        let context = super::context::load_custom_guidance(custom_guidance);
        let schema = "{\n  \"summary\": \"A 2-3 sentence summary of what the issue is about and its impact\",\n  \"suggested_labels\": [\"label1\", \"label2\"],\n  \"clarifying_questions\": [\"question1\", \"question2\"],\n  \"potential_duplicates\": [\"#123\", \"#456\"],\n  \"related_issues\": [\n    {\n      \"number\": 789,\n      \"title\": \"Related issue title\",\n      \"reason\": \"Brief explanation of why this is related\"\n    }\n  ],\n  \"status_note\": \"Optional note about issue status (e.g., claimed, in-progress)\",\n  \"contributor_guidance\": {\n    \"beginner_friendly\": true,\n    \"reasoning\": \"1-2 sentence explanation of beginner-friendliness assessment\"\n  },\n  \"implementation_approach\": \"Optional suggestions for implementation based on repository structure\",\n  \"suggested_milestone\": \"Optional milestone title for the issue\",\n  \"complexity\": {\n    \"level\": \"low|medium|high\",\n    \"estimated_loc\": 150,\n    \"affected_areas\": [\"crates/aptu-core/src/ai/types.rs\"],\n    \"recommendation\": \"Optional decomposition recommendation for high-complexity issues\"\n  }\n}";
        let guidelines = "Reason through each step before producing output.\n\n\
Guidelines:\n\
- summary: Concise explanation of the problem/request and why it matters\n\
- suggested_labels: Prefer labels from the Available Labels list provided. Choose from: bug, enhancement, documentation, question, duplicate, invalid, wontfix. If a more specific label exists in the repository, use it instead of generic ones.\n\
- clarifying_questions: Only include if the issue lacks critical information. Leave empty array if issue is clear. Skip questions already answered in comments.\n\
- potential_duplicates: Only include if you detect likely duplicates from the context. Leave empty array if none. A duplicate is an issue that describes the exact same problem.\n\
- related_issues: Include issues from the search results that are contextually related but NOT duplicates. Provide brief reasoning for each. Leave empty array if none are relevant.\n\
- status_note: Detect if someone has claimed the issue or is working on it. Look for patterns like \"I'd like to work on this\", \"I'll submit a PR\", \"working on this\", or \"@user I've assigned you\". If claimed, set status_note to a brief description (e.g., \"Issue claimed by @username\"). If not claimed, leave as null or empty string.\n\
- contributor_guidance: Assess whether the issue is suitable for beginners. Consider: scope (small, well-defined), file count (few files to modify), required knowledge (no deep expertise needed), clarity (clear problem statement). Set beginner_friendly to true if all factors are favorable. Provide 1-2 sentence reasoning explaining the assessment.\n\
- implementation_approach: Based on the repository structure provided, suggest specific files or modules to modify. Reference the file paths from the repository structure. Be concrete and actionable. Leave as null or empty string if no specific guidance can be provided.\n\
- suggested_milestone: If applicable, suggest a milestone title from the Available Milestones list. Only include if a milestone is clearly relevant to the issue. Leave as null or empty string if no milestone is appropriate.\n\
- complexity: Always populate this field. Set `level` to low/medium/high based on estimated implementation scope: low = small, self-contained change (1-2 files, <100 LOC); medium = moderate change (3-5 files, 100-300 LOC); high = large change (5+ files, 300+ LOC or deep domain knowledge). Populate `affected_areas` with likely file paths from the repository structure. For high complexity, set `recommendation` to a concrete suggestion (e.g. 'Decompose into 3 sub-issues: CLI parsing, AI prompt update, GitHub API integration').\n\
\n\
Be helpful, concise, and actionable. Focus on what a maintainer needs to know.\n\
\n\
## Examples\n\
\n\
### Example 1 (happy path)\n\
Input: Issue titled \"Add dark mode support\" with body describing a UI theme toggle request.\n\
Output:\n\
```json\n\
{\n\
  \"summary\": \"User requests dark mode support with a toggle in settings.\",\n\
  \"suggested_labels\": [\"enhancement\", \"ui\"],\n\
  \"clarifying_questions\": [\"Which components should be themed first?\"],\n\
  \"potential_duplicates\": [],\n\
  \"related_issues\": [],\n\
  \"status_note\": \"Ready for design discussion\",\n\
  \"contributor_guidance\": {\n\
    \"beginner_friendly\": false,\n\
    \"reasoning\": \"Requires understanding of the theme system and CSS. Could span multiple files.\"\n\
  },\n\
  \"implementation_approach\": \"Extend the existing ThemeProvider with a dark variant and persist preference to localStorage.\",\n\
  \"suggested_milestone\": \"v2.0\",\n\
  \"complexity\": {\n\
    \"level\": \"medium\",\n\
    \"estimated_loc\": 120,\n\
    \"affected_areas\": [\"src/theme/ThemeProvider.tsx\", \"src/components/Settings.tsx\"],\n\
    \"recommendation\": null\n\
  }\n\
}\n\
```\n\
\n\
### Example 2 (edge case - vague report)\n\
Input: Issue titled \"it broken\" with empty body.\n\
Output:\n\
```json\n\
{\n\
  \"summary\": \"Vague report with no reproduction steps or context.\",\n\
  \"suggested_labels\": [\"needs-info\"],\n\
  \"clarifying_questions\": [\"What is broken?\", \"Steps to reproduce?\", \"Expected vs actual behavior?\"],\n\
  \"potential_duplicates\": [],\n\
  \"related_issues\": [],\n\
  \"status_note\": \"Blocked on clarification\",\n\
  \"contributor_guidance\": {\n\
    \"beginner_friendly\": false,\n\
    \"reasoning\": \"Issue is too vague to assess or action without clarification.\"\n\
  },\n\
  \"implementation_approach\": \"\",\n\
  \"suggested_milestone\": null,\n\
  \"complexity\": {\n\
    \"level\": \"low\",\n\
    \"estimated_loc\": null,\n\
    \"affected_areas\": [],\n\
    \"recommendation\": null\n\
  }\n\
}\n\
```";
        format!(
            "You are a senior OSS maintainer. Your mission is to produce structured triage output that helps maintainers prioritize and route incoming issues.\n\n{context}\n\nYour response MUST be valid JSON with this exact schema:\n{schema}\n\n{guidelines}"
        )
    }

    /// Builds the user prompt containing the issue details.
    #[must_use]
    fn build_user_prompt(issue: &IssueDetails) -> String {
        use std::fmt::Write;

        let mut prompt = String::new();

        prompt.push_str("<issue_content>\n");
        let _ = writeln!(prompt, "Title: {}\n", issue.title);

        // Truncate body if too long
        let body = if issue.body.len() > MAX_BODY_LENGTH {
            format!(
                "{}...\n[Body truncated - original length: {} chars]",
                &issue.body[..MAX_BODY_LENGTH],
                issue.body.len()
            )
        } else if issue.body.is_empty() {
            "[No description provided]".to_string()
        } else {
            issue.body.clone()
        };
        let _ = writeln!(prompt, "Body:\n{body}\n");

        // Include existing labels
        if !issue.labels.is_empty() {
            let _ = writeln!(prompt, "Existing Labels: {}\n", issue.labels.join(", "));
        }

        // Include recent comments (limited)
        if !issue.comments.is_empty() {
            prompt.push_str("Recent Comments:\n");
            for comment in issue.comments.iter().take(MAX_COMMENTS) {
                let comment_body = if comment.body.len() > 500 {
                    format!("{}...", &comment.body[..500])
                } else {
                    comment.body.clone()
                };
                let _ = writeln!(prompt, "- @{}: {}", comment.author, comment_body);
            }
            prompt.push('\n');
        }

        // Include related issues from search (for context)
        if !issue.repo_context.is_empty() {
            prompt.push_str("Related Issues in Repository (for context):\n");
            for related in issue.repo_context.iter().take(10) {
                let _ = writeln!(
                    prompt,
                    "- #{} [{}] {}",
                    related.number, related.state, related.title
                );
            }
            prompt.push('\n');
        }

        // Include repository structure (source files)
        if !issue.repo_tree.is_empty() {
            prompt.push_str("Repository Structure (source files):\n");
            for path in issue.repo_tree.iter().take(20) {
                let _ = writeln!(prompt, "- {path}");
            }
            prompt.push('\n');
        }

        // Include available labels
        if !issue.available_labels.is_empty() {
            prompt.push_str("Available Labels:\n");
            for label in issue.available_labels.iter().take(MAX_LABELS) {
                let description = if label.description.is_empty() {
                    String::new()
                } else {
                    format!(" - {}", label.description)
                };
                let _ = writeln!(
                    prompt,
                    "- {} (color: #{}){}",
                    label.name, label.color, description
                );
            }
            prompt.push('\n');
        }

        // Include available milestones
        if !issue.available_milestones.is_empty() {
            prompt.push_str("Available Milestones:\n");
            for milestone in issue.available_milestones.iter().take(MAX_MILESTONES) {
                let description = if milestone.description.is_empty() {
                    String::new()
                } else {
                    format!(" - {}", milestone.description)
                };
                let _ = writeln!(prompt, "- {}{}", milestone.title, description);
            }
            prompt.push('\n');
        }

        prompt.push_str("</issue_content>");

        prompt
    }

    /// Builds the system prompt for issue creation/formatting.
    #[must_use]
    fn build_create_system_prompt(custom_guidance: Option<&str>) -> String {
        let context = super::context::load_custom_guidance(custom_guidance);
        format!(
            "You are a senior developer advocate. Your mission is to produce a well-structured, professional GitHub issue from raw user input.\n\n\
{context}\n\n\
Your response MUST be valid JSON with this exact schema:\n\
{{\n  \"formatted_title\": \"Well-formatted issue title following conventional commit style\",\n  \"formatted_body\": \"Professionally formatted issue body with clear sections\",\n  \"suggested_labels\": [\"label1\", \"label2\"]\n}}\n\n\
Reason through each step before producing output.\n\n\
Guidelines:\n\
- formatted_title: Use conventional commit style (e.g., \"feat: add search functionality\", \"fix: resolve memory leak in parser\"). Keep it concise (under 72 characters). No period at the end.\n\
- formatted_body: Structure the body with clear sections:\n  * Start with a brief 1-2 sentence summary if not already present\n  * Use markdown formatting with headers (## Summary, ## Details, ## Steps to Reproduce, ## Expected Behavior, ## Actual Behavior, ## Context, etc.)\n  * Keep sentences clear and concise\n  * Use bullet points for lists\n  * Improve grammar and clarity\n  * Add relevant context if missing\n\
- suggested_labels: Suggest up to 3 relevant GitHub labels. Common ones: bug, enhancement, documentation, question, duplicate, invalid, wontfix. Choose based on the issue content.\n\n\
Be professional but friendly. Maintain the user's intent while improving clarity and structure.\n\n\
## Examples\n\n\
### Example 1 (happy path)\n\
Input: Title \"app crashes\", Body \"when i click login it crashes on android\"\n\
Output:\n\
```json\n\
{{\n  \"formatted_title\": \"fix(auth): app crashes on login on Android\",\n  \"formatted_body\": \"## Description\\nThe app crashes when tapping the login button on Android.\\n\\n## Steps to Reproduce\\n1. Open the app on Android\\n2. Tap the login button\\n\\n## Expected Behavior\\nUser is authenticated and redirected to the home screen.\\n\\n## Actual Behavior\\nApp crashes immediately.\",\n  \"suggested_labels\": [\"bug\", \"android\", \"auth\"]\n}}\n\
```\n\n\
### Example 2 (edge case - already well-formatted)\n\
Input: Title \"feat(api): add pagination to /users endpoint\", Body already has sections.\n\
Output:\n\
```json\n\
{{\n  \"formatted_title\": \"feat(api): add pagination to /users endpoint\",\n  \"formatted_body\": \"## Description\\nAdd cursor-based pagination to the /users endpoint to support large datasets.\\n\\n## Motivation\\nThe endpoint currently returns all users at once, causing timeouts for large datasets.\",\n  \"suggested_labels\": [\"enhancement\", \"api\"]\n}}\n\
```"
        )
    }

    /// Builds the user prompt for issue creation/formatting.
    #[must_use]
    fn build_create_user_prompt(title: &str, body: &str, _repo: &str) -> String {
        format!("Please format this GitHub issue:\n\nTitle: {title}\n\nBody:\n{body}")
    }

    /// Reviews a pull request using the provider's API.
    ///
    /// Analyzes PR metadata and file diffs to provide structured review feedback.
    ///
    /// # Arguments
    ///
    /// * `pr` - Pull request details including files and diffs
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - API request fails (network, timeout, rate limit)
    /// - Response cannot be parsed as valid JSON
    #[instrument(skip(self, pr), fields(pr_number = pr.number, repo = %format!("{}/{}", pr.owner, pr.repo)))]
    async fn review_pr(
        &self,
        pr: &super::types::PrDetails,
    ) -> Result<(super::types::PrReviewResponse, AiStats)> {
        debug!(model = %self.model(), "Calling {} API for PR review", self.name());

        // Build request
        let system_content = if let Some(override_prompt) =
            super::context::load_system_prompt_override("pr_review_system").await
        {
            override_prompt
        } else {
            Self::build_pr_review_system_prompt(None)
        };

        let request = ChatCompletionRequest {
            model: self.model().to_string(),
            messages: vec![
                ChatMessage {
                    role: "system".to_string(),
                    content: system_content,
                },
                ChatMessage {
                    role: "user".to_string(),
                    content: Self::build_pr_review_user_prompt(pr),
                },
            ],
            response_format: Some(ResponseFormat {
                format_type: "json_object".to_string(),
                json_schema: None,
            }),
            max_tokens: Some(self.max_tokens()),
            temperature: Some(self.temperature()),
        };

        // Send request and parse JSON with retry logic
        let (review, ai_stats) = self
            .send_and_parse::<super::types::PrReviewResponse>(&request)
            .await?;

        debug!(
            verdict = %review.verdict,
            input_tokens = ai_stats.input_tokens,
            output_tokens = ai_stats.output_tokens,
            duration_ms = ai_stats.duration_ms,
            "PR review complete with stats"
        );

        Ok((review, ai_stats))
    }

    /// Suggests labels for a pull request using the provider's API.
    ///
    /// Analyzes PR title, body, and file paths to suggest relevant labels.
    ///
    /// # Arguments
    ///
    /// * `title` - Pull request title
    /// * `body` - Pull request description
    /// * `file_paths` - List of file paths changed in the PR
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - API request fails (network, timeout, rate limit)
    /// - Response cannot be parsed as valid JSON
    #[instrument(skip(self), fields(title = %title))]
    async fn suggest_pr_labels(
        &self,
        title: &str,
        body: &str,
        file_paths: &[String],
    ) -> Result<(Vec<String>, AiStats)> {
        debug!(model = %self.model(), "Calling {} API for PR label suggestion", self.name());

        // Build request
        let system_content = if let Some(override_prompt) =
            super::context::load_system_prompt_override("pr_label_system").await
        {
            override_prompt
        } else {
            Self::build_pr_label_system_prompt(None)
        };

        let request = ChatCompletionRequest {
            model: self.model().to_string(),
            messages: vec![
                ChatMessage {
                    role: "system".to_string(),
                    content: system_content,
                },
                ChatMessage {
                    role: "user".to_string(),
                    content: Self::build_pr_label_user_prompt(title, body, file_paths),
                },
            ],
            response_format: Some(ResponseFormat {
                format_type: "json_object".to_string(),
                json_schema: None,
            }),
            max_tokens: Some(self.max_tokens()),
            temperature: Some(self.temperature()),
        };

        // Send request and parse JSON with retry logic
        let (response, ai_stats) = self
            .send_and_parse::<super::types::PrLabelResponse>(&request)
            .await?;

        debug!(
            label_count = response.suggested_labels.len(),
            input_tokens = ai_stats.input_tokens,
            output_tokens = ai_stats.output_tokens,
            duration_ms = ai_stats.duration_ms,
            "PR label suggestion complete with stats"
        );

        Ok((response.suggested_labels, ai_stats))
    }

    /// Builds the system prompt for PR review.
    #[must_use]
    fn build_pr_review_system_prompt(custom_guidance: Option<&str>) -> String {
        let context = super::context::load_custom_guidance(custom_guidance);
        format!(
            "You are a senior software engineer. Your mission is to produce structured, actionable review feedback on a pull request.\n\n\
{context}\n\n\
Your response MUST be valid JSON with this exact schema:\n\
{{\n  \"summary\": \"A 2-3 sentence summary of what the PR does and its impact\",\n  \"verdict\": \"approve|request_changes|comment\",\n  \"strengths\": [\"strength1\", \"strength2\"],\n  \"concerns\": [\"concern1\", \"concern2\"],\n  \"comments\": [\n    {{\n      \"file\": \"path/to/file.rs\",\n      \"line\": 42,\n      \"comment\": \"Specific feedback about this line\",\n      \"severity\": \"info|suggestion|warning|issue\",\n      \"suggested_code\": null\n    }}\n  ],\n  \"suggestions\": [\"suggestion1\", \"suggestion2\"],\n  \"disclaimer\": null\n}}\n\n\
Reason through each step before producing output.\n\n\
Guidelines:\n\
- summary: Concise explanation of the changes and their purpose\n\
- verdict: Use \"approve\" for good PRs, \"request_changes\" for blocking issues, \"comment\" for feedback without blocking\n\
- strengths: What the PR does well (good patterns, clear code, etc.)\n\
- concerns: Potential issues or risks (bugs, performance, security, maintainability)\n\
- comments: Specific line-level feedback. Use severity:\n  - \"info\": Informational, no action needed\n  - \"suggestion\": Optional improvement\n  - \"warning\": Should consider changing\n  - \"issue\": Should be fixed before merge\n  - \"suggested_code\": Optional. Provide replacement lines for a one-click GitHub suggestion block when you have a small, safe, directly applicable fix (1-10 lines). Omit diff markers (+/-). Leave null for refactors, multi-file changes, or uncertain fixes.\n\
- suggestions: General improvements that are not blocking\n\
- disclaimer: Optional field. If the PR involves platform versions (iOS, Android, Node, Rust, Python, Java, etc.), include a disclaimer explaining that platform version validation may be inaccurate due to knowledge cutoffs. Otherwise, set to null.\n\n\
IMPORTANT - Platform Version Exclusions:\n\
DO NOT validate or flag platform versions (iOS, Android, Node, Rust, Python, Java, simulator availability, package versions, framework versions) as concerns or issues. These may be newer than your knowledge cutoff and flagging them creates false positives. If the PR involves platform versions, include a disclaimer field explaining that platform version validation was skipped due to knowledge cutoff limitations. Focus your review on code logic, patterns, and structure instead.\n\n\
Focus on:\n\
1. Correctness: Does the code do what it claims?\n\
2. Security: Any potential vulnerabilities?\n\
3. Performance: Any obvious inefficiencies?\n\
4. Maintainability: Is the code clear and well-structured?\n\
5. Testing: Are changes adequately tested?\n\n\
Be constructive and specific. Explain why something is an issue and how to fix it.\n\n\
## Examples\n\n\
### Example 1 (happy path)\n\
Input: PR adds a retry helper with tests.\n\
Output:\n\
```json\n\
{{\n  \"summary\": \"Adds an exponential-backoff retry helper with unit tests.\",\n  \"verdict\": \"approve\",\n  \"strengths\": [\"Well-tested with happy and error paths\", \"Follows existing error handling patterns\"],\n  \"concerns\": [],\n  \"comments\": [],\n  \"suggestions\": [\"Consider adding a jitter parameter to reduce thundering-herd effects.\"],\n  \"disclaimer\": null\n}}\n\
```\n\n\
### Example 2 (edge case - missing error handling)\n\
Input: PR adds a file parser that uses unwrap().\n\
Output:\n\
```json\n\
{{\n  \"summary\": \"Adds a CSV parser but uses unwrap() on file reads.\",\n  \"verdict\": \"request_changes\",\n  \"strengths\": [\"Covers the happy path\"],\n  \"concerns\": [\"unwrap() on file open will panic on missing files\"],\n  \"comments\": [{{\"file\": \"src/parser.rs\", \"line\": 42, \"severity\": \"high\", \"comment\": \"Replace unwrap() with proper error propagation using ?\", \"suggested_code\": \"        let file = File::open(path)?;\\n\"}}],\n  \"suggestions\": [\"Return Result<_, io::Error> from parse_file instead of panicking.\"],\n  \"disclaimer\": null\n}}\n\
```"
        )
    }

    /// Builds the user prompt for PR review.
    #[must_use]
    fn build_pr_review_user_prompt(pr: &super::types::PrDetails) -> String {
        use std::fmt::Write;

        let mut prompt = String::new();

        prompt.push_str("<pull_request>\n");
        let _ = writeln!(prompt, "Title: {}\n", pr.title);
        let _ = writeln!(prompt, "Branch: {} -> {}\n", pr.head_branch, pr.base_branch);

        // PR description
        let body = if pr.body.is_empty() {
            "[No description provided]".to_string()
        } else if pr.body.len() > MAX_BODY_LENGTH {
            format!(
                "{}...\n[Description truncated - original length: {} chars]",
                &pr.body[..MAX_BODY_LENGTH],
                pr.body.len()
            )
        } else {
            pr.body.clone()
        };
        let _ = writeln!(prompt, "Description:\n{body}\n");

        // File changes with limits
        prompt.push_str("Files Changed:\n");
        let mut total_diff_size = 0;
        let mut files_included = 0;
        let mut files_skipped = 0;

        for file in &pr.files {
            // Check file count limit
            if files_included >= MAX_FILES {
                files_skipped += 1;
                continue;
            }

            let _ = writeln!(
                prompt,
                "- {} ({}) +{} -{}\n",
                file.filename, file.status, file.additions, file.deletions
            );

            // Include patch if available (truncate large patches)
            if let Some(patch) = &file.patch {
                const MAX_PATCH_LENGTH: usize = 2000;
                let patch_content = if patch.len() > MAX_PATCH_LENGTH {
                    format!(
                        "{}...\n[Patch truncated - original length: {} chars]",
                        &patch[..MAX_PATCH_LENGTH],
                        patch.len()
                    )
                } else {
                    patch.clone()
                };

                // Check if adding this patch would exceed total diff size limit
                let patch_size = patch_content.len();
                if total_diff_size + patch_size > MAX_TOTAL_DIFF_SIZE {
                    let _ = writeln!(
                        prompt,
                        "```diff\n[Patch omitted - total diff size limit reached]\n```\n"
                    );
                    files_skipped += 1;
                    continue;
                }

                let _ = writeln!(prompt, "```diff\n{patch_content}\n```\n");
                total_diff_size += patch_size;
            }

            files_included += 1;
        }

        // Add truncation message if files were skipped
        if files_skipped > 0 {
            let _ = writeln!(
                prompt,
                "\n[{files_skipped} files omitted due to size limits (MAX_FILES={MAX_FILES}, MAX_TOTAL_DIFF_SIZE={MAX_TOTAL_DIFF_SIZE})]"
            );
        }

        prompt.push_str("</pull_request>");

        prompt
    }

    /// Builds the system prompt for PR label suggestion.
    #[must_use]
    fn build_pr_label_system_prompt(custom_guidance: Option<&str>) -> String {
        let context = super::context::load_custom_guidance(custom_guidance);
        format!(
            r#"You are a senior open-source maintainer. Your mission is to suggest the most relevant labels for a pull request based on its content.

{context}

Your response MUST be valid JSON with this exact schema:
{{
  "suggested_labels": ["label1", "label2", "label3"]
}}

Response format: json_object

Reason through each step before producing output.

Guidelines:
- suggested_labels: Suggest 1-3 relevant GitHub labels based on the PR content. Common labels include: bug, enhancement, documentation, feature, refactor, performance, security, testing, ci, dependencies. Choose labels that best describe the type of change.
- Focus on the PR title, description, and file paths to determine appropriate labels.
- Prefer specific labels over generic ones when possible.
- Only suggest labels that are commonly used in GitHub repositories.

Be concise and practical.

## Examples

### Example 1 (happy path)
Input: PR adds OAuth2 login flow with tests.
Output:
```json
{{"suggested_labels": ["feature", "auth", "security"]}}
```

### Example 2 (edge case - documentation only PR)
Input: PR fixes typos in README.
Output:
```json
{{"suggested_labels": ["documentation"]}}
```"#
        )
    }

    /// Builds the user prompt for PR label suggestion.
    #[must_use]
    fn build_pr_label_user_prompt(title: &str, body: &str, file_paths: &[String]) -> String {
        use std::fmt::Write;

        let mut prompt = String::new();

        prompt.push_str("<pull_request>\n");
        let _ = writeln!(prompt, "Title: {title}\n");

        // PR description
        let body_content = if body.is_empty() {
            "[No description provided]".to_string()
        } else if body.len() > MAX_BODY_LENGTH {
            format!(
                "{}...\n[Description truncated - original length: {} chars]",
                &body[..MAX_BODY_LENGTH],
                body.len()
            )
        } else {
            body.to_string()
        };
        let _ = writeln!(prompt, "Description:\n{body_content}\n");

        // File paths
        if !file_paths.is_empty() {
            prompt.push_str("Files Changed:\n");
            for path in file_paths.iter().take(20) {
                let _ = writeln!(prompt, "- {path}");
            }
            if file_paths.len() > 20 {
                let _ = writeln!(prompt, "- ... and {} more files", file_paths.len() - 20);
            }
            prompt.push('\n');
        }

        prompt.push_str("</pull_request>");

        prompt
    }

    /// Generate release notes from PR summaries.
    ///
    /// # Arguments
    ///
    /// * `prs` - List of PR summaries to synthesize
    /// * `version` - Version being released
    ///
    /// # Returns
    ///
    /// Structured release notes with theme, highlights, and categorized changes.
    #[instrument(skip(self, prs))]
    async fn generate_release_notes(
        &self,
        prs: Vec<super::types::PrSummary>,
        version: &str,
    ) -> Result<(super::types::ReleaseNotesResponse, AiStats)> {
        let prompt = Self::build_release_notes_prompt(&prs, version);
        let request = ChatCompletionRequest {
            model: self.model().to_string(),
            messages: vec![ChatMessage {
                role: "user".to_string(),
                content: prompt,
            }],
            response_format: Some(ResponseFormat {
                format_type: "json_object".to_string(),
                json_schema: None,
            }),
            temperature: Some(0.7),
            max_tokens: Some(self.max_tokens()),
        };

        let (parsed, ai_stats) = self
            .send_and_parse::<super::types::ReleaseNotesResponse>(&request)
            .await?;

        debug!(
            input_tokens = ai_stats.input_tokens,
            output_tokens = ai_stats.output_tokens,
            duration_ms = ai_stats.duration_ms,
            "Release notes generation complete with stats"
        );

        Ok((parsed, ai_stats))
    }

    /// Build the user prompt for release notes generation.
    #[must_use]
    fn build_release_notes_prompt(prs: &[super::types::PrSummary], version: &str) -> String {
        let pr_list = prs
            .iter()
            .map(|pr| {
                format!(
                    "- #{}: {} (by @{})\n  {}",
                    pr.number,
                    pr.title,
                    pr.author,
                    pr.body.lines().next().unwrap_or("")
                )
            })
            .collect::<Vec<_>>()
            .join("\n");

        format!(
            r#"Generate release notes for version {version} based on these merged PRs:

{pr_list}

Create a curated release notes document with:
1. A theme/title that captures the essence of this release
2. A 1-2 sentence narrative about the release
3. 3-5 highlighted features
4. Categorized changes: Features, Fixes, Improvements, Documentation, Maintenance
5. List of contributors

Follow these conventions:
- No emojis
- Bold feature names with dash separator
- Include PR numbers in parentheses
- Group by user impact, not just commit type
- Filter CI/deps under Maintenance

Your response MUST be valid JSON with this exact schema:
{{
  "theme": "Release theme title",
  "narrative": "1-2 sentence summary",
  "highlights": ["highlight1", "highlight2"],
  "features": ["feature1", "feature2"],
  "fixes": ["fix1", "fix2"],
  "improvements": ["improvement1"],
  "documentation": ["doc change1"],
  "maintenance": ["maintenance1"],
  "contributors": ["@author1", "@author2"]
}}"#
        )
    }
}

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

    struct TestProvider;

    impl AiProvider for TestProvider {
        fn name(&self) -> &'static str {
            "test"
        }

        fn api_url(&self) -> &'static str {
            "https://test.example.com"
        }

        fn api_key_env(&self) -> &'static str {
            "TEST_API_KEY"
        }

        fn http_client(&self) -> &Client {
            unimplemented!()
        }

        fn api_key(&self) -> &SecretString {
            unimplemented!()
        }

        fn model(&self) -> &'static str {
            "test-model"
        }

        fn max_tokens(&self) -> u32 {
            2048
        }

        fn temperature(&self) -> f32 {
            0.3
        }
    }

    #[test]
    fn test_build_system_prompt_contains_json_schema() {
        let prompt = TestProvider::build_system_prompt(None);
        assert!(prompt.contains("summary"));
        assert!(prompt.contains("suggested_labels"));
        assert!(prompt.contains("clarifying_questions"));
        assert!(prompt.contains("potential_duplicates"));
        assert!(prompt.contains("status_note"));
    }

    #[test]
    fn test_build_user_prompt_with_delimiters() {
        let issue = IssueDetails::builder()
            .owner("test".to_string())
            .repo("repo".to_string())
            .number(1)
            .title("Test issue".to_string())
            .body("This is the body".to_string())
            .labels(vec!["bug".to_string()])
            .comments(vec![])
            .url("https://github.com/test/repo/issues/1".to_string())
            .build();

        let prompt = TestProvider::build_user_prompt(&issue);
        assert!(prompt.starts_with("<issue_content>"));
        assert!(prompt.ends_with("</issue_content>"));
        assert!(prompt.contains("Title: Test issue"));
        assert!(prompt.contains("This is the body"));
        assert!(prompt.contains("Existing Labels: bug"));
    }

    #[test]
    fn test_build_user_prompt_truncates_long_body() {
        let long_body = "x".repeat(5000);
        let issue = IssueDetails::builder()
            .owner("test".to_string())
            .repo("repo".to_string())
            .number(1)
            .title("Test".to_string())
            .body(long_body)
            .labels(vec![])
            .comments(vec![])
            .url("https://github.com/test/repo/issues/1".to_string())
            .build();

        let prompt = TestProvider::build_user_prompt(&issue);
        assert!(prompt.contains("[Body truncated"));
        assert!(prompt.contains("5000 chars"));
    }

    #[test]
    fn test_build_user_prompt_empty_body() {
        let issue = IssueDetails::builder()
            .owner("test".to_string())
            .repo("repo".to_string())
            .number(1)
            .title("Test".to_string())
            .body(String::new())
            .labels(vec![])
            .comments(vec![])
            .url("https://github.com/test/repo/issues/1".to_string())
            .build();

        let prompt = TestProvider::build_user_prompt(&issue);
        assert!(prompt.contains("[No description provided]"));
    }

    #[test]
    fn test_build_create_system_prompt_contains_json_schema() {
        let prompt = TestProvider::build_create_system_prompt(None);
        assert!(prompt.contains("formatted_title"));
        assert!(prompt.contains("formatted_body"));
        assert!(prompt.contains("suggested_labels"));
    }

    #[test]
    fn test_build_pr_review_user_prompt_respects_file_limit() {
        use super::super::types::{PrDetails, PrFile};

        let mut files = Vec::new();
        for i in 0..25 {
            files.push(PrFile {
                filename: format!("file{i}.rs"),
                status: "modified".to_string(),
                additions: 10,
                deletions: 5,
                patch: Some(format!("patch content {i}")),
            });
        }

        let pr = PrDetails {
            owner: "test".to_string(),
            repo: "repo".to_string(),
            number: 1,
            title: "Test PR".to_string(),
            body: "Description".to_string(),
            head_branch: "feature".to_string(),
            base_branch: "main".to_string(),
            url: "https://github.com/test/repo/pull/1".to_string(),
            files,
            labels: vec![],
            head_sha: String::new(),
        };

        let prompt = TestProvider::build_pr_review_user_prompt(&pr);
        assert!(prompt.contains("files omitted due to size limits"));
        assert!(prompt.contains("MAX_FILES=20"));
    }

    #[test]
    fn test_build_pr_review_user_prompt_respects_diff_size_limit() {
        use super::super::types::{PrDetails, PrFile};

        // Create patches that will exceed the limit when combined
        // Each patch is ~30KB, so two will exceed 50KB limit
        let patch1 = "x".repeat(30_000);
        let patch2 = "y".repeat(30_000);

        let files = vec![
            PrFile {
                filename: "file1.rs".to_string(),
                status: "modified".to_string(),
                additions: 100,
                deletions: 50,
                patch: Some(patch1),
            },
            PrFile {
                filename: "file2.rs".to_string(),
                status: "modified".to_string(),
                additions: 100,
                deletions: 50,
                patch: Some(patch2),
            },
        ];

        let pr = PrDetails {
            owner: "test".to_string(),
            repo: "repo".to_string(),
            number: 1,
            title: "Test PR".to_string(),
            body: "Description".to_string(),
            head_branch: "feature".to_string(),
            base_branch: "main".to_string(),
            url: "https://github.com/test/repo/pull/1".to_string(),
            files,
            labels: vec![],
            head_sha: String::new(),
        };

        let prompt = TestProvider::build_pr_review_user_prompt(&pr);
        // Both files should be listed
        assert!(prompt.contains("file1.rs"));
        assert!(prompt.contains("file2.rs"));
        // The second patch should be limited - verify the prompt doesn't contain both full patches
        // by checking that the total size is less than what two full 30KB patches would be
        assert!(prompt.len() < 65_000);
    }

    #[test]
    fn test_build_pr_review_user_prompt_with_no_patches() {
        use super::super::types::{PrDetails, PrFile};

        let files = vec![PrFile {
            filename: "file1.rs".to_string(),
            status: "added".to_string(),
            additions: 10,
            deletions: 0,
            patch: None,
        }];

        let pr = PrDetails {
            owner: "test".to_string(),
            repo: "repo".to_string(),
            number: 1,
            title: "Test PR".to_string(),
            body: "Description".to_string(),
            head_branch: "feature".to_string(),
            base_branch: "main".to_string(),
            url: "https://github.com/test/repo/pull/1".to_string(),
            files,
            labels: vec![],
            head_sha: String::new(),
        };

        let prompt = TestProvider::build_pr_review_user_prompt(&pr);
        assert!(prompt.contains("file1.rs"));
        assert!(prompt.contains("added"));
        assert!(!prompt.contains("files omitted"));
    }

    #[test]
    fn test_build_pr_label_system_prompt_contains_json_schema() {
        let prompt = TestProvider::build_pr_label_system_prompt(None);
        assert!(prompt.contains("suggested_labels"));
        assert!(prompt.contains("json_object"));
        assert!(prompt.contains("bug"));
        assert!(prompt.contains("enhancement"));
    }

    #[test]
    fn test_build_pr_label_user_prompt_with_title_and_body() {
        let title = "feat: add new feature";
        let body = "This PR adds a new feature";
        let files = vec!["src/main.rs".to_string(), "tests/test.rs".to_string()];

        let prompt = TestProvider::build_pr_label_user_prompt(title, body, &files);
        assert!(prompt.starts_with("<pull_request>"));
        assert!(prompt.ends_with("</pull_request>"));
        assert!(prompt.contains("feat: add new feature"));
        assert!(prompt.contains("This PR adds a new feature"));
        assert!(prompt.contains("src/main.rs"));
        assert!(prompt.contains("tests/test.rs"));
    }

    #[test]
    fn test_build_pr_label_user_prompt_empty_body() {
        let title = "fix: bug fix";
        let body = "";
        let files = vec!["src/lib.rs".to_string()];

        let prompt = TestProvider::build_pr_label_user_prompt(title, body, &files);
        assert!(prompt.contains("[No description provided]"));
        assert!(prompt.contains("src/lib.rs"));
    }

    #[test]
    fn test_build_pr_label_user_prompt_truncates_long_body() {
        let title = "test";
        let long_body = "x".repeat(5000);
        let files = vec![];

        let prompt = TestProvider::build_pr_label_user_prompt(title, &long_body, &files);
        assert!(prompt.contains("[Description truncated"));
        assert!(prompt.contains("5000 chars"));
    }

    #[test]
    fn test_build_pr_label_user_prompt_respects_file_limit() {
        let title = "test";
        let body = "test";
        let mut files = Vec::new();
        for i in 0..25 {
            files.push(format!("file{i}.rs"));
        }

        let prompt = TestProvider::build_pr_label_user_prompt(title, body, &files);
        assert!(prompt.contains("file0.rs"));
        assert!(prompt.contains("file19.rs"));
        assert!(!prompt.contains("file20.rs"));
        assert!(prompt.contains("... and 5 more files"));
    }

    #[test]
    fn test_build_pr_label_user_prompt_empty_files() {
        let title = "test";
        let body = "test";
        let files: Vec<String> = vec![];

        let prompt = TestProvider::build_pr_label_user_prompt(title, body, &files);
        assert!(prompt.contains("Title: test"));
        assert!(prompt.contains("Description:\ntest"));
        assert!(!prompt.contains("Files Changed:"));
    }

    #[test]
    fn test_parse_ai_json_with_valid_json() {
        #[derive(serde::Deserialize)]
        struct TestResponse {
            message: String,
        }

        let json = r#"{"message": "hello"}"#;
        let result: Result<TestResponse> = parse_ai_json(json, "test-provider");
        assert!(result.is_ok());
        let response = result.unwrap();
        assert_eq!(response.message, "hello");
    }

    #[test]
    fn test_parse_ai_json_with_truncated_json() {
        #[derive(Debug, serde::Deserialize)]
        struct TestResponse {
            message: String,
        }

        let json = r#"{"message": "hello"#;
        let result: Result<TestResponse> = parse_ai_json(json, "test-provider");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string()
                .contains("Truncated response from test-provider")
        );
    }

    #[test]
    fn test_parse_ai_json_with_malformed_json() {
        #[derive(Debug, serde::Deserialize)]
        struct TestResponse {
            message: String,
        }

        let json = r#"{"message": invalid}"#;
        let result: Result<TestResponse> = parse_ai_json(json, "test-provider");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Invalid JSON response from AI"));
    }

    #[test]
    fn test_build_system_prompt_has_senior_persona() {
        let prompt = TestProvider::build_system_prompt(None);
        assert!(
            prompt.contains("You are a senior"),
            "prompt should have senior persona"
        );
        assert!(
            prompt.contains("Your mission is"),
            "prompt should have mission statement"
        );
    }

    #[test]
    fn test_build_system_prompt_has_cot_directive() {
        let prompt = TestProvider::build_system_prompt(None);
        assert!(prompt.contains("Reason through each step before producing output."));
    }

    #[test]
    fn test_build_system_prompt_has_examples_section() {
        let prompt = TestProvider::build_system_prompt(None);
        assert!(prompt.contains("## Examples"));
    }

    #[test]
    fn test_build_create_system_prompt_has_senior_persona() {
        let prompt = TestProvider::build_create_system_prompt(None);
        assert!(
            prompt.contains("You are a senior"),
            "prompt should have senior persona"
        );
        assert!(
            prompt.contains("Your mission is"),
            "prompt should have mission statement"
        );
    }

    #[test]
    fn test_build_pr_review_system_prompt_has_senior_persona() {
        let prompt = TestProvider::build_pr_review_system_prompt(None);
        assert!(
            prompt.contains("You are a senior"),
            "prompt should have senior persona"
        );
        assert!(
            prompt.contains("Your mission is"),
            "prompt should have mission statement"
        );
    }

    #[test]
    fn test_build_pr_label_system_prompt_has_senior_persona() {
        let prompt = TestProvider::build_pr_label_system_prompt(None);
        assert!(
            prompt.contains("You are a senior"),
            "prompt should have senior persona"
        );
        assert!(
            prompt.contains("Your mission is"),
            "prompt should have mission statement"
        );
    }

    #[tokio::test]
    async fn test_load_system_prompt_override_returns_none_when_absent() {
        let result =
            super::super::context::load_system_prompt_override("__nonexistent_test_override__")
                .await;
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_load_system_prompt_override_returns_content_when_present() {
        use std::io::Write;
        let dir = tempfile::tempdir().expect("create tempdir");
        let file_path = dir.path().join("test_override.md");
        let mut f = std::fs::File::create(&file_path).expect("create file");
        writeln!(f, "Custom override content").expect("write file");
        drop(f);

        let content = tokio::fs::read_to_string(&file_path).await.ok();
        assert_eq!(content.as_deref(), Some("Custom override content\n"));
    }
}