/// 容错JSON解析器的Tauri命令接口
/// 遵循Tauri开发规范，提供安全、高性能的JSON解析API
use crate::infrastructure::tolerant_json_parser::{
    ParseStatistics, ParserConfig, RecoveryStrategy, TolerantJsonParser,
};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::Mutex;
use tauri::{command, State};
use tracing::{error, info};

/// JSON解析请求参数
#[derive(Debug, Deserialize)]
pub struct ParseJsonRequest {
    /// 要解析的JSON文本
    pub text: String,
    /// 解析器配置（可选）
    pub config: Option<JsonParserConfig>,
}

/// JSON解析器配置（前端友好的格式）
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct JsonParserConfig {
    /// 最大文本长度（字节）
    pub max_text_length: Option<usize>,
    /// 是否启用注释支持
    pub enable_comments: Option<bool>,
    /// 是否启用无引号键支持
    pub enable_unquoted_keys: Option<bool>,
    /// 是否启用尾随逗号支持
    pub enable_trailing_commas: Option<bool>,
    /// 超时时间（毫秒）
    pub timeout_ms: Option<u64>,
    /// 启用的恢复策略
    pub recovery_strategies: Option<Vec<String>>,
}

impl From<JsonParserConfig> for ParserConfig {
    fn from(config: JsonParserConfig) -> Self {
        let mut parser_config = ParserConfig::default();
        
        if let Some(max_length) = config.max_text_length {
            parser_config.max_text_length = max_length;
        }
        if let Some(comments) = config.enable_comments {
            parser_config.enable_comments = comments;
        }
        if let Some(unquoted_keys) = config.enable_unquoted_keys {
            parser_config.enable_unquoted_keys = unquoted_keys;
        }
        if let Some(trailing_commas) = config.enable_trailing_commas {
            parser_config.enable_trailing_commas = trailing_commas;
        }
        if let Some(timeout) = config.timeout_ms {
            parser_config.timeout_ms = timeout;
        }
        if let Some(strategies) = config.recovery_strategies {
            parser_config.recovery_strategies = strategies
                .into_iter()
                .filter_map(|s| match s.as_str() {
                    "StandardJson" => Some(RecoveryStrategy::StandardJson),
                    "ManualFix" => Some(RecoveryStrategy::ManualFix),
                    "RegexExtract" => Some(RecoveryStrategy::RegexExtract),
                    "PartialParse" => Some(RecoveryStrategy::PartialParse),
                    _ => None,
                })
                .collect();
        }
        
        parser_config
    }
}

/// JSON解析响应
#[derive(Debug, Serialize)]
pub struct ParseJsonResponse {
    /// 解析成功标志
    pub success: bool,
    /// 解析结果（JSON值）
    pub data: Option<Value>,
    /// 解析统计信息
    pub statistics: Option<ParseStatistics>,
    /// 错误信息
    pub error: Option<String>,
}

/// JSON解析器状态管理
pub struct JsonParserState {
    parser: Mutex<Option<TolerantJsonParser>>,
}

impl JsonParserState {
    pub fn new() -> Self {
        Self {
            parser: Mutex::new(None),
        }
    }

    /// 获取或创建解析器实例
    fn get_or_create_parser(&self, config: Option<ParserConfig>) -> Result<()> {
        let mut parser_guard = self.parser.lock().unwrap();

        // 每次都创建新的解析器实例以确保使用正确的配置
        let parser = TolerantJsonParser::new(config)?;
        *parser_guard = Some(parser);

        Ok(())
    }
}

