//! ComfyUI 数据访问层
//! 提供对 ComfyUI 相关数据的 CRUD 操作

use anyhow::{Result, anyhow};
use rusqlite::{Connection, params, Row};
use serde_json;
use std::collections::HashMap;
use std::sync::Arc;
use tracing::{info, warn, error, debug};

use crate::data::models::comfyui::{
    WorkflowModel, TemplateModel, ExecutionModel, QueueModel, ComfyUIConfig,
    ExecutionStatus, QueueStatistics
};

/// ComfyUI 数据仓库
pub struct ComfyUIRepository {
    database: Arc<crate::infrastructure::database::Database>,
}

impl ComfyUIRepository {
    /// 创建新的数据仓库实例
    pub fn new(database: Arc<crate::infrastructure::database::Database>) -> Self {
        Self { database }
    }

    /// 获取数据库连接（优先使用连接池）
    fn get_connection(&self) -> Result<crate::infrastructure::database::ConnectionHandle> {
        // 优先使用连接池，如果没有连接池则使用普通连接
        if self.database.has_pool() {
            self.database.get_best_connection()
        } else {
            warn!("ComfyUI Repository 使用单连接模式，性能可能受限");
            self.database.get_best_connection()
        }
    }

    /// 执行数据库操作的辅助方法
    fn with_connection<F, R>(&self, f: F) -> Result<R>
    where
        F: FnOnce(&Connection) -> Result<R>,
    {
        let mut conn = self.get_connection()?;
        f(&*conn)
    }

    /// 初始化数据库表（现在通过主数据库的migration系统处理）
    pub fn initialize(&self) -> Result<()> {
        // ComfyUI表现在通过主数据库的migration系统创建
        // 这里只需要确保连接可用
        match self.with_connection(|_conn| {
            info!("ComfyUI 数据仓库初始化完成");
            Ok(())
        }) {
            Ok(result) => Ok(result),
            Err(e) => {
                warn!("ComfyUI 数据仓库初始化警告: {}", e);
                // 即使连接有问题，也不阻止应用启动
                Ok(())
            }
        }
    }

    // ==================== 工作流相关操作 ====================

    /// 创建工作流
    pub fn create_workflow(&self, workflow: &WorkflowModel) -> Result<()> {
        self.with_connection(|conn| {
            let workflow_data_json = serde_json::to_string(&workflow.workflow_data)?;
            let tags_json = serde_json::to_string(&workflow.tags)?;

            conn.execute(
                "INSERT INTO comfyui_workflows (id, name, description, workflow_data, version, created_at, updated_at, enabled, tags, category)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
                params![
                    workflow.id,
                    workflow.name,
                    workflow.description,
                    workflow_data_json,
                    workflow.version,
                    workflow.created_at,
                    workflow.updated_at,
                    workflow.enabled,
                    tags_json,
                    workflow.category
                ],
            )?;

            debug!("创建工作流: {}", workflow.id);
            Ok(())
        })
    }

    /// 获取工作流
    pub fn get_workflow(&self, id: &str) -> Result<Option<WorkflowModel>> {
        let mut conn = self.get_connection()?;
        
        let mut stmt = conn.prepare(
            "SELECT id, name, description, workflow_data, version, created_at, updated_at, enabled, tags, category
             FROM comfyui_workflows WHERE id = ?1"
        )?;
        
        let workflow_iter = stmt.query_map([id], |row| {
            self.row_to_workflow_model(row)
        })?;
        
        for workflow in workflow_iter {
            return Ok(Some(workflow?));
        }
        
        Ok(None)
    }

    /// 获取所有工作流
    pub fn list_workflows(&self, enabled_only: bool) -> Result<Vec<WorkflowModel>> {
        let mut conn = self.get_connection()?;
        
        let sql = if enabled_only {
            "SELECT id, name, description, workflow_data, version, created_at, updated_at, enabled, tags, category
             FROM comfyui_workflows WHERE enabled = 1 ORDER BY created_at DESC"
        } else {
            "SELECT id, name, description, workflow_data, version, created_at, updated_at, enabled, tags, category
             FROM comfyui_workflows ORDER BY created_at DESC"
        };
        
        let mut stmt = conn.prepare(sql)?;
        let workflow_iter = stmt.query_map([], |row| {
            self.row_to_workflow_model(row)
        })?;
        
        let mut workflows = Vec::new();
        for workflow in workflow_iter {
            workflows.push(workflow?);
        }
        
        Ok(workflows)
    }

