use std::path::Path;
use std::sync::Arc;

use crate::browser::BrowserBackend;
use crate::compat::config_adapter::resolve_skills_dir_from_sgclaw_settings;
use crate::compat::runtime::CompatTaskContext;
use crate::config::SgClawSettings;
use crate::pipe::{BrowserPipeTool, PipeError, Transport};

pub fn should_use_primary_orchestration(
    instruction: &str,
    page_url: Option<&str>,
    page_title: Option<&str>,
) -> bool {
    if crate::compat::workflow_executor::detect_route(instruction, page_url, page_title)
        .is_some_and(|route| crate::compat::workflow_executor::prefers_direct_execution(&route))
    {
        return true;
    }

    let normalized = instruction.to_ascii_lowercase();
    let needs_export = normalized.contains("excel")
        || normalized.contains("xlsx")
        || instruction.contains("导出")
        || instruction.contains("大屏")
        || instruction.contains("新标签页")
        || normalized.contains("dashboard");

    crate::runtime::is_zhihu_hotlist_task(instruction, page_url, page_title) && needs_export
}

pub fn execute_task_with_browser_backend(
    transport: &dyn crate::agent::AgentEventSink,
    browser_backend: Arc<dyn BrowserBackend>,
    instruction: &str,
    task_context: &CompatTaskContext,
    workspace_root: &Path,
    settings: &SgClawSettings,
) -> Result<String, PipeError> {
    let skills_dir = resolve_skills_dir_from_sgclaw_settings(workspace_root, settings);
    let route = crate::compat::workflow_executor::detect_route(
        instruction,
        task_context.page_url.as_deref(),
        task_context.page_title.as_deref(),
    );
    if let Some(route) = route.clone() {
        if crate::compat::workflow_executor::prefers_direct_execution(&route) {
            return crate::compat::workflow_executor::execute_route_with_browser_backend(
                transport,
                browser_backend.clone(),
                workspace_root,
                &skills_dir,
                instruction,
                task_context,
                route,
                settings,
            );
        }
    }
    let primary_result = crate::compat::runtime::execute_task_with_browser_backend(
        transport,
        browser_backend.clone(),
        instruction,
        task_context,
        workspace_root,
        settings,
    );

    match (route, primary_result) {
        (Some(route), Ok(summary))
            if crate::compat::workflow_executor::should_fallback_after_summary(
                &summary, &route,
            ) =>
        {
            crate::compat::workflow_executor::execute_route_with_browser_backend(
                transport,
                browser_backend,
                workspace_root,
                &skills_dir,
                instruction,
                task_context,
                route,
                settings,
            )
        }
        (_, Ok(summary)) => Ok(summary),
        (Some(route), Err(_)) => crate::compat::workflow_executor::execute_route_with_browser_backend(
            transport,
            browser_backend,
            workspace_root,
            &skills_dir,
            instruction,
            task_context,
            route,
            settings,
        ),
        (None, Err(err)) => Err(err),
    }
}

pub fn execute_task_with_sgclaw_settings<T: Transport + 'static>(
    transport: &T,
    browser_tool: BrowserPipeTool<T>,
    instruction: &str,
    task_context: &CompatTaskContext,
    workspace_root: &Path,
    settings: &SgClawSettings,
) -> Result<String, PipeError> {
    let skills_dir = resolve_skills_dir_from_sgclaw_settings(workspace_root, settings);
    let route = crate::compat::workflow_executor::detect_route(
        instruction,
        task_context.page_url.as_deref(),
        task_context.page_title.as_deref(),
    );
    if let Some(route) = route.clone() {
        if crate::compat::workflow_executor::prefers_direct_execution(&route) {
            return crate::compat::workflow_executor::execute_route(
                transport,
                &browser_tool,
                workspace_root,
                &skills_dir,
                instruction,
                task_context,
                route,
                settings,
            );
        }
    }
    let primary_result = crate::compat::runtime::execute_task_with_sgclaw_settings(
        transport,
        browser_tool.clone(),
        instruction,
        task_context,
        workspace_root,
        settings,
    );

    match (route, primary_result) {
        (Some(route), Ok(summary))
            if crate::compat::workflow_executor::should_fallback_after_summary(
                &summary, &route,
            ) =>
        {
            crate::compat::workflow_executor::execute_route(
                transport,
                &browser_tool,
                workspace_root,
                &skills_dir,
                instruction,
                task_context,
                route,
                settings,
            )
        }
        (_, Ok(summary)) => Ok(summary),
        (Some(route), Err(_)) => crate::compat::workflow_executor::execute_route(
            transport,
            &browser_tool,
            workspace_root,
            &skills_dir,
            instruction,
            task_context,
            route,
            settings,
        ),
        (None, Err(err)) => Err(err),
    }
}
