use tauri::State;
use std::sync::Arc;
use anyhow::Result;

use crate::data::models::template::{
    Template, ImportTemplateRequest, BatchImportRequest, ImportProgress,
    CreateTemplateRequest, SegmentMatchingRule
};
use crate::business::services::template_service::{TemplateService, TemplateQueryOptions, TemplateListResponse, TemplateAssociations};
use crate::business::services::template_import_service::TemplateImportService;
use crate::business::services::import_queue_manager::{ImportQueueManager, BatchImportProgress};
use crate::infrastructure::database::Database;

/// 模板相关的 Tauri 命令
/// 遵循 Tauri 开发规范的 API 设计原则

#[tauri::command]
pub async fn list_templates(
    options: TemplateQueryOptions,
    database: State<'_, Arc<Database>>,
) -> Result<TemplateListResponse, String> {
    let service = TemplateService::new(database.inner().clone());
    
    service.list_templates(options)
        .await
        .map_err(|e| e.to_string())
}

#[tauri::command]
pub async fn get_template_by_id(
    id: String,
    database: State<'_, Arc<Database>>,
) -> Result<Option<Template>, String> {
    let service = TemplateService::new(database.inner().clone());
    
    service.get_template_by_id(&id)
        .await
        .map_err(|e| e.to_string())
}

#[tauri::command]
pub async fn create_template(
    request: CreateTemplateRequest,
    database: State<'_, Arc<Database>>,
) -> Result<String, String> {
    let service = TemplateService::new(database.inner().clone());
    
    service.create_template(request)
        .await
        .map_err(|e| e.to_string())
}

#[tauri::command]
pub async fn update_template(
    template: Template,
    database: State<'_, Arc<Database>>,
) -> Result<(), String> {
    let service = TemplateService::new(database.inner().clone());
    
    service.update_template(&template)
        .await
        .map_err(|e| e.to_string())
}

#[tauri::command]
pub async fn delete_template(
    id: String,
    database: State<'_, Arc<Database>>,
) -> Result<(), String> {
    let service = TemplateService::new(database.inner().clone());

    service.delete_template(&id)
        .await
        .map_err(|e| e.to_string())
}

/// 硬删除模板及其所有关联数据
#[tauri::command]
pub async fn hard_delete_template(
    id: String,
    database: State<'_, Arc<Database>>,
) -> Result<(), String> {
    let service = TemplateService::new(database.inner().clone());

    service.hard_delete_template(&id)
        .await
        .map_err(|e| e.to_string())
}

/// 验证模板删除后的数据清理完整性
#[tauri::command]
pub async fn verify_template_deletion(
    id: String,
    database: State<'_, Arc<Database>>,
) -> Result<bool, String> {
    let service = TemplateService::new(database.inner().clone());

    service.verify_template_deletion(&id)
        .await
        .map_err(|e| e.to_string())
}

/// 获取模板的关联数据统计信息
#[tauri::command]
pub async fn get_template_associations(
    id: String,
    database: State<'_, Arc<Database>>,
) -> Result<TemplateAssociations, String> {
    let service = TemplateService::new(database.inner().clone());

    service.get_template_associations(&id)
        .await
        .map_err(|e| e.to_string())
}

#[tauri::command]
pub async fn import_template(
    request: ImportTemplateRequest,
    database: State<'_, Arc<Database>>,
) -> Result<String, String> {
    use tracing::info;
    info!("=== 收到模板导入请求 ===");
    info!("文件路径: {}", request.file_path);

    let import_service = TemplateImportService::new(database.inner().clone());
    
    // 创建进度回调（在实际应用中可以通过事件系统发送进度更新）
    let callback = None; // 暂时不使用回调，后续可以通过 Tauri 事件系统实现
    
    import_service.import_template(request, callback)
        .await
        .map_err(|e| e.to_string())
}

#[tauri::command]
pub async fn get_import_progress(
    template_id: String,
    database: State<'_, Arc<Database>>,
) -> Result<Option<ImportProgress>, String> {
    use tracing::info;

    let import_service = TemplateImportService::new(database.inner().clone());
    let progress = import_service.get_import_progress(&template_id).await;

    // 如果进度已完成或失败，返回一次后就清除，避免无限轮询
    if let Some(ref prog) = progress {
        if matches!(prog.status, crate::data::models::template::ImportStatus::Completed | crate::data::models::template::ImportStatus::Failed) {
            // 清除已完成的进度信息
            import_service.clear_import_progress(&template_id).await;
            info!(
                template_id = %template_id,
                status = ?prog.status,
                "进度已完成，清除进度信息"
            );
        }
    }

    info!(
        template_id = %template_id,
        progress_found = %progress.is_some(),
        status = ?progress.as_ref().map(|p| &p.status),
        "获取导入进度"
    );

    Ok(progress)
}