    /// 更新工作流
    pub fn update_workflow(&self, workflow: &WorkflowModel) -> Result<()> {
        let mut conn = self.get_connection()?;
        
        let workflow_data_json = serde_json::to_string(&workflow.workflow_data)?;
        let tags_json = serde_json::to_string(&workflow.tags)?;
        
        let rows_affected = conn.execute(
            "UPDATE comfyui_workflows 
             SET name = ?2, description = ?3, workflow_data = ?4, version = ?5, updated_at = ?6, enabled = ?7, tags = ?8, category = ?9
             WHERE id = ?1",
            params![
                workflow.id,
                workflow.name,
                workflow.description,
                workflow_data_json,
                workflow.version,
                workflow.updated_at,
                workflow.enabled,
                tags_json,
                workflow.category
            ],
        )?;
        
        if rows_affected == 0 {
            return Err(anyhow!("工作流不存在: {}", workflow.id));
        }
        
        debug!("更新工作流: {}", workflow.id);
        Ok(())
    }

    /// 删除工作流
    pub fn delete_workflow(&self, id: &str) -> Result<()> {
        let mut conn = self.get_connection()?;
        
        let rows_affected = conn.execute("DELETE FROM comfyui_workflows WHERE id = ?1", [id])?;
        
        if rows_affected == 0 {
            return Err(anyhow!("工作流不存在: {}", id));
        }
        
        debug!("删除工作流: {}", id);
        Ok(())
    }

    /// 按分类获取工作流
    pub fn get_workflows_by_category(&self, category: &str) -> Result<Vec<WorkflowModel>> {
        let mut conn = self.get_connection()?;
        
        let mut stmt = conn.prepare(
            "SELECT id, name, description, workflow_data, version, created_at, updated_at, enabled, tags, category
             FROM comfyui_workflows WHERE category = ?1 AND enabled = 1 ORDER BY created_at DESC"
        )?;
        
        let workflow_iter = stmt.query_map([category], |row| {
            self.row_to_workflow_model(row)
        })?;
        
        let mut workflows = Vec::new();
        for workflow in workflow_iter {
            workflows.push(workflow?);
        }
        
        Ok(workflows)
    }

    /// 搜索工作流
    pub fn search_workflows(&self, query: &str) -> Result<Vec<WorkflowModel>> {
        let mut conn = self.get_connection()?;

        let search_pattern = format!("%{}%", query);
        let mut stmt = conn.prepare(
            "SELECT id, name, description, workflow_data, version, created_at, updated_at, enabled, tags, category
             FROM comfyui_workflows
             WHERE (name LIKE ?1 OR description LIKE ?1) AND enabled = 1
             ORDER BY created_at DESC"
        )?;

        let workflow_iter = stmt.query_map([&search_pattern], |row| {
            self.row_to_workflow_model(row)
        })?;

        let mut workflows = Vec::new();
        for workflow in workflow_iter {
            workflows.push(workflow?);
        }

        Ok(workflows)
    }



    // ==================== 辅助方法 ====================

    /// 将数据库行转换为工作流模型
    fn row_to_workflow_model(&self, row: &Row) -> rusqlite::Result<WorkflowModel> {
        let workflow_data_json: String = row.get("workflow_data")?;
        let tags_json: String = row.get("tags")?;
        
        let workflow_data = serde_json::from_str(&workflow_data_json)
            .map_err(|e| rusqlite::Error::InvalidColumnType(0, "workflow_data".to_string(), rusqlite::types::Type::Text))?;
        let tags = serde_json::from_str(&tags_json)
            .map_err(|e| rusqlite::Error::InvalidColumnType(0, "tags".to_string(), rusqlite::types::Type::Text))?;
        
        Ok(WorkflowModel {
            id: row.get("id")?,
            name: row.get("name")?,
            description: row.get("description")?,
            workflow_data,
            version: row.get("version")?,
            created_at: row.get("created_at")?,
            updated_at: row.get("updated_at")?,
            enabled: row.get("enabled")?,
            tags,
            category: row.get("category")?,
        })
    }

