use crate::data::models::workflow_execution_record::{
    WorkflowExecutionRecord, ExecutionStatus, ErrorDetails, ExecutionRecordFilter
};
use crate::infrastructure::database::Database;
use anyhow::{Result, anyhow};
use chrono::{DateTime, Utc};
use rusqlite::Row;
use std::sync::Arc;
use tracing::{debug, info};

/// 工作流执行记录数据仓库
/// 遵循 Tauri 开发规范的仓库模式设计
#[derive(Clone)]
pub struct WorkflowExecutionRecordRepository {
    database: Arc<Database>,
}

impl WorkflowExecutionRecordRepository {
    /// 创建新的工作流执行记录仓库实例
    pub fn new(database: Arc<Database>) -> Self {
        Self { database }
    }

    /// 创建工作流执行记录
    pub fn create(&self, record: &WorkflowExecutionRecord) -> Result<i64> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let conn = self.database.acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;

        // 序列化JSON字段
        let input_data_json = serde_json::to_string(&record.input_data_json)
            .map_err(|e| anyhow!("序列化input_data_json失败: {}", e))?;
        
        let output_data_json = record.output_data_json.as_ref()
            .map(|data| serde_json::to_string(data))
            .transpose()
            .map_err(|e| anyhow!("序列化output_data_json失败: {}", e))?;
        
        let error_details_json = record.error_details_json.as_ref()
            .map(|details| serde_json::to_string(details))
            .transpose()
            .map_err(|e| anyhow!("序列化error_details失败: {}", e))?;

        let metadata_json = record.metadata_json.as_ref()
            .map(|metadata| serde_json::to_string(metadata))
            .transpose()
            .map_err(|e| anyhow!("序列化metadata失败: {}", e))?;
        
        let tags_json = record.tags.as_ref()
            .map(|tags| serde_json::to_string(tags))
            .transpose()
            .map_err(|e| anyhow!("序列化tags失败: {}", e))?;

        let status_str = serde_json::to_string(&record.status)
            .map_err(|e| anyhow!("序列化status失败: {}", e))?;

        let now = Utc::now().to_rfc3339();