#[tauri::command]
pub async fn cancel_import(
    template_id: String,
    database: State<'_, Arc<Database>>,
) -> Result<(), String> {
    let import_service = TemplateImportService::new(database.inner().clone());
    
    import_service.cancel_import(&template_id)
        .await
        .map_err(|e| e.to_string())
}

// 全局的队列管理器状态
use std::sync::Mutex;
use std::sync::OnceLock;

static QUEUE_MANAGER: OnceLock<Mutex<Option<Arc<ImportQueueManager>>>> = OnceLock::new();

fn get_or_create_queue_manager(database: Arc<Database>) -> Arc<ImportQueueManager> {
    let manager_mutex = QUEUE_MANAGER.get_or_init(|| Mutex::new(None));
    let mut manager_guard = manager_mutex.lock().unwrap();

    if manager_guard.is_none() {
        *manager_guard = Some(Arc::new(ImportQueueManager::new(database, 3)));
    }

    manager_guard.as_ref().unwrap().clone()
}

#[tauri::command]
pub async fn batch_import_templates(
    request: BatchImportRequest,
    database: State<'_, Arc<Database>>,
) -> Result<(), String> {
    let queue_manager = get_or_create_queue_manager(database.inner().clone());
    
    // 扫描文件夹并添加到队列
    queue_manager.scan_and_queue_folder(request)
        .await
        .map_err(|e| e.to_string())?;
    
    // 开始批量处理
    let callback = None; // 暂时不使用回调，后续可以通过 Tauri 事件系统实现
    queue_manager.start_batch_processing(callback)
        .await
        .map_err(|e| e.to_string())
}

#[tauri::command]
pub async fn get_batch_import_progress(
    database: State<'_, Arc<Database>>,
) -> Result<BatchImportProgress, String> {
    let queue_manager = get_or_create_queue_manager(database.inner().clone());
    
    Ok(queue_manager.get_batch_progress().await)
}

#[tauri::command]
pub async fn stop_batch_import(
    database: State<'_, Arc<Database>>,
) -> Result<(), String> {
    let queue_manager = get_or_create_queue_manager(database.inner().clone());
    
    queue_manager.stop_batch_processing()
        .await
        .map_err(|e| e.to_string())
}

#[tauri::command]
pub async fn get_queue_status(
    database: State<'_, Arc<Database>>,
) -> Result<(usize, usize, usize, usize), String> {
    let queue_manager = get_or_create_queue_manager(database.inner().clone());
    
    Ok(queue_manager.get_queue_status().await)
}

#[tauri::command]
pub async fn clear_import_queue(
    database: State<'_, Arc<Database>>,
) -> Result<(), String> {
    let queue_manager = get_or_create_queue_manager(database.inner().clone());
    
    queue_manager.clear_queue()
        .await
        .map_err(|e| e.to_string())
}

/// 验证剪映草稿文件
#[tauri::command]
pub async fn validate_draft_file(
    file_path: String,
) -> Result<bool, String> {
    use crate::business::services::draft_parser::DraftContentParser;
    
    match DraftContentParser::parse_file(&file_path, None) {
        Ok(parse_result) => {
            let errors = DraftContentParser::validate_result(&parse_result);
            Ok(errors.is_empty())
        }
        Err(_) => Ok(false)
    }
}

/// 预览剪映草稿文件信息
#[tauri::command]
pub async fn preview_draft_file(
    file_path: String,
) -> Result<serde_json::Value, String> {
    use crate::business::services::draft_parser::DraftContentParser;
    
    match DraftContentParser::parse_file(&file_path, None) {
        Ok(parse_result) => {
            let preview = serde_json::json!({
                "template_name": parse_result.template.name,
                "duration": parse_result.template.duration,
                "fps": parse_result.template.fps,
                "canvas_config": parse_result.template.canvas_config,
                "materials_count": parse_result.template.materials.len(),
                "tracks_count": parse_result.template.tracks.len(),
                "missing_files": parse_result.missing_files,
                "warnings": parse_result.warnings
            });
            Ok(preview)
        }
        Err(e) => Err(e.to_string())
    }
}