    // ==================== 模板相关操作 ====================

    /// 创建模板
    pub fn create_template(&self, template: &TemplateModel) -> Result<()> {
        let mut conn = self.get_connection()?;

        let template_data_json = serde_json::to_string(&template.template_data)?;
        let parameter_schema_json = serde_json::to_string(&template.parameter_schema)?;
        let tags_json = serde_json::to_string(&template.tags)?;

        conn.execute(
            "INSERT INTO comfyui_templates (id, name, category, description, template_data, parameter_schema, created_at, updated_at, enabled, tags, author, version)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
            params![
                template.id,
                template.name,
                template.category,
                template.description,
                template_data_json,
                parameter_schema_json,
                template.created_at,
                template.updated_at,
                template.enabled,
                tags_json,
                template.author,
                template.version
            ],
        )?;

        debug!("创建模板: {}", template.id);
        Ok(())
    }

    /// 获取模板
    pub fn get_template(&self, id: &str) -> Result<Option<TemplateModel>> {
        let mut conn = self.get_connection()?;

        let mut stmt = conn.prepare(
            "SELECT id, name, category, description, template_data, parameter_schema, created_at, updated_at, enabled, tags, author, version
             FROM comfyui_templates WHERE id = ?1"
        )?;

        let template_iter = stmt.query_map([id], |row| {
            self.row_to_template_model(row)
        })?;

        for template in template_iter {
            return Ok(Some(template?));
        }

        Ok(None)
    }

    /// 获取所有模板
    pub fn list_templates(&self, enabled_only: bool) -> Result<Vec<TemplateModel>> {
        let mut conn = self.get_connection()?;

        let sql = if enabled_only {
            "SELECT id, name, category, description, template_data, parameter_schema, created_at, updated_at, enabled, tags, author, version
             FROM comfyui_templates WHERE enabled = 1 ORDER BY created_at DESC"
        } else {
            "SELECT id, name, category, description, template_data, parameter_schema, created_at, updated_at, enabled, tags, author, version
             FROM comfyui_templates ORDER BY created_at DESC"
        };

        let mut stmt = conn.prepare(sql)?;
        let template_iter = stmt.query_map([], |row| {
            self.row_to_template_model(row)
        })?;

        let mut templates = Vec::new();
        for template in template_iter {
            templates.push(template?);
        }

        Ok(templates)
    }

    /// 更新模板
    pub fn update_template(&self, template: &TemplateModel) -> Result<()> {
        let mut conn = self.get_connection()?;

        let template_data_json = serde_json::to_string(&template.template_data)?;
        let parameter_schema_json = serde_json::to_string(&template.parameter_schema)?;
        let tags_json = serde_json::to_string(&template.tags)?;

        let rows_affected = conn.execute(
            "UPDATE comfyui_templates
             SET name = ?2, category = ?3, description = ?4, template_data = ?5, parameter_schema = ?6, updated_at = ?7, enabled = ?8, tags = ?9, author = ?10, version = ?11
             WHERE id = ?1",
            params![
                template.id,
                template.name,
                template.category,
                template.description,
                template_data_json,
                parameter_schema_json,
                template.updated_at,
                template.enabled,
                tags_json,
                template.author,
                template.version
            ],
        )?;

        if rows_affected == 0 {
            return Err(anyhow!("模板不存在: {}", template.id));
        }

        debug!("更新模板: {}", template.id);
        Ok(())
    }

    /// 删除模板
    pub fn delete_template(&self, id: &str) -> Result<()> {
        let mut conn = self.get_connection()?;

        let rows_affected = conn.execute("DELETE FROM comfyui_templates WHERE id = ?1", [id])?;

        if rows_affected == 0 {
            return Err(anyhow!("模板不存在: {}", id));
        }

        debug!("删除模板: {}", id);
        Ok(())
    }

    /// 按分类获取模板
    pub fn get_templates_by_category(&self, category: &str) -> Result<Vec<TemplateModel>> {
        let mut conn = self.get_connection()?;

        let mut stmt = conn.prepare(
            "SELECT id, name, category, description, template_data, parameter_schema, created_at, updated_at, enabled, tags, author, version
             FROM comfyui_templates WHERE category = ?1 AND enabled = 1 ORDER BY created_at DESC"
        )?;

        let template_iter = stmt.query_map([category], |row| {
            self.row_to_template_model(row)
        })?;

        let mut templates = Vec::new();
        for template in template_iter {
            templates.push(template?);
        }

        Ok(templates)
    }

