1use super::prompt::{create_system_prompt, create_user_prompt};
2use super::types::GeneratedMessage;
3use crate::config::Config;
4use crate::core::context::CommitContext;
5use crate::core::llm;
6use crate::core::token_optimizer::TokenOptimizer;
7use crate::git::{CommitResult, GitRepo};
8
9use anyhow::Result;
10use log::debug;
11use std::path::Path;
12use std::sync::Arc;
13use tokio::sync::{RwLock, mpsc};
14
15pub struct CommitService {
17 config: Config,
18 repo: Arc<GitRepo>,
19 provider_name: String,
20 verify: bool,
21 cached_context: Arc<RwLock<Option<CommitContext>>>,
22}
23
24impl CommitService {
25 pub fn new(
39 config: Config,
40 _repo_path: &Path,
41 provider_name: &str,
42 verify: bool,
43 git_repo: GitRepo,
44 ) -> Result<Self> {
45 Ok(Self {
46 config,
47 repo: Arc::new(git_repo),
48 provider_name: provider_name.to_string(),
49 verify,
50 cached_context: Arc::new(RwLock::new(None)),
51 })
52 }
53
54 pub fn is_remote_repository(&self) -> bool {
56 self.repo.is_remote()
57 }
58
59 pub fn check_environment(&self) -> Result<()> {
61 self.config.check_environment()
62 }
63
64 pub async fn get_git_info(&self) -> Result<CommitContext> {
66 {
67 let cached_context = self.cached_context.read().await;
68 if let Some(context) = &*cached_context {
69 return Ok(context.clone());
70 }
71 }
72
73 let context = self.repo.get_git_info(&self.config).await?;
74
75 {
76 let mut cached_context = self.cached_context.write().await;
77 *cached_context = Some(context.clone());
78 }
79 Ok(context)
80 }
81
82 pub async fn get_git_info_with_unstaged(
84 &self,
85 include_unstaged: bool,
86 ) -> Result<CommitContext> {
87 if !include_unstaged {
88 return self.get_git_info().await;
89 }
90
91 {
92 let cached_context = self.cached_context.read().await;
95 if let Some(context) = &*cached_context
96 && !include_unstaged
97 {
98 return Ok(context.clone());
99 }
100 }
101
102 let context = self
103 .repo
104 .get_git_info_with_unstaged(&self.config, include_unstaged)
105 .await?;
106
107 if !include_unstaged {
109 let mut cached_context = self.cached_context.write().await;
110 *cached_context = Some(context.clone());
111 }
112
113 Ok(context)
114 }
115
116 #[allow(clippy::unused_async)]
118 pub async fn get_git_info_for_commit(&self, commit_id: &str) -> Result<CommitContext> {
119 debug!("Getting git info for commit: {}", commit_id);
120
121 let context = self.repo.get_git_info_for_commit(&self.config, commit_id)?;
122
123 Ok(context)
125 }
126
127 async fn optimize_prompt<F>(
140 &self,
141 config_clone: &Config,
142 system_prompt: &str,
143 mut context: CommitContext,
144 create_user_prompt_fn: F,
145 ) -> (CommitContext, String)
146 where
147 F: Fn(&CommitContext) -> String,
148 {
149 let token_limit = config_clone
151 .providers
152 .get(&self.provider_name)
153 .and_then(|p| p.token_limit)
154 .unwrap_or({
155 match self.provider_name.as_str() {
156 "openai" => 16_000,
157 "anthropic" => 100_000,
158 "groq" | "openrouter" => 32_000,
159 "google" => 1_000_000,
160 _ => 8_000,
161 }
162 });
163
164 let optimizer = TokenOptimizer::for_counting().expect("Failed to create TokenOptimizer");
166 let system_tokens = optimizer.count_tokens(system_prompt);
167
168 debug!("Token limit: {}", token_limit);
169 debug!("System prompt tokens: {}", system_tokens);
170
171 let context_token_limit = token_limit.saturating_sub(system_tokens + 1000);
174 debug!("Available tokens for context: {}", context_token_limit);
175
176 let user_prompt_before = create_user_prompt_fn(&context);
178 let total_tokens_before = system_tokens + optimizer.count_tokens(&user_prompt_before);
179 debug!("Total tokens before optimization: {}", total_tokens_before);
180
181 context.optimize(context_token_limit, config_clone).await;
183
184 let user_prompt = create_user_prompt_fn(&context);
185 let user_tokens = optimizer.count_tokens(&user_prompt);
186 let total_tokens = system_tokens + user_tokens;
187
188 debug!("User prompt tokens after optimization: {}", user_tokens);
189 debug!("Total tokens after optimization: {}", total_tokens);
190
191 let final_user_prompt = if total_tokens > token_limit {
194 debug!(
195 "Total tokens {} still exceeds limit {}, truncating user prompt",
196 total_tokens, token_limit
197 );
198 let max_user_tokens = token_limit.saturating_sub(system_tokens + 100);
199 optimizer
200 .truncate_string(&user_prompt, max_user_tokens)
201 .expect("Failed to truncate user prompt")
202 } else {
203 user_prompt
204 };
205
206 let final_tokens = system_tokens + optimizer.count_tokens(&final_user_prompt);
207 debug!(
208 "Final total tokens after potential truncation: {}",
209 final_tokens
210 );
211
212 (context, final_user_prompt)
213 }
214
215 pub async fn generate_message(&self, instructions: &str) -> anyhow::Result<GeneratedMessage> {
226 let mut config_clone = self.config.clone();
227
228 config_clone.instructions = instructions.to_string();
229
230 let context = self.get_git_info().await?;
231
232 let system_prompt = create_system_prompt(&config_clone)?;
234
235 let (_, final_user_prompt) = self
237 .optimize_prompt(&config_clone, &system_prompt, context, create_user_prompt)
238 .await;
239
240 let generated_message = llm::get_message::<GeneratedMessage>(
241 &config_clone,
242 &self.provider_name,
243 &system_prompt,
244 &final_user_prompt,
245 )
246 .await?;
247
248 Ok(generated_message)
249 }
250
251 pub async fn generate_pr_for_commit_range(
264 &self,
265 instructions: &str,
266 from: &str,
267 to: &str,
268 ) -> anyhow::Result<super::types::GeneratedPullRequest> {
269 let mut config_clone = self.config.clone();
270
271 config_clone.instructions = instructions.to_string();
272
273 let context = self
275 .repo
276 .get_git_info_for_commit_range(&self.config, from, to)?;
277
278 let commit_messages = self.repo.get_commits_for_pr(from, to)?;
280
281 let system_prompt = super::prompt::create_pr_system_prompt(&config_clone)?;
283
284 let (_, final_user_prompt) = self
286 .optimize_prompt(&config_clone, &system_prompt, context, |ctx| {
287 super::prompt::create_pr_user_prompt(ctx, &commit_messages)
288 })
289 .await;
290
291 let generated_pr = llm::get_message::<super::types::GeneratedPullRequest>(
292 &config_clone,
293 &self.provider_name,
294 &system_prompt,
295 &final_user_prompt,
296 )
297 .await?;
298
299 Ok(generated_pr)
300 }
301
302 pub async fn generate_pr_for_branch_diff(
315 &self,
316 instructions: &str,
317 base_branch: &str,
318 target_branch: &str,
319 ) -> anyhow::Result<super::types::GeneratedPullRequest> {
320 let mut config_clone = self.config.clone();
321
322 config_clone.instructions = instructions.to_string();
323
324 let context =
326 self.repo
327 .get_git_info_for_branch_diff(&self.config, base_branch, target_branch)?;
328
329 let commit_messages = self.repo.get_commits_for_pr(base_branch, target_branch)?;
331
332 let system_prompt = super::prompt::create_pr_system_prompt(&config_clone)?;
334
335 let (_, final_user_prompt) = self
337 .optimize_prompt(&config_clone, &system_prompt, context, |ctx| {
338 super::prompt::create_pr_user_prompt(ctx, &commit_messages)
339 })
340 .await;
341
342 let generated_pr = llm::get_message::<super::types::GeneratedPullRequest>(
343 &config_clone,
344 &self.provider_name,
345 &system_prompt,
346 &final_user_prompt,
347 )
348 .await?;
349
350 Ok(generated_pr)
351 }
352
353 pub fn perform_commit(
363 &self,
364 message: &str,
365 amend: bool,
366 commit_ref: Option<&str>,
367 ) -> Result<CommitResult> {
368 if self.is_remote_repository() {
370 return Err(anyhow::anyhow!("Cannot commit to a remote repository"));
371 }
372
373 debug!(
374 "Performing commit with message: {}, amend: {}, commit_ref: {:?}",
375 message, amend, commit_ref
376 );
377
378 if !self.verify {
379 debug!("Skipping pre-commit hook (verify=false)");
380 if amend {
381 return self
382 .repo
383 .amend_commit(message, commit_ref.unwrap_or("HEAD"));
384 }
385 return self.repo.commit(message);
386 }
387
388 debug!("Executing pre-commit hook");
390 if let Err(e) = self.repo.execute_hook("pre-commit") {
391 debug!("Pre-commit hook failed: {}", e);
392 return Err(e);
393 }
394 debug!("Pre-commit hook executed successfully");
395
396 let commit_result = if amend {
398 self.repo
399 .amend_commit(message, commit_ref.unwrap_or("HEAD"))
400 } else {
401 self.repo.commit(message)
402 };
403
404 match commit_result {
405 Ok(result) => {
406 debug!("Executing post-commit hook");
408 if let Err(e) = self.repo.execute_hook("post-commit") {
409 debug!("Post-commit hook failed: {}", e);
410 }
412 debug!("Commit performed successfully");
413 Ok(result)
414 }
415 Err(e) => {
416 debug!("Commit failed: {}", e);
417 Err(e)
418 }
419 }
420 }
421
422 pub fn pre_commit(&self) -> Result<()> {
424 if self.is_remote_repository() {
426 debug!("Skipping pre-commit hook for remote repository");
427 return Ok(());
428 }
429
430 if self.verify {
431 self.repo.execute_hook("pre-commit")
432 } else {
433 Ok(())
434 }
435 }
436
437 pub fn create_message_channel(
439 &self,
440 ) -> (
441 mpsc::Sender<Result<GeneratedMessage>>,
442 mpsc::Receiver<Result<GeneratedMessage>>,
443 ) {
444 mpsc::channel(1)
445 }
446}