// 导入宏
extern crate lazy_static;

// 四层架构模块定义
pub mod infrastructure;
pub mod data;
pub mod business;
pub mod presentation;

// 应用状态和配置
pub mod app_state;
pub mod config;

use app_state::AppState;
use presentation::commands;
use tauri::Manager;
use infrastructure::logging;
use tracing::info;

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .plugin(tauri_plugin_fs::init())
        .plugin(tauri_plugin_dialog::init())
        .manage(AppState::new())
        .manage(commands::tolerant_json_commands::JsonParserState::new())
        .invoke_handler(tauri::generate_handler![
            commands::project_commands::create_project,
            commands::project_commands::get_all_projects,
            commands::project_commands::get_project_by_id,
            commands::project_commands::update_project,
            commands::project_commands::delete_project,
            commands::project_commands::validate_project_path,
            commands::project_commands::get_default_project_name,
            commands::system_commands::select_directory,
            commands::system_commands::select_file,
            commands::system_commands::open_file_directory,
            commands::system_commands::play_video_segment,
            commands::system_commands::get_app_info,
            commands::system_commands::validate_directory,
            commands::system_commands::get_directory_name,
            commands::system_commands::get_database_info,
            commands::system_commands::get_performance_report,
            commands::system_commands::cleanup_performance_data,
            commands::system_commands::record_performance_metric,
            commands::system_commands::cleanup_invalid_projects,
            commands::database_commands::initialize_database,
            commands::database_commands::check_database_connection,
            commands::database_commands::force_release_database_connection,
            commands::database_commands::get_connection_pool_stats,
            commands::database_commands::test_connection_pool_init,
            commands::database_commands::debug_database_data,
            commands::material_commands::import_materials,
            commands::material_commands::import_materials_async,
            commands::material_commands::select_material_folders,
            commands::material_commands::scan_folder_materials,
            commands::material_commands::get_project_materials,
            commands::material_commands::get_all_materials,
            commands::material_commands::get_material_by_id,
            commands::material_commands::delete_material,
            commands::material_commands::batch_delete_materials,
            commands::material_commands::get_project_material_stats,
            commands::material_commands::batch_process_materials,
            commands::material_commands::update_material_status,
            commands::material_commands::cleanup_invalid_materials,
            commands::material_commands::is_supported_format,
            commands::material_commands::get_supported_extensions,
            commands::material_commands::select_material_files,
            commands::material_commands::validate_material_files,
            commands::material_commands::get_file_info,
            commands::material_commands::check_ffmpeg_available,
            commands::material_commands::get_ffmpeg_version,
            commands::material_commands::get_ffmpeg_status,
            commands::material_commands::extract_file_metadata,
            commands::material_commands::detect_video_scenes,
            commands::material_commands::generate_video_thumbnail,
            commands::material_commands::generate_and_save_segment_thumbnail,
            commands::material_commands::read_thumbnail_as_data_url,
            commands::material_commands::get_material_thumbnail_base64,
            commands::material_commands::get_segment_thumbnail_base64,
            commands::material_commands::get_audio_file_base64,
            commands::material_commands::test_scene_detection,
            commands::material_commands::get_material_segments,
            commands::material_commands::get_material_segment_by_id,
            commands::material_commands::test_video_split,
            commands::material_commands::associate_material_to_model,
            commands::material_commands::disassociate_material_from_model,
            commands::material_commands::get_materials_by_model_id,
            commands::material_commands::get_unassociated_materials,
            commands::material_commands::batch_bind_materials_to_model,
            commands::material_commands::batch_unbind_materials_from_model,
            commands::material_commands::switch_material_model,
            commands::material_commands::get_model_material_statistics,
            commands::material_commands::get_project_model_binding_stats,
            commands::material_commands::get_global_model_binding_stats,
            commands::material_commands::update_material,
            // 模特管理命令
            commands::model_commands::create_model,
            commands::model_commands::get_model_by_id,
            commands::model_commands::get_all_models,
            commands::model_commands::search_models,
            commands::model_commands::update_model,
            commands::model_commands::delete_model,
            commands::model_commands::delete_model_permanently,
            commands::model_commands::add_model_photo,
            commands::model_commands::delete_model_photo,
            commands::model_commands::set_cover_photo,
            commands::model_commands::add_model_tag,
            commands::model_commands::remove_model_tag,
            commands::model_commands::update_model_status,
            commands::model_commands::set_model_rating,
            commands::model_commands::set_model_avatar,
            commands::model_commands::get_model_statistics,
            commands::model_commands::select_photo_files,
            commands::model_commands::select_photo_file,
            // 模特动态管理命令
            commands::model_dynamic_commands::create_model_dynamic,
            commands::model_dynamic_commands::get_model_dynamic_by_id,
            commands::model_dynamic_commands::get_model_dynamics_by_model_id,
            commands::model_dynamic_commands::update_model_dynamic,
            commands::model_dynamic_commands::delete_model_dynamic,
            commands::model_dynamic_commands::get_model_dynamic_stats,
            commands::model_dynamic_commands::regenerate_dynamic_video,
            commands::model_dynamic_commands::get_available_ai_models,
            commands::model_dynamic_commands::update_video_generation_progress,
            commands::model_dynamic_commands::mark_video_generation_failed,
            // AI分类管理命令
            commands::ai_classification_commands::create_ai_classification,
            commands::ai_classification_commands::get_all_ai_classifications,
            commands::ai_classification_commands::get_ai_classification_by_id,
            commands::ai_classification_commands::update_ai_classification,
            commands::ai_classification_commands::delete_ai_classification,
            commands::ai_classification_commands::get_ai_classification_count,
            commands::ai_classification_commands::generate_ai_classification_preview,
            commands::ai_classification_commands::update_ai_classification_sort_orders,
            commands::ai_classification_commands::toggle_ai_classification_status,
            commands::ai_classification_commands::validate_ai_classification_name,
            // AI视频分类命令
            commands::video_classification_commands::start_video_classification,
            commands::video_classification_commands::start_project_batch_classification,
            commands::video_classification_commands::get_classification_queue_status,
            commands::video_classification_commands::get_project_classification_queue_status,
            commands::video_classification_commands::get_classification_task_progress,
            commands::video_classification_commands::get_all_classification_task_progress,
            commands::video_classification_commands::get_project_classification_task_progress,
            commands::video_classification_commands::stop_classification_queue,
            commands::video_classification_commands::recover_stuck_classification_tasks,
            commands::video_classification_commands::pause_classification_queue,
            commands::video_classification_commands::resume_classification_queue,
            commands::video_classification_commands::get_material_classification_records,
            commands::video_classification_commands::get_classification_statistics,
            commands::video_classification_commands::is_segment_classified,
            commands::video_classification_commands::cancel_classification_task,
            commands::video_classification_commands::retry_classification_task,
            commands::video_classification_commands::test_gemini_connection,
            // AI分析日志命令
            commands::ai_analysis_log_commands::get_ai_analysis_logs,
            commands::ai_analysis_log_commands::get_ai_analysis_stats,
            commands::ai_analysis_log_commands::export_ai_analysis_logs,
            commands::ai_analysis_log_commands::cleanup_ai_analysis_logs,
            commands::ai_analysis_log_commands::retry_failed_classification_task,
            commands::ai_analysis_log_commands::get_classification_record_detail,
            commands::ai_analysis_log_commands::delete_classification_records,
            commands::ai_analysis_log_commands::get_ai_analysis_log_filters,
            commands::ai_analysis_log_commands::create_test_ai_analysis_logs,
            // 模板管理命令
            commands::template_commands::list_templates,
            commands::template_commands::get_template_by_id,
            commands::template_commands::create_template,
            commands::template_commands::update_template,
            commands::template_commands::delete_template,
            commands::template_commands::import_template,
            commands::template_commands::get_import_progress,
            commands::template_commands::cancel_import,
            commands::template_commands::batch_import_templates,
            commands::template_commands::get_batch_import_progress,
            commands::template_commands::stop_batch_import,
            commands::template_commands::get_queue_status,
            commands::template_commands::clear_import_queue,
            commands::template_commands::validate_draft_file,
            commands::template_commands::preview_draft_file,
            commands::template_commands::scan_draft_files_count,
            commands::template_commands::get_template_performance_report,
            commands::template_commands::get_cache_stats,
            commands::template_commands::warm_template_cache,
            commands::template_commands::cleanup_template_performance_data,
            commands::template_commands::import_template_optimized,
            commands::template_commands::update_segment_matching_rule,
            commands::template_commands::get_segment_matching_rule,
            // 项目-模板绑定管理命令
            commands::project_template_binding_commands::create_project_template_binding,
            commands::project_template_binding_commands::update_project_template_binding,
            commands::project_template_binding_commands::delete_project_template_binding,
            commands::project_template_binding_commands::delete_project_template_binding_by_ids,
            commands::project_template_binding_commands::get_project_template_binding,
            commands::project_template_binding_commands::list_project_template_bindings,
            commands::project_template_binding_commands::get_templates_by_project,
            commands::project_template_binding_commands::get_projects_by_template,
            commands::project_template_binding_commands::batch_create_project_template_bindings,
            commands::project_template_binding_commands::batch_delete_project_template_bindings,
            commands::project_template_binding_commands::activate_project_template_binding,
            commands::project_template_binding_commands::deactivate_project_template_binding,
            commands::project_template_binding_commands::get_primary_template_binding_for_project,
            commands::project_template_binding_commands::set_primary_template_for_project,
            commands::project_template_binding_commands::check_project_template_binding_exists,
            // 素材匹配命令
            commands::material_matching_commands::execute_material_matching,
            commands::material_matching_commands::execute_material_matching_with_save,
            commands::material_matching_commands::get_project_material_stats_for_matching,
            commands::material_matching_commands::validate_template_binding_for_matching,
            commands::material_matching_commands::batch_match_all_templates,
            // 素材使用记录命令
            commands::material_usage_commands::create_material_usage_record,
            commands::material_usage_commands::create_material_usage_records_batch,
            commands::material_usage_commands::get_project_material_usage_records,
            commands::material_usage_commands::get_matching_result_usage_records,
            commands::material_usage_commands::get_project_material_usage_stats,
            commands::material_usage_commands::get_project_material_usage_overview,
            commands::material_usage_commands::create_usage_records_from_matching_result,
            commands::material_usage_commands::reset_material_segment_usage,
            commands::material_usage_commands::reset_project_material_usage,
            // 模板匹配结果命令
            commands::template_matching_result_commands::save_matching_result,
            commands::template_matching_result_commands::get_matching_result_detail,
            commands::template_matching_result_commands::get_project_matching_results,
            commands::template_matching_result_commands::get_template_matching_results,
            commands::template_matching_result_commands::get_binding_matching_results,
            commands::template_matching_result_commands::list_matching_results,
            commands::template_matching_result_commands::delete_matching_result,
            commands::template_matching_result_commands::soft_delete_matching_result,
            commands::template_matching_result_commands::batch_delete_matching_results,
            commands::template_matching_result_commands::batch_soft_delete_matching_results,
            commands::template_matching_result_commands::batch_delete_matching_results_with_usage_reset,
            commands::template_matching_result_commands::batch_soft_delete_matching_results_with_usage_reset,
            commands::template_matching_result_commands::reset_matching_result_export_status,
            commands::template_matching_result_commands::update_matching_result_info,
            commands::template_matching_result_commands::set_matching_result_quality_score,
            commands::template_matching_result_commands::get_matching_statistics,
            commands::template_matching_result_commands::create_matching_result,
            commands::template_matching_result_commands::get_matching_result_by_id,
            commands::template_matching_result_commands::get_matching_result_status_options,
            commands::template_matching_result_commands::export_matching_result_to_jianying,
            commands::template_matching_result_commands::export_matching_result_to_jianying_v2,
            // 导出记录命令
            commands::export_record_commands::get_export_record,
            commands::export_record_commands::list_export_records,
            commands::export_record_commands::get_project_export_records,
            commands::export_record_commands::get_matching_result_export_records,
            commands::export_record_commands::delete_export_record,
            commands::export_record_commands::get_project_export_statistics,
            commands::export_record_commands::get_global_export_statistics,
            commands::export_record_commands::validate_export_file,
            commands::export_record_commands::cleanup_expired_export_records,
            commands::export_record_commands::re_export_record,
            // MaterialSegment聚合视图命令
            commands::material_segment_view_commands::get_project_segment_view,
            commands::material_segment_view_commands::get_project_segment_view_with_query,
            // 视频生成命令
            commands::video_generation_commands::create_video_generation_task,
            commands::video_generation_commands::execute_video_generation_task,
            commands::video_generation_commands::get_video_generation_task,
            commands::video_generation_commands::get_video_generation_tasks,
            commands::video_generation_commands::cancel_video_generation_task,
            commands::video_generation_commands::delete_video_generation_task,
            commands::video_generation_commands::retry_video_generation_task,
            commands::video_generation_commands::get_model_video_generation_statistics,
            commands::video_generation_commands::get_model_detail_with_photos,
            commands::video_generation_commands::batch_upload_model_photos,
            // 测试命令
            commands::test_commands::test_database_connection,
            commands::test_commands::test_template_table,
            commands::test_commands::test_logging,
            // 调试命令
            commands::debug_commands::test_parse_draft_file,
            commands::debug_commands::validate_template_structure,
            // 便捷工具命令
            commands::tools_commands::clean_jsonl_data,
            // 服装搭配搜索命令
            commands::outfit_search_commands::analyze_outfit_image,
            commands::outfit_search_commands::search_similar_outfits,
            commands::outfit_search_commands::ask_llm_outfit_advice,
            commands::outfit_search_commands::get_outfit_search_suggestions,
            commands::outfit_search_commands::generate_search_config_from_analysis,
            commands::outfit_search_commands::validate_outfit_image,
            commands::outfit_search_commands::get_supported_image_formats,
            commands::outfit_search_commands::get_default_search_config,
            commands::outfit_search_commands::get_outfit_search_config,
            // 自定义标签管理命令
            commands::custom_tag_commands::get_custom_tag_categories,
            commands::custom_tag_commands::create_custom_tag_category,
            commands::custom_tag_commands::update_custom_tag_category,
            commands::custom_tag_commands::delete_custom_tag_category,
            commands::custom_tag_commands::get_custom_tags,
            commands::custom_tag_commands::create_custom_tag,
            commands::custom_tag_commands::update_custom_tag,
            commands::custom_tag_commands::delete_custom_tag,
            commands::custom_tag_commands::add_entity_tag,
            commands::custom_tag_commands::remove_entity_tag,
            commands::custom_tag_commands::get_entity_tags,
            commands::custom_tag_commands::get_tag_statistics,
            commands::custom_tag_commands::batch_add_entity_tags,
            commands::custom_tag_commands::batch_remove_entity_tags,
            // 容错JSON解析器命令
            commands::tolerant_json_commands::parse_json_tolerant,
            commands::tolerant_json_commands::validate_json_format,
            commands::tolerant_json_commands::format_json_text,
            commands::tolerant_json_commands::get_recovery_strategies,
            commands::tolerant_json_commands::get_default_parser_config,
            // RAG Grounding命令
            commands::rag_grounding_commands::query_rag_grounding,
            commands::rag_grounding_commands::test_rag_grounding_connection,
            commands::rag_grounding_commands::get_rag_grounding_config,
            // 多轮对话命令
            commands::conversation_commands::create_conversation_session,
            commands::conversation_commands::get_conversation_session,
            commands::conversation_commands::get_conversation_history,
            commands::conversation_commands::get_conversation_sessions,
            commands::conversation_commands::delete_conversation_session,
            commands::conversation_commands::add_conversation_message,
            commands::conversation_commands::process_multi_turn_conversation,
            commands::conversation_commands::get_conversation_stats,
            commands::conversation_commands::cleanup_expired_sessions,
            commands::conversation_commands::update_session_title,
            commands::conversation_commands::generate_session_summary
        ])
        .setup(|app| {
            // 初始化日志系统
            let mut log_config = logging::LogConfig::default();
            log_config.level = tracing::Level::INFO; // 设置为 INFO 级别以减少日志噪音
            if let Err(e) = logging::init_logging(log_config) {
                eprintln!("日志系统初始化失败: {}", e);
            }

            info!("MixVideo Desktop 应用启动");

            // 初始化应用状态
            let app_handle = app.handle();
            let state: tauri::State<AppState> = app_handle.state();

            // 初始化数据库
            if let Err(e) = state.initialize_database() {
                eprintln!("Failed to initialize database: {}", e);
                return Err(e.into());
            }

            // 同时管理 Database 实例供模板命令使用
            let database = state.get_database();
            app.manage(database);

            // 发布应用启动事件
            let event_bus_manager = state.event_bus_manager.clone();
            tauri::async_runtime::spawn(async move {
                let _ = event_bus_manager.publish_app_started().await;
            });

            // 记录启动性能指标
            {
                let mut monitor = state.performance_monitor.lock().unwrap();
                monitor.record_metric("startup_time_ms", 0.0); // 实际应该测量真实启动时间
            }

            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

#[cfg(test)]
mod tests {
    mod batch_delete_test;
    mod material_matching_service_test;
}