    /// 将数据库行转换为模板模型
    fn row_to_template_model(&self, row: &Row) -> rusqlite::Result<TemplateModel> {
        let template_data_json: String = row.get("template_data")?;
        let parameter_schema_json: String = row.get("parameter_schema")?;
        let tags_json: String = row.get("tags")?;

        let template_data = serde_json::from_str(&template_data_json)
            .map_err(|e| rusqlite::Error::InvalidColumnType(0, "template_data".to_string(), rusqlite::types::Type::Text))?;
        let parameter_schema = serde_json::from_str(&parameter_schema_json)
            .map_err(|e| rusqlite::Error::InvalidColumnType(0, "parameter_schema".to_string(), rusqlite::types::Type::Text))?;
        let tags = serde_json::from_str(&tags_json)
            .map_err(|e| rusqlite::Error::InvalidColumnType(0, "tags".to_string(), rusqlite::types::Type::Text))?;

        Ok(TemplateModel {
            id: row.get("id")?,
            name: row.get("name")?,
            category: row.get("category")?,
            description: row.get("description")?,
            template_data,
            parameter_schema,
            created_at: row.get("created_at")?,
            updated_at: row.get("updated_at")?,
            enabled: row.get("enabled")?,
            tags,
            author: row.get("author")?,
            version: row.get("version")?,
        })
    }

    // ==================== 执行记录相关操作 ====================

    /// 创建执行记录
    pub fn create_execution(&self, execution: &ExecutionModel) -> Result<()> {
        let mut conn = self.get_connection()?;

        let parameters_json = execution.parameters.as_ref()
            .map(|p| serde_json::to_string(p))
            .transpose()?;
        let results_json = execution.results.as_ref()
            .map(|r| serde_json::to_string(r))
            .transpose()?;
        let output_urls_json = serde_json::to_string(&execution.output_urls)?;
        let node_outputs_json = execution.node_outputs.as_ref()
            .map(|n| serde_json::to_string(n))
            .transpose()?;

        conn.execute(
            "INSERT INTO comfyui_executions (id, workflow_id, template_id, prompt_id, status, parameters, results, output_urls, error_message, execution_time, created_at, completed_at, client_id, node_outputs)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)",
            params![
                execution.id,
                execution.workflow_id,
                execution.template_id,
                execution.prompt_id,
                execution.status.to_string(),
                parameters_json,
                results_json,
                output_urls_json,
                execution.error_message,
                execution.execution_time,
                execution.created_at,
                execution.completed_at,
                execution.client_id,
                node_outputs_json
            ],
        )?;

        debug!("创建执行记录: {}", execution.id);
        Ok(())
    }

    /// 获取执行记录
    pub fn get_execution(&self, id: &str) -> Result<Option<ExecutionModel>> {
        let mut conn = self.get_connection()?;

        let mut stmt = conn.prepare(
            "SELECT id, workflow_id, template_id, prompt_id, status, parameters, results, output_urls, error_message, execution_time, created_at, completed_at, client_id, node_outputs
             FROM comfyui_executions WHERE id = ?1"
        )?;

        let execution_iter = stmt.query_map([id], |row| {
            self.row_to_execution_model(row)
        })?;

        for execution in execution_iter {
            return Ok(Some(execution?));
        }

        Ok(None)
    }

    /// 通过 prompt_id 获取执行记录
    pub fn get_execution_by_prompt_id(&self, prompt_id: &str) -> Result<Option<ExecutionModel>> {
        let mut conn = self.get_connection()?;

        let mut stmt = conn.prepare(
            "SELECT id, workflow_id, template_id, prompt_id, status, parameters, results, output_urls, error_message, execution_time, created_at, completed_at, client_id, node_outputs
             FROM comfyui_executions WHERE prompt_id = ?1"
        )?;

        let execution_iter = stmt.query_map([prompt_id], |row| {
            self.row_to_execution_model(row)
        })?;

        for execution in execution_iter {
            return Ok(Some(execution?));
        }

        Ok(None)
    }