        let _result = conn.execute(
            "INSERT INTO workflow_execution_records (
                workflow_template_id, workflow_name, workflow_version,
                execution_environment_id, execution_environment_name,
                input_data_json, output_data_json,
                status, progress,
                comfyui_prompt_id, comfyui_workflow_name,
                started_at, completed_at, duration_seconds,
                error_message, error_details_json,
                user_id, session_id,
                metadata_json, tags,
                created_at, updated_at
            ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22)",
            [
                &record.workflow_template_id as &dyn rusqlite::ToSql,
                &record.workflow_name,
                &record.workflow_version,
                &record.execution_environment_id,
                &record.execution_environment_name,
                &input_data_json,
                &output_data_json,
                &status_str,
                &record.progress,
                &record.comfyui_prompt_id,
                &record.comfyui_workflow_name,
                &record.started_at.map(|dt| dt.to_rfc3339()),
                &record.completed_at.map(|dt| dt.to_rfc3339()),
                &record.duration_seconds,
                &record.error_message,
                &error_details_json,
                &record.user_id,
                &record.session_id,
                &metadata_json,
                &tags_json,
                &now,
                &now,
            ],
        ).map_err(|e| anyhow!("插入工作流执行记录失败: {}", e))?;

        let id = conn.last_insert_rowid();
        info!("成功创建工作流执行记录，ID: {}", id);
        Ok(id)
    }

    /// 根据ID获取工作流执行记录
    pub fn find_by_id(&self, id: i64) -> Result<Option<WorkflowExecutionRecord>> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let conn = self.database.acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;

        let mut stmt = conn.prepare(
            "SELECT id, workflow_template_id, workflow_name, workflow_version,
                    execution_environment_id, execution_environment_name,
                    input_data_json, output_data_json,
                    status, progress,
                    comfyui_prompt_id, comfyui_workflow_name,
                    started_at, completed_at, duration_seconds,
                    error_message, error_details_json,
                    user_id, session_id,
                    metadata_json, tags,
                    created_at, updated_at
             FROM workflow_execution_records WHERE id = ?1"
        ).map_err(|e| anyhow!("准备查询语句失败: {}", e))?;

        let record_iter = stmt.query_map([id], |row| self.row_to_record(row))
            .map_err(|e| anyhow!("执行查询失败: {}", e))?;

        for record in record_iter {
            return Ok(Some(record.map_err(|e| anyhow!("解析查询结果失败: {}", e))?));
        }

        Ok(None)
    }

    /// 获取所有工作流执行记录（支持筛选）
    pub fn find_all(&self, filter: Option<&ExecutionRecordFilter>) -> Result<Vec<WorkflowExecutionRecord>> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let conn = self.database.acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;

        let (sql, params) = self.build_query_sql(filter);
        
        let mut stmt = conn.prepare(&sql)
            .map_err(|e| anyhow!("准备查询语句失败: {}", e))?;

        let param_refs: Vec<&dyn rusqlite::ToSql> = params.iter().map(|p| p.as_ref()).collect();
        let record_iter = stmt.query_map(param_refs.as_slice(), |row| self.row_to_record(row))
            .map_err(|e| anyhow!("执行查询失败: {}", e))?;

        let mut records = Vec::new();
        for record in record_iter {
            records.push(record.map_err(|e| anyhow!("解析查询结果失败: {}", e))?);
        }

        debug!("查询到 {} 个工作流执行记录", records.len());
        Ok(records)
    }

    /// 更新工作流执行记录
    pub fn update(&self, record: &WorkflowExecutionRecord) -> Result<()> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let id = record.id.ok_or_else(|| anyhow!("执行记录ID不能为空"))?;

        let conn = self.database.acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;

        // 序列化JSON字段
        let input_data_json = serde_json::to_string(&record.input_data_json)
            .map_err(|e| anyhow!("序列化input_data_json失败: {}", e))?;
        
        let output_data_json = record.output_data_json.as_ref()
            .map(|data| serde_json::to_string(data))
            .transpose()
            .map_err(|e| anyhow!("序列化output_data_json失败: {}", e))?;
        
        let error_details_json = record.error_details_json.as_ref()
            .map(|details| serde_json::to_string(details))
            .transpose()
            .map_err(|e| anyhow!("序列化error_details失败: {}", e))?;

        let metadata_json = record.metadata_json.as_ref()
            .map(|metadata| serde_json::to_string(metadata))
            .transpose()
            .map_err(|e| anyhow!("序列化metadata失败: {}", e))?;
        
        let tags_json = record.tags.as_ref()
            .map(|tags| serde_json::to_string(tags))
            .transpose()
            .map_err(|e| anyhow!("序列化tags失败: {}", e))?;

        let status_str = serde_json::to_string(&record.status)
            .map_err(|e| anyhow!("序列化status失败: {}", e))?;

        let now = Utc::now().to_rfc3339();

        conn.execute(
            "UPDATE workflow_execution_records SET
                workflow_template_id = ?1, workflow_name = ?2, workflow_version = ?3,
                execution_environment_id = ?4, execution_environment_name = ?5,
                input_data_json = ?6, output_data_json = ?7,
                status = ?8, progress = ?9,
                comfyui_prompt_id = ?10, comfyui_workflow_name = ?11,
                started_at = ?12, completed_at = ?13, duration_seconds = ?14,
                error_message = ?15, error_details_json = ?16,
                user_id = ?17, session_id = ?18,
                metadata_json = ?19, tags = ?20,
                updated_at = ?21
             WHERE id = ?22",
            [
                &record.workflow_template_id as &dyn rusqlite::ToSql,
                &record.workflow_name,
                &record.workflow_version,
                &record.execution_environment_id,
                &record.execution_environment_name,
                &input_data_json,
                &output_data_json,
                &status_str,
                &record.progress,
                &record.comfyui_prompt_id,
                &record.comfyui_workflow_name,
                &record.started_at.map(|dt| dt.to_rfc3339()),
                &record.completed_at.map(|dt| dt.to_rfc3339()),
                &record.duration_seconds,
                &record.error_message,
                &error_details_json,
                &record.user_id,
                &record.session_id,
                &metadata_json,
                &tags_json,
                &now,
                &id,
            ],
        ).map_err(|e| anyhow!("更新工作流执行记录失败: {}", e))?;

        info!("成功更新工作流执行记录，ID: {}", id);
        Ok(())
    }

    /// 删除工作流执行记录
    pub fn delete(&self, id: i64) -> Result<()> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let conn = self.database.acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;

        let affected_rows = conn.execute("DELETE FROM workflow_execution_records WHERE id = ?1", [id])
            .map_err(|e| anyhow!("删除工作流执行记录失败: {}", e))?;

        if affected_rows == 0 {
            return Err(anyhow!("工作流执行记录不存在，ID: {}", id));
        }

        info!("成功删除工作流执行记录，ID: {}", id);
        Ok(())
    }

    /// 批量删除工作流执行记录
    pub fn batch_delete(&self, ids: &[i64]) -> Result<usize> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        if ids.is_empty() {
            return Ok(0);
        }

        let conn = self.database.acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;

        let placeholders = ids.iter().map(|_| "?").collect::<Vec<_>>().join(",");
        let sql = format!("DELETE FROM workflow_execution_records WHERE id IN ({})", placeholders);

        let affected_rows = conn.execute(&sql, rusqlite::params_from_iter(ids.iter()))
            .map_err(|e| anyhow!("批量删除工作流执行记录失败: {}", e))?;

        info!("成功批量删除 {} 个工作流执行记录", affected_rows);
        Ok(affected_rows)
    }

    /// 分页查询工作流执行记录
    pub fn find_with_pagination(
        &self,
        filter: Option<&ExecutionRecordFilter>,
        page: u32,
        page_size: u32
    ) -> Result<(Vec<WorkflowExecutionRecord>, u32)> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let conn = self.database.acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;

        // 首先获取总数
        let (count_sql, count_params) = self.build_count_sql(filter);
        let mut stmt = conn.prepare(&count_sql)
            .map_err(|e| anyhow!("准备计数查询语句失败: {}", e))?;

        let count_param_refs: Vec<&dyn rusqlite::ToSql> = count_params.iter().map(|p| p.as_ref()).collect();
        let total_count: u32 = stmt.query_row(count_param_refs.as_slice(), |row| {
            Ok(row.get::<_, i64>(0)? as u32)
        }).map_err(|e| anyhow!("执行计数查询失败: {}", e))?;

        // 然后获取分页数据
        let (sql, mut params) = self.build_query_sql(filter);
        let offset = page * page_size;
        let paginated_sql = format!("{} LIMIT ? OFFSET ?", sql);

        params.push(Box::new(page_size));
        params.push(Box::new(offset));

        let mut stmt = conn.prepare(&paginated_sql)
            .map_err(|e| anyhow!("准备分页查询语句失败: {}", e))?;

        let param_refs: Vec<&dyn rusqlite::ToSql> = params.iter().map(|p| p.as_ref()).collect();
        let record_iter = stmt.query_map(param_refs.as_slice(), |row| self.row_to_record(row))
            .map_err(|e| anyhow!("执行分页查询失败: {}", e))?;

        let mut records = Vec::new();
        for record in record_iter {
            records.push(record.map_err(|e| anyhow!("解析查询结果失败: {}", e))?);
        }

        debug!("分页查询到 {} 个工作流执行记录，总数: {}", records.len(), total_count);
        Ok((records, total_count))
    }

    /// 获取执行统计信息
    pub fn get_execution_statistics(&self, filter: Option<&ExecutionRecordFilter>) -> Result<ExecutionStatistics> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let conn = self.database.acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;

        let (base_sql, params) = self.build_base_filter_sql(filter);

        // 构建统计查询SQL
        let sql = format!(
            "SELECT
                COUNT(*) as total_count,
                COALESCE(SUM(CASE WHEN status = '\"completed\"' THEN 1 ELSE 0 END), 0) as completed_count,
                COALESCE(SUM(CASE WHEN status = '\"failed\"' THEN 1 ELSE 0 END), 0) as failed_count,
                COALESCE(SUM(CASE WHEN status = '\"running\"' THEN 1 ELSE 0 END), 0) as running_count,
                COALESCE(SUM(CASE WHEN status = '\"pending\"' THEN 1 ELSE 0 END), 0) as pending_count,
                AVG(CASE WHEN duration_seconds IS NOT NULL THEN duration_seconds ELSE NULL END) as avg_duration,
                MIN(created_at) as earliest_execution,
                MAX(created_at) as latest_execution
             FROM workflow_execution_records {}",
            base_sql
        );

        let mut stmt = conn.prepare(&sql)
            .map_err(|e| anyhow!("准备统计查询语句失败: {}", e))?;

        let param_refs: Vec<&dyn rusqlite::ToSql> = params.iter().map(|p| p.as_ref()).collect();
        let stats = stmt.query_row(param_refs.as_slice(), |row| {
            let total_count: i64 = row.get("total_count")?;
            let completed_count: i64 = row.get("completed_count")?;
            let failed_count: i64 = row.get("failed_count")?;
            let running_count: i64 = row.get("running_count")?;
            let pending_count: i64 = row.get("pending_count")?;
            let avg_duration: Option<f64> = row.get("avg_duration")?;
            let earliest_execution: Option<String> = row.get("earliest_execution")?;
            let latest_execution: Option<String> = row.get("latest_execution")?;

            let success_rate = if total_count > 0 {
                completed_count as f64 / total_count as f64
            } else {
                0.0
            };

            let earliest_execution_dt = earliest_execution
                .and_then(|s| DateTime::parse_from_rfc3339(&s).ok())
                .map(|dt| dt.with_timezone(&Utc));

            let latest_execution_dt = latest_execution
                .and_then(|s| DateTime::parse_from_rfc3339(&s).ok())
                .map(|dt| dt.with_timezone(&Utc));

            Ok(ExecutionStatistics {
                total_executions: total_count as u32,
                completed_executions: completed_count as u32,
                failed_executions: failed_count as u32,
                running_executions: running_count as u32,
                pending_executions: pending_count as u32,
                success_rate,
                average_duration_seconds: avg_duration,
                earliest_execution: earliest_execution_dt,
                latest_execution: latest_execution_dt,
            })
        }).map_err(|e| anyhow!("执行统计查询失败: {}", e))?;

        debug!("获取执行统计信息: 总数={}, 成功率={:.2}", stats.total_executions, stats.success_rate);
        Ok(stats)
    }

    /// 构建查询SQL和参数
    fn build_query_sql(&self, filter: Option<&ExecutionRecordFilter>) -> (String, Vec<Box<dyn rusqlite::ToSql>>) {
        let mut sql = "SELECT id, workflow_template_id, workflow_name, workflow_version,
                             execution_environment_id, execution_environment_name,
                             input_data_json, output_data_json,
                             status, progress,
                             comfyui_prompt_id, comfyui_workflow_name,
                             started_at, completed_at, duration_seconds,
                             error_message, error_details_json,
                             user_id, session_id,
                             metadata_json, tags,
                             created_at, updated_at
                      FROM workflow_execution_records".to_string();

        let (where_clause, params) = self.build_where_clause(filter);
        if !where_clause.is_empty() {
            sql.push_str(" WHERE ");
            sql.push_str(&where_clause);
        }

        // 默认按创建时间倒序排列
        sql.push_str(" ORDER BY created_at DESC");

        (sql, params)
    }

    /// 构建计数查询SQL和参数
    fn build_count_sql(&self, filter: Option<&ExecutionRecordFilter>) -> (String, Vec<Box<dyn rusqlite::ToSql>>) {
        let mut sql = "SELECT COUNT(*) FROM workflow_execution_records".to_string();

        let (where_clause, params) = self.build_where_clause(filter);
        if !where_clause.is_empty() {
            sql.push_str(" WHERE ");
            sql.push_str(&where_clause);
        }

        (sql, params)
    }

    /// 构建基础筛选SQL（用于统计查询）
    fn build_base_filter_sql(&self, filter: Option<&ExecutionRecordFilter>) -> (String, Vec<Box<dyn rusqlite::ToSql>>) {
        let (where_clause, params) = self.build_where_clause(filter);
        if !where_clause.is_empty() {
            (format!(" WHERE {}", where_clause), params)
        } else {
            (String::new(), params)
        }
    }

    /// 构建WHERE子句
    fn build_where_clause(&self, filter: Option<&ExecutionRecordFilter>) -> (String, Vec<Box<dyn rusqlite::ToSql>>) {
        let mut where_clauses = Vec::new();
        let mut params: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();

        if let Some(filter) = filter {
            if let Some(workflow_template_id) = filter.workflow_template_id {
                where_clauses.push("workflow_template_id = ?");
                params.push(Box::new(workflow_template_id));
            }

            if let Some(status) = &filter.status {
                let status_str = serde_json::to_string(status).unwrap_or_default();
                where_clauses.push("status = ?");
                params.push(Box::new(status_str));
            }

            if let Some(user_id) = &filter.user_id {
                where_clauses.push("user_id = ?");
                params.push(Box::new(user_id.clone()));
            }

            if let Some(session_id) = &filter.session_id {
                where_clauses.push("session_id = ?");
                params.push(Box::new(session_id.clone()));
            }

            if let Some(comfyui_prompt_id) = &filter.comfyui_prompt_id {
                where_clauses.push("comfyui_prompt_id = ?");
                params.push(Box::new(comfyui_prompt_id.clone()));
            }

            if let Some(date_from) = filter.date_from {
                where_clauses.push("created_at >= ?");
                params.push(Box::new(date_from.to_rfc3339()));
            }

            if let Some(date_to) = filter.date_to {
                where_clauses.push("created_at <= ?");
                params.push(Box::new(date_to.to_rfc3339()));
            }
        }

        (where_clauses.join(" AND "), params)
    }

    /// 将数据库行转换为WorkflowExecutionRecord对象
    fn row_to_record(&self, row: &Row) -> rusqlite::Result<WorkflowExecutionRecord> {
        let id: Option<i64> = Some(row.get("id")?);
        let workflow_template_id: i64 = row.get("workflow_template_id")?;
        let workflow_name: String = row.get("workflow_name")?;
        let workflow_version: String = row.get("workflow_version")?;
        let execution_environment_id: Option<i64> = row.get("execution_environment_id")?;
        let execution_environment_name: Option<String> = row.get("execution_environment_name")?;

        // 解析JSON字段
        let input_data_json_str: String = row.get("input_data_json")?;
        let input_data_json: serde_json::Value = serde_json::from_str(&input_data_json_str)
            .map_err(|e| rusqlite::Error::FromSqlConversionFailure(
                0, rusqlite::types::Type::Text, Box::new(e)
            ))?;

        let output_data_json: Option<serde_json::Value> = row.get::<_, Option<String>>("output_data_json")?
            .map(|s| serde_json::from_str(&s))
            .transpose()
            .map_err(|e| rusqlite::Error::FromSqlConversionFailure(
                0, rusqlite::types::Type::Text, Box::new(e)
            ))?;

        // 解析执行状态
        let status_str: String = row.get("status")?;
        let status: ExecutionStatus = serde_json::from_str(&status_str)
            .map_err(|e| rusqlite::Error::FromSqlConversionFailure(
                0, rusqlite::types::Type::Text, Box::new(e)
            ))?;

        let progress: i32 = row.get("progress")?;
        let comfyui_prompt_id: Option<String> = row.get("comfyui_prompt_id")?;
        let comfyui_workflow_name: Option<String> = row.get("comfyui_workflow_name")?;

        // 解析时间字段
        let started_at: Option<DateTime<Utc>> = row.get::<_, Option<String>>("started_at")?
            .map(|s| DateTime::parse_from_rfc3339(&s))
            .transpose()
            .map_err(|e| rusqlite::Error::FromSqlConversionFailure(
                0, rusqlite::types::Type::Text, Box::new(e)
            ))?
            .map(|dt| dt.with_timezone(&Utc));

        let completed_at: Option<DateTime<Utc>> = row.get::<_, Option<String>>("completed_at")?
            .map(|s| DateTime::parse_from_rfc3339(&s))
            .transpose()
            .map_err(|e| rusqlite::Error::FromSqlConversionFailure(
                0, rusqlite::types::Type::Text, Box::new(e)
            ))?
            .map(|dt| dt.with_timezone(&Utc));

        let duration_seconds: Option<i32> = row.get("duration_seconds")?;
        let error_message: Option<String> = row.get("error_message")?;

        let error_details: Option<ErrorDetails> = row.get::<_, Option<String>>("error_details_json")?
            .map(|s| serde_json::from_str(&s))
            .transpose()
            .map_err(|e| rusqlite::Error::FromSqlConversionFailure(
                0, rusqlite::types::Type::Text, Box::new(e)
            ))?;

        let user_id: Option<String> = row.get("user_id")?;
        let session_id: Option<String> = row.get("session_id")?;

        let metadata: Option<serde_json::Value> = row.get::<_, Option<String>>("metadata_json")?
            .map(|s| serde_json::from_str(&s))
            .transpose()
            .map_err(|e| rusqlite::Error::FromSqlConversionFailure(
                0, rusqlite::types::Type::Text, Box::new(e)
            ))?;

        let tags: Option<Vec<String>> = row.get::<_, Option<String>>("tags")?
            .map(|s| serde_json::from_str(&s))
            .transpose()
            .map_err(|e| rusqlite::Error::FromSqlConversionFailure(
                0, rusqlite::types::Type::Text, Box::new(e)
            ))?;

        // 解析时间戳
        let created_at_str: String = row.get("created_at")?;
        let created_at = DateTime::parse_from_rfc3339(&created_at_str)
            .map_err(|e| rusqlite::Error::FromSqlConversionFailure(
                0, rusqlite::types::Type::Text, Box::new(e)
            ))?
            .with_timezone(&Utc);

        let updated_at_str: String = row.get("updated_at")?;
        let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)
            .map_err(|e| rusqlite::Error::FromSqlConversionFailure(
                0, rusqlite::types::Type::Text, Box::new(e)
            ))?
            .with_timezone(&Utc);

        Ok(WorkflowExecutionRecord {
            id,
            workflow_template_id,
            workflow_name,
            workflow_version,
            execution_environment_id,
            execution_environment_name,
            input_data_json,
            output_data_json,
            status,
            progress,
            comfyui_prompt_id,
            comfyui_workflow_name,
            started_at,
            completed_at,
            duration_seconds,
            error_message,
            error_details_json: error_details.map(|e| serde_json::to_value(e).unwrap_or(serde_json::Value::Null)),
            user_id,
            session_id,
            metadata_json: metadata,
            tags,
            created_at,
            updated_at,
        })
    }
}

/// 执行统计信息
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExecutionStatistics {
    pub total_executions: u32,
    pub completed_executions: u32,
    pub failed_executions: u32,
    pub running_executions: u32,
    pub pending_executions: u32,
    pub success_rate: f64,
    pub average_duration_seconds: Option<f64>,
    pub earliest_execution: Option<DateTime<Utc>>,
    pub latest_execution: Option<DateTime<Utc>>,
}