/// 解析JSON文本
#[command]
pub async fn parse_json_tolerant(
    request: ParseJsonRequest,
    state: State<'_, JsonParserState>,
) -> Result<ParseJsonResponse, String> {
    info!("Received JSON parse request, text length: {}", request.text.len());
    
    // 转换配置
    let parser_config = request.config.map(|c| c.into());
    
    // 确保解析器已初始化
    if let Err(e) = state.get_or_create_parser(parser_config) {
        error!("Failed to initialize JSON parser: {}", e);
        return Ok(ParseJsonResponse {
            success: false,
            data: None,
            statistics: None,
            error: Some(format!("Parser initialization failed: {}", e)),
        });
    }
    
    // 执行解析
    let mut parser_guard = state.parser.lock().unwrap();
    if let Some(ref mut parser) = *parser_guard {
        info!("Starting JSON parsing for text: {}", &request.text[..std::cmp::min(100, request.text.len())]);
        match parser.parse(&request.text) {
            Ok((data, statistics)) => {
                info!("JSON parsing successful, error rate: {:.2}%, result: {:?}",
                      statistics.error_rate * 100.0,
                      serde_json::to_string(&data).unwrap_or_else(|_| "Failed to serialize".to_string()));
                Ok(ParseJsonResponse {
                    success: true,
                    data: Some(data),
                    statistics: Some(statistics),
                    error: None,
                })
            }
            Err(e) => {
                error!("JSON parsing failed: {}", e);
                Ok(ParseJsonResponse {
                    success: false,
                    data: None,
                    statistics: None,
                    error: Some(e.to_string()),
                })
            }
        }
    } else {
        error!("JSON parser not initialized");
        Ok(ParseJsonResponse {
            success: false,
            data: None,
            statistics: None,
            error: Some("Parser not initialized".to_string()),
        })
    }
}

/// 验证JSON文本格式
#[command]
pub fn validate_json_format(text: String) -> Result<bool, String> {
    match serde_json::from_str::<Value>(&text) {
        Ok(_) => Ok(true),
        Err(_) => Ok(false),
    }
}

/// 格式化JSON文本
#[command]
pub fn format_json_text(
    text: String,
    indent: Option<usize>,
) -> Result<String, String> {
    let indent_size = indent.unwrap_or(2);
    
    match serde_json::from_str::<Value>(&text) {
        Ok(value) => {
            match serde_json::to_string_pretty(&value) {
                Ok(formatted) => {
                    // 如果需要自定义缩进，重新格式化
                    if indent_size != 2 {
                        let custom_formatted = format_with_custom_indent(&formatted, indent_size);
                        Ok(custom_formatted)
                    } else {
                        Ok(formatted)
                    }
                }
                Err(e) => Err(format!("Failed to format JSON: {}", e)),
            }
        }
        Err(e) => Err(format!("Invalid JSON: {}", e)),
    }
}

/// 自定义缩进格式化
fn format_with_custom_indent(json: &str, indent_size: usize) -> String {
    let indent_str = " ".repeat(indent_size);
    let mut result = String::new();
    let mut current_indent = 0;
    let mut in_string = false;
    let mut escape_next = false;
    
    for ch in json.chars() {
        if escape_next {
            result.push(ch);
            escape_next = false;
            continue;
        }
        
        match ch {
            '"' if !escape_next => {
                in_string = !in_string;
                result.push(ch);
            }
            '\\' if in_string => {
                escape_next = true;
                result.push(ch);
            }
            '{' | '[' if !in_string => {
                result.push(ch);
                result.push('\n');
                current_indent += 1;
                result.push_str(&indent_str.repeat(current_indent));
            }
            '}' | ']' if !in_string => {
                result.pop(); // 移除最后的空格
                result.push('\n');
                current_indent -= 1;
                result.push_str(&indent_str.repeat(current_indent));
                result.push(ch);
            }
            ',' if !in_string => {
                result.push(ch);
                result.push('\n');
                result.push_str(&indent_str.repeat(current_indent));
            }
            ':' if !in_string => {
                result.push(ch);
                result.push(' ');
            }
            ' ' | '\t' | '\n' | '\r' if !in_string => {
                // 跳过原有的空白字符
            }
            _ => {
                result.push(ch);
            }
        }
    }
    
    result
}

/// 获取JSON解析器支持的恢复策略列表
#[command]
pub fn get_recovery_strategies() -> Result<Vec<String>, String> {
    Ok(vec![
        "StandardJson".to_string(),
        "ManualFix".to_string(),
        "RegexExtract".to_string(),
        "PartialParse".to_string(),
    ])
}

/// 获取默认解析器配置
#[command]
pub fn get_default_parser_config() -> Result<JsonParserConfig, String> {
    let default_config = ParserConfig::default();
    
    Ok(JsonParserConfig {
        max_text_length: Some(default_config.max_text_length),
        enable_comments: Some(default_config.enable_comments),
        enable_unquoted_keys: Some(default_config.enable_unquoted_keys),
        enable_trailing_commas: Some(default_config.enable_trailing_commas),
        timeout_ms: Some(default_config.timeout_ms),
        recovery_strategies: Some(vec![
            "StandardJson".to_string(),
            "ManualFix".to_string(),
            "RegexExtract".to_string(),
            "PartialParse".to_string(),
        ]),
    })
}