    /// 获取执行记录列表
    pub fn list_executions(&self, limit: Option<u32>, status_filter: Option<ExecutionStatus>) -> Result<Vec<ExecutionModel>> {
        let mut conn = self.get_connection()?;

        let (sql, params): (String, Vec<String>) = match (limit, status_filter) {
            (Some(limit), Some(status)) => (
                "SELECT id, workflow_id, template_id, prompt_id, status, parameters, results, output_urls, error_message, execution_time, created_at, completed_at, client_id, node_outputs
                 FROM comfyui_executions WHERE status = ?1 ORDER BY created_at DESC LIMIT ?2".to_string(),
                vec![status.to_string(), limit.to_string()]
            ),
            (Some(limit), None) => (
                "SELECT id, workflow_id, template_id, prompt_id, status, parameters, results, output_urls, error_message, execution_time, created_at, completed_at, client_id, node_outputs
                 FROM comfyui_executions ORDER BY created_at DESC LIMIT ?1".to_string(),
                vec![limit.to_string()]
            ),
            (None, Some(status)) => (
                "SELECT id, workflow_id, template_id, prompt_id, status, parameters, results, output_urls, error_message, execution_time, created_at, completed_at, client_id, node_outputs
                 FROM comfyui_executions WHERE status = ?1 ORDER BY created_at DESC".to_string(),
                vec![status.to_string()]
            ),
            (None, None) => (
                "SELECT id, workflow_id, template_id, prompt_id, status, parameters, results, output_urls, error_message, execution_time, created_at, completed_at, client_id, node_outputs
                 FROM comfyui_executions ORDER BY created_at DESC".to_string(),
                vec![]
            ),
        };

        let mut stmt = conn.prepare(&sql)?;
        let execution_iter = stmt.query_map(rusqlite::params_from_iter(params.iter()), |row| {
            self.row_to_execution_model(row)
        })?;

        let mut executions = Vec::new();
        for execution in execution_iter {
            executions.push(execution?);
        }

        Ok(executions)
    }

    /// 更新执行记录
    pub fn update_execution(&self, execution: &ExecutionModel) -> Result<()> {
        let mut conn = self.get_connection()?;

        let parameters_json = execution.parameters.as_ref()
            .map(|p| serde_json::to_string(p))
            .transpose()?;
        let results_json = execution.results.as_ref()
            .map(|r| serde_json::to_string(r))
            .transpose()?;
        let output_urls_json = serde_json::to_string(&execution.output_urls)?;
        let node_outputs_json = execution.node_outputs.as_ref()
            .map(|n| serde_json::to_string(n))
            .transpose()?;

        let rows_affected = conn.execute(
            "UPDATE comfyui_executions
             SET workflow_id = ?2, template_id = ?3, status = ?4, parameters = ?5, results = ?6, output_urls = ?7, error_message = ?8, execution_time = ?9, completed_at = ?10, client_id = ?11, node_outputs = ?12
             WHERE id = ?1",
            params![
                execution.id,
                execution.workflow_id,
                execution.template_id,
                execution.status.to_string(),
                parameters_json,
                results_json,
                output_urls_json,
                execution.error_message,
                execution.execution_time,
                execution.completed_at,
                execution.client_id,
                node_outputs_json
            ],
        )?;

        if rows_affected == 0 {
            return Err(anyhow!("执行记录不存在: {}", execution.id));
        }

        debug!("更新执行记录: {}", execution.id);
        Ok(())
    }

    /// 删除执行记录
    pub fn delete_execution(&self, id: &str) -> Result<()> {
        let mut conn = self.get_connection()?;

        let rows_affected = conn.execute("DELETE FROM comfyui_executions WHERE id = ?1", [id])?;

        if rows_affected == 0 {
            return Err(anyhow!("执行记录不存在: {}", id));
        }

        debug!("删除执行记录: {}", id);
        Ok(())
    }

