use crate::agent::jobs::{
    BackgroundJobSnapshot, CancelBackgroundJobRequest, StartBackgroundJobRequest,
};
use crate::agent::TaskProfile;
use crate::state::AppState;

#[tauri::command]
pub async fn start_background_job(
    state: tauri::State<'_, AppState>,
    request: StartBackgroundJobRequest,
) -> Result<BackgroundJobSnapshot, String> {
    let (runtime, gateway) = {
        let agent = state.agent.lock().await;
        let config_status = agent.get_config_status().map_err(|e| e.to_string())?;
        if !config_status.configured {
            return Err(
                "AI provider is not configured. Configure a provider in AI Settings first."
                    .to_string(),
            );
        }
        drop(config_status);
        let runtime = agent
            .resolve_runtime_for_job(Some(TaskProfile::Analysis))
            .map_err(|e| e.to_string())?;
        let gateway = agent.gateway();
        (runtime, gateway)
    };

    drop(gateway);

    state
        .background_jobs
        .start_job(request, runtime, TaskProfile::Analysis)
        .map_err(|error| error.to_string())
}

#[tauri::command]
pub async fn get_background_job_status(
    state: tauri::State<'_, AppState>,
    job_id: String,
) -> Result<BackgroundJobSnapshot, String> {
    state
        .background_jobs
        .get_job_status(&job_id)
        .map_err(|error| error.to_string())
}

#[tauri::command]
pub async fn cancel_background_job(
    state: tauri::State<'_, AppState>,
    request: CancelBackgroundJobRequest,
) -> Result<(), String> {
    state
        .background_jobs
        .cancel_job(&request.job_id)
        .map_err(|error| error.to_string())
}
