use std::path::Path;
use aurora_core::{Command, CommandCategory, Pipeline, Engine, AuroraResult, AuroraError};
use crate::analyzer;
use crate::suggestions;

pub struct AutoDebugEngine;

impl Engine for AutoDebugEngine {
    fn name(&self) -> &'static str { "autodebug" }

    fn can_handle(&self, cmd: &Command) -> bool {
        matches!(cmd.category, CommandCategory::AutoDebug)
    }

    fn execute(&self, cmd: &Command, _input: &Pipeline) -> AuroraResult<Pipeline> {
        match cmd.action.as_str() {
            "analyze" => {
                let target = cmd.args.first().ok_or_else(|| {
                    AuroraError::InvalidInput("Specify target to analyze (file, PID)".to_string())
                })?;
                analyzer::analyze_target(target)
            }
            "log" => {
                let path = cmd.args.first().map(|s| s.as_str()).unwrap_or(".");
                let path_str = path.to_string();

                if Path::new(&path_str).is_file() {
                    analyzer::analyze_log_file(&path_str)
                } else {
                    let logs = analyzer::find_log_files(&path_str);
                    if logs.is_empty() {
                        Ok(Pipeline::single(
                            aurora_core::Value::String("No .log files found.".to_string())
                        ))
                    } else {
                        analyzer::analyze_log_file(&logs[0])
                    }
                }
            }
            "suggest" => {
                let errors = &cmd.args;
                if errors.is_empty() {
                    return Err(AuroraError::InvalidInput(
                        "Specify error messages to get suggestions".to_string()
                    ));
                }
                suggestions::suggest_fix(errors)
            }
            _ => Err(AuroraError::CommandNotFound(
                format!("autodebug.{}", cmd.action)
            )),
        }
    }
}
