use crate::app::AppState;
use chrono::Local;

/// Substitute template variables in commit message template
pub fn substitute_template(template: &str, state: &AppState, user_message: &str) -> String {
    let mut result = template.to_string();
    
    // Replace {message} with user's input
    result = result.replace("{message}", user_message);
    
    // Replace {branch} with current branch name
    let branch = if state.current_branch.is_empty() {
        "main".to_string()
    } else {
        state.current_branch.clone()
    };
    result = result.replace("{branch}", &branch);
    
    // Replace {date} with current date (ISO format)
    let date = Local::now().format("%Y-%m-%d").to_string();
    result = result.replace("{date}", &date);
    
    // Replace {time} with current time
    let time = Local::now().format("%H:%M:%S").to_string();
    result = result.replace("{time}", &time);
    
    // Replace {repo} with repository name (last part of repo_path)
    let repo_name = state.repo_path
        .split('/')
        .last()
        .unwrap_or("repo")
        .to_string();
    result = result.replace("{repo}", &repo_name);
    
    // Replace {files} with number of staged files
    let staged_count = state.status_entries.iter().filter(|e| e.staged).count();
    result = result.replace("{files}", &staged_count.to_string());
    
    result
}

/// Get initial commit message from template (before user input)
pub fn get_template_preview(template: &str, state: &AppState) -> String {
    substitute_template(template, state, "{message}")
}