    /// 将数据库行转换为执行记录模型
    fn row_to_execution_model(&self, row: &Row) -> rusqlite::Result<ExecutionModel> {
        let parameters_json: Option<String> = row.get("parameters")?;
        let results_json: Option<String> = row.get("results")?;
        let output_urls_json: String = row.get("output_urls")?;
        let node_outputs_json: Option<String> = row.get("node_outputs")?;
        let status_str: String = row.get("status")?;

        let parameters = parameters_json
            .map(|json| serde_json::from_str(&json))
            .transpose()
            .map_err(|e| rusqlite::Error::InvalidColumnType(0, "parameters".to_string(), rusqlite::types::Type::Text))?;

        let results = results_json
            .map(|json| serde_json::from_str(&json))
            .transpose()
            .map_err(|e| rusqlite::Error::InvalidColumnType(0, "results".to_string(), rusqlite::types::Type::Text))?;

        let output_urls = serde_json::from_str(&output_urls_json)
            .map_err(|e| rusqlite::Error::InvalidColumnType(0, "output_urls".to_string(), rusqlite::types::Type::Text))?;

        let node_outputs = node_outputs_json
            .map(|json| serde_json::from_str(&json))
            .transpose()
            .map_err(|e| rusqlite::Error::InvalidColumnType(0, "node_outputs".to_string(), rusqlite::types::Type::Text))?;

        let status = match status_str.as_str() {
            "pending" => ExecutionStatus::Pending,
            "running" => ExecutionStatus::Running,
            "completed" => ExecutionStatus::Completed,
            "failed" => ExecutionStatus::Failed,
            "cancelled" => ExecutionStatus::Cancelled,
            _ => ExecutionStatus::Failed, // 默认为失败状态
        };

        Ok(ExecutionModel {
            id: row.get("id")?,
            workflow_id: row.get("workflow_id")?,
            template_id: row.get("template_id")?,
            prompt_id: row.get("prompt_id")?,
            status,
            parameters,
            results,
            output_urls,
            error_message: row.get("error_message")?,
            execution_time: row.get("execution_time")?,
            created_at: row.get("created_at")?,
            completed_at: row.get("completed_at")?,
            client_id: row.get("client_id")?,
            node_outputs,
        })
    }

    /// 获取配置
    pub async fn get_config(&self) -> Result<crate::data::models::comfyui::ComfyUIConfig> {
        self.with_connection(|conn| {
            let mut stmt = conn.prepare(
                "SELECT base_url, timeout_seconds, retry_attempts, retry_delay_ms,
                        enable_websocket, enable_cache, max_concurrency, custom_headers
                 FROM comfyui_configs WHERE id = 'default'"
            )?;

            let config_iter = stmt.query_map([], |row| {
                let custom_headers_json: Option<String> = row.get(7)?;
                let custom_headers = if let Some(json) = custom_headers_json {
                    serde_json::from_str(&json).ok()
                } else {
                    None
                };

                Ok(crate::data::models::comfyui::ComfyUIConfig {
                    base_url: row.get(0)?,
                    timeout_seconds: row.get(1)?,
                    retry_attempts: row.get(2)?,
                    retry_delay_ms: row.get(3)?,
                    enable_websocket: row.get(4)?,
                    enable_cache: row.get(5)?,
                    max_concurrency: row.get(6)?,
                    custom_headers,
                })
            })?;

            for config in config_iter {
                return Ok(config?);
            }

            // 如果没有找到配置，返回默认配置
            Ok(crate::data::models::comfyui::ComfyUIConfig::default())
        })
    }

    /// 保存配置
    pub async fn save_config(&self, config: &crate::data::models::comfyui::ComfyUIConfig) -> Result<()> {
        self.with_connection(|conn| {
            let custom_headers_json = if let Some(headers) = &config.custom_headers {
                Some(serde_json::to_string(headers)?)
            } else {
                None
            };

            conn.execute(
                "INSERT OR REPLACE INTO comfyui_configs
                 (id, base_url, timeout_seconds, retry_attempts, retry_delay_ms,
                  enable_websocket, enable_cache, max_concurrency, custom_headers, updated_at)
                 VALUES ('default', ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, CURRENT_TIMESTAMP)",
                params![
                    config.base_url,
                    config.timeout_seconds,
                    config.retry_attempts,
                    config.retry_delay_ms,
                    config.enable_websocket,
                    config.enable_cache,
                    config.max_concurrency,
                    custom_headers_json
                ],
            )?;

            debug!("保存配置成功: {}", config.base_url);
            Ok(())
        })
    }
}
