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::services::agent_runtime;
use crate::services::process_registry::ProcessRegistry;
use rusqlite::Connection;
use std::sync::{Arc, Mutex};
use tauri::{AppHandle, Emitter};
use tokio::time::{interval, Duration};

fn build_task_prompt(task: &AgentTask, project: &Project) -> String {
    format!(
        r#"Tu es un agent d'exécution de tâches pour un projet logiciel.

## Projet
- Nom: {project_name}
- Chemin repo: {project_path}
- Branche de base: {base_branch}

## Tâche
- Titre: {task_title}
- Description:
{task_description}

## Attendu
1. Exécute la tâche dans le contexte du dépôt.
2. Fais des changements concrets si nécessaire.
3. Donne un rapport final en markdown:
   - Résumé
   - Changements
   - Vérifications faites
   - Risques / suites
"#,
        project_name = project.name,
        project_path = project.path,
        base_branch = project.base_branch,
        task_title = task.title,
        task_description = task.description,
    )
}

fn emit_status(
    app_handle: &AppHandle,
    project_id: &str,
    task_id: &str,
    status: &str,
    error: Option<&str>,
) {
    let _ = app_handle.emit(
        "agent-task-updated",
        serde_json::json!({
            "project_id": project_id,
            "task_id": task_id,
            "status": status,
            "error": error,
        }),
    );
}

async fn process_next_task(
    db: &Arc<Mutex<Connection>>,
    app_handle: &AppHandle,
    process_registry: &ProcessRegistry,
) -> Result<bool, String> {
    let next_task = {
        let conn = db.lock().map_err(|e| format!("DB lock failed: {}", e))?;
        let pending = AgentTask::list_pending(&conn)
            .map_err(|e| format!("list pending tasks failed: {}", e))?;

        let mut selected = None;
        for task in pending {
            let enabled =
                ProjectModule::is_enabled(&conn, &task.project_id, MODULE_AGENT_TASK_RUNNER)
                    .map_err(|e| format!("task module lookup failed: {}", e))?;
            if enabled {
                selected = Some(task);
                break;
            }
        }

        selected
    };

    let task = match next_task {
        Some(task) => task,
        None => return Ok(false),
    };

    let (project, agent) = {
        let conn = db.lock().map_err(|e| format!("DB lock failed: {}", e))?;

        AgentTask::mark_running(&conn, &task.id)
            .map_err(|e| format!("mark task running failed: {}", e))?;
        let project = Project::get_by_id(&conn, &task.project_id)
            .map_err(|e| format!("project lookup failed: {}", e))?;
        let agent = Agent::get_by_id(&conn, &task.agent_id)
            .map_err(|e| format!("agent lookup failed: {}", e))?;

        (project, agent)
    };

    emit_status(app_handle, &task.project_id, &task.id, "running", None);

    let prompt = build_task_prompt(&task, &project);
    let args = agent.tool.to_non_interactive_args();
    let result = agent_runtime::run_agent_command_for_task(
        agent.tool.to_command(),
        &args,
        &prompt,
        &project.path,
        900,
        process_registry,
        &task.id,
    )
    .await;

    match result {
        Ok(report) => {
            let current = {
                let conn = db.lock().map_err(|e| format!("DB lock failed: {}", e))?;
                AgentTask::get_by_id(&conn, &task.id)
                    .map_err(|e| format!("task lookup failed: {}", e))?
            };
            if current.status == "cancelled" {
                emit_status(app_handle, &task.project_id, &task.id, "cancelled", None);
                return Ok(true);
            }

            let conn = db.lock().map_err(|e| format!("DB lock failed: {}", e))?;
            AgentTask::mark_done(&conn, &task.id, &report)
                .map_err(|e| format!("mark task done failed: {}", e))?;
            emit_status(app_handle, &task.project_id, &task.id, "done", None);
        }
        Err(error) => {
            let current = {
                let conn = db.lock().map_err(|e| format!("DB lock failed: {}", e))?;
                AgentTask::get_by_id(&conn, &task.id)
                    .map_err(|e| format!("task lookup failed: {}", e))?
            };
            if current.status == "cancelled" {
                emit_status(app_handle, &task.project_id, &task.id, "cancelled", None);
                return Ok(true);
            }

            let conn = db.lock().map_err(|e| format!("DB lock failed: {}", e))?;
            AgentTask::mark_error(&conn, &task.id, &error)
                .map_err(|e| format!("mark task error failed: {}", e))?;
            emit_status(
                app_handle,
                &task.project_id,
                &task.id,
                "error",
                Some(&error),
            );
        }
    }

    Ok(true)
}

pub fn start(db: Arc<Mutex<Connection>>, app_handle: AppHandle, process_registry: ProcessRegistry) {
    tauri::async_runtime::spawn(async move {
        let mut tick = interval(Duration::from_secs(8));
        loop {
            tick.tick().await;
            match process_next_task(&db, &app_handle, &process_registry).await {
                Ok(true) => continue,
                Ok(false) => {}
                Err(e) => {
                    eprintln!("task_runner: {}", e);
                }
            }
        }
    });
}