/// 获取文件夹中的草稿文件数量
#[tauri::command]
pub async fn scan_draft_files_count(
    folder_path: String,
) -> Result<usize, String> {
    use std::path::Path;
    use crate::business::services::import_queue_manager::ImportQueueManager;

    let path = Path::new(&folder_path);
    if !path.exists() || !path.is_dir() {
        return Err("指定的路径不存在或不是文件夹".to_string());
    }

    // 使用同步版本的扫描函数
    match ImportQueueManager::scan_draft_files_sync(path) {
        Ok(files) => Ok(files.len()),
        Err(e) => Err(e.to_string())
    }
}

/// 获取模板性能报告
#[tauri::command]
pub async fn get_template_performance_report(
    database: State<'_, Arc<Database>>,
) -> Result<serde_json::Value, String> {
    use crate::business::services::enhanced_template_import_service::EnhancedTemplateImportService;

    let service = EnhancedTemplateImportService::new(database.inner().clone());
    Ok(service.get_performance_report().await)
}

/// 获取缓存统计
#[tauri::command]
pub async fn get_cache_stats(
    database: State<'_, Arc<Database>>,
) -> Result<serde_json::Value, String> {
    use crate::business::services::enhanced_template_import_service::EnhancedTemplateImportService;

    let service = EnhancedTemplateImportService::new(database.inner().clone());
    Ok(service.get_cache_stats().await)
}

/// 预热缓存
#[tauri::command]
pub async fn warm_template_cache(
    template_ids: Vec<String>,
    database: State<'_, Arc<Database>>,
) -> Result<(), String> {
    use crate::business::services::enhanced_template_import_service::EnhancedTemplateImportService;

    let service = EnhancedTemplateImportService::new(database.inner().clone());
    service.warm_cache(template_ids)
        .await
        .map_err(|e| e.to_string())
}

/// 清理模板性能数据
#[tauri::command]
pub async fn cleanup_template_performance_data(
    older_than_hours: u64,
    database: State<'_, Arc<Database>>,
) -> Result<(), String> {
    use crate::business::services::enhanced_template_import_service::EnhancedTemplateImportService;

    let service = EnhancedTemplateImportService::new(database.inner().clone());
    service.cleanup_performance_data(older_than_hours).await;
    Ok(())
}

/// 优化的模板导入
#[tauri::command]
pub async fn import_template_optimized(
    request: ImportTemplateRequest,
    database: State<'_, Arc<Database>>,
) -> Result<String, String> {
    use crate::business::services::enhanced_template_import_service::EnhancedTemplateImportService;

    let service = EnhancedTemplateImportService::new(database.inner().clone());
    service.import_template_optimized(request, None)
        .await
        .map_err(|e| e.to_string())
}

/// 更新轨道片段的匹配规则
#[tauri::command]
pub async fn update_segment_matching_rule(
    segment_id: String,
    matching_rule: SegmentMatchingRule,
    database: State<'_, Arc<Database>>,
) -> Result<(), String> {
    let service = TemplateService::new(database.inner().clone());

    service.update_segment_matching_rule(&segment_id, matching_rule)
        .await
        .map_err(|e| e.to_string())
}

/// 获取轨道片段的匹配规则
#[tauri::command]
pub async fn get_segment_matching_rule(
    segment_id: String,
    database: State<'_, Arc<Database>>,
) -> Result<SegmentMatchingRule, String> {
    let service = TemplateService::new(database.inner().clone());

    service.get_segment_matching_rule(&segment_id)
        .await
        .map_err(|e| e.to_string())
}

/// 选择模板文件命令
#[tauri::command]
pub async fn select_template_file(app: tauri::AppHandle) -> Result<Option<String>, String> {
    use crate::presentation::commands::system_commands::select_file_with_options;
    use crate::business::services::directory_settings_service::DirectorySettingsService;
    use crate::config::DirectorySettingType;

    // 获取默认目录设置
    let service = DirectorySettingsService::new();
    let default_dir = service.get_directory_setting(DirectorySettingType::TemplateImport)
        .unwrap_or(None);

    // 使用带选项的文件选择功能
    let result = select_file_with_options(
        app,
        Some(vec![("剪映草稿文件".to_string(), vec!["json".to_string()])]),
        Some("选择模板文件".to_string()),
        default_dir
    );

    match result {
        Ok(Some(file_path)) => {
            // 如果启用了自动记忆，更新默认目录
            if let Ok(true) = service.is_auto_remember_enabled() {
                if let Some(parent_dir) = std::path::Path::new(&file_path).parent() {
                    let parent_path = parent_dir.to_string_lossy().to_string();
                    let _ = service.update_directory_setting(
                        DirectorySettingType::TemplateImport,
                        parent_path
                    );
                }
            }
            Ok(Some(file_path))
        },
        Ok(None) => Ok(None),
        Err(e) => Err(e),
    }
}