use crate::error::AppError;
use crate::models::agent::Agent;
use crate::models::agent_task::AgentTask;
use crate::models::module::{ProjectModule, MODULE_AGENT_TASK_RUNNER};
use crate::models::project::Project;
use crate::AppState;
use tauri::async_runtime;
use tauri::State;

#[tauri::command]
pub fn create_agent_task(
    state: State<'_, AppState>,
    project_id: String,
    agent_id: String,
    title: String,
    description: String,
) -> Result<AgentTask, AppError> {
    if title.trim().is_empty() {
        return Err(AppError::from(
            "Le titre de la tâche est obligatoire".to_string(),
        ));
    }

    let db = state
        .db
        .lock()
        .map_err(|e| AppError::from(format!("Database lock failed: {}", e)))?;

    let enabled = ProjectModule::is_enabled(&db, &project_id, MODULE_AGENT_TASK_RUNNER)?;
    if !enabled {
        return Err(AppError::from(
            "Le module Agent task runner est désactivé pour ce projet".to_string(),
        ));
    }

    Project::get_by_id(&db, &project_id)?;
    Agent::get_by_id(&db, &agent_id)?;

    let task = AgentTask::insert(
        &db,
        &project_id,
        &agent_id,
        title.trim(),
        description.trim(),
    )?;
    Ok(task)
}

#[tauri::command]
pub fn list_agent_tasks(
    state: State<'_, AppState>,
    project_id: String,
) -> Result<Vec<AgentTask>, AppError> {
    let db = state
        .db
        .lock()
        .map_err(|e| AppError::from(format!("Database lock failed: {}", e)))?;

    let tasks = AgentTask::list_by_project(&db, &project_id)?;
    Ok(tasks)
}

#[tauri::command]
pub fn retry_agent_task(state: State<'_, AppState>, task_id: String) -> Result<(), AppError> {
    let db = state
        .db
        .lock()
        .map_err(|e| AppError::from(format!("Database lock failed: {}", e)))?;

    let task = AgentTask::get_by_id(&db, &task_id)?;
    let enabled = ProjectModule::is_enabled(&db, &task.project_id, MODULE_AGENT_TASK_RUNNER)?;
    if !enabled {
        return Err(AppError::from(
            "Le module Agent task runner est désactivé pour ce projet".to_string(),
        ));
    }

    if task.status != "error" && task.status != "cancelled" && task.status != "done" {
        return Err(AppError::from(format!(
            "Impossible de relancer une tâche avec le statut '{}'",
            task.status
        )));
    }

    AgentTask::retry(&db, &task_id)?;
    Ok(())
}

#[tauri::command]
pub fn cancel_agent_task(state: State<'_, AppState>, task_id: String) -> Result<(), AppError> {
    {
        let db = state
            .db
            .lock()
            .map_err(|e| AppError::from(format!("Database lock failed: {}", e)))?;

        let task = AgentTask::get_by_id(&db, &task_id)?;
        if task.status == "done" || task.status == "cancelled" {
            return Err(AppError::from(format!(
                "Impossible d'annuler une tâche avec le statut '{}'",
                task.status
            )));
        }
    }

    async_runtime::block_on(state.process_registry.cancel_task(&task_id));

    let db = state
        .db
        .lock()
        .map_err(|e| AppError::from(format!("Database lock failed: {}", e)))?;
    let task = AgentTask::get_by_id(&db, &task_id)?;
    if task.status == "done" || task.status == "cancelled" {
        return Err(AppError::from(format!(
            "Impossible d'annuler une tâche avec le statut '{}'",
            task.status
        )));
    }

    AgentTask::cancel(&db, &task_id)?;
    Ok(())
}
