/// 容错JSON解析器使用示例
/// 
/// 本文件包含了各种使用场景的示例代码，展示如何使用容错JSON解析器
/// 处理大模型返回的不规范JSON数据。

#[cfg(test)]
mod examples {
    use super::super::tolerant_json_parser::{TolerantJsonParser, CachedTolerantJsonParser, ParserConfig, RecoveryStrategy};
    use serde_json::json;

    /// 示例1: 基本使用
    #[test]
    fn example_basic_usage() {
        let mut parser = TolerantJsonParser::new(None).unwrap();
        
        // 处理标准JSON
        let standard_json = r#"{"name": "Alice", "age": 30}"#;
        let (result, stats) = parser.parse(standard_json).unwrap();
        println!("标准JSON解析结果: {:?}", result);
        println!("解析统计: 错误率 {:.2}%", stats.error_rate * 100.0);
        
        assert_eq!(result, json!({"name": "Alice", "age": 30}));
        assert_eq!(stats.error_rate, 0.0);
    }

    /// 示例2: 处理Markdown包裹的JSON
    #[test]
    fn example_markdown_wrapped() {
        let mut parser = TolerantJsonParser::new(None).unwrap();
        
        let markdown_json = r#"
        以下是用户信息的JSON数据：
        
        ```json
        {
            "user": {
                "name": "Bob",
                "email": "bob@example.com"
            }
        }
        ```
        
        请注意检查数据的完整性。
        "#;
        
        let (result, stats) = parser.parse(markdown_json).unwrap();
        println!("Markdown包裹JSON解析结果: {:?}", result);
        
        let expected = json!({
            "user": {
                "name": "Bob",
                "email": "bob@example.com"
            }
        });
        assert_eq!(result, expected);
    }

    /// 示例3: 处理无引号键和尾随逗号
    #[test]
    fn example_malformed_json() {
        let mut parser = TolerantJsonParser::new(None).unwrap();
        
        let malformed_json = r#"{
            name: "Charlie",
            age: 25,
            hobbies: ["reading", "coding",],
            active: true,
        }"#;
        
        let (result, stats) = parser.parse(malformed_json).unwrap();
        println!("格式错误JSON解析结果: {:?}", result);
        println!("使用的恢复策略: {:?}", stats.recovery_strategies_used);
        
        // 验证解析结果
        assert!(result.is_object());
        assert!(stats.recovery_strategies_used.len() > 0);
    }

    /// 示例4: 使用自定义配置
    #[test]
    fn example_custom_config() {
        let config = ParserConfig {
            max_text_length: 1024,
            enable_comments: true,
            enable_unquoted_keys: true,
            enable_trailing_commas: true,
            timeout_ms: 10000,
            recovery_strategies: vec![
                RecoveryStrategy::StandardJson,
                RecoveryStrategy::ManualFix,
            ],
        };
        
        let mut parser = TolerantJsonParser::new(Some(config)).unwrap();
        
        let json_with_comments = r#"{
            // 用户基本信息
            "name": "David",
            "age": 28,
            /* 联系方式 */
            "email": "david@example.com"
        }"#;
        
        let (result, stats) = parser.parse(json_with_comments).unwrap();
        println!("带注释JSON解析结果: {:?}", result);
        
        assert!(result.is_object());
    }

    /// 示例5: 使用缓存解析器
    #[test]
    fn example_cached_parser() {
        let cached_parser = CachedTolerantJsonParser::new(None, Some(100)).unwrap();
        
        let json_text = r#"{"product": "laptop", "price": 999.99}"#;
        
        // 第一次解析 - 会被缓存
        let start = std::time::Instant::now();
        let (result1, _) = cached_parser.parse(json_text).unwrap();
        let first_duration = start.elapsed();
        
        // 第二次解析 - 使用缓存
        let start = std::time::Instant::now();
        let (result2, _) = cached_parser.parse(json_text).unwrap();
        let second_duration = start.elapsed();
        
        println!("第一次解析耗时: {:?}", first_duration);
        println!("第二次解析耗时: {:?}", second_duration);
        println!("缓存统计: {:?}", cached_parser.get_cache_stats());
        
        assert_eq!(result1, result2);
        // 第二次解析应该更快（使用缓存）
        assert!(second_duration <= first_duration);
    }

    /// 示例6: 处理部分损坏的JSON
    #[test]
    fn example_partial_json() {
        let mut parser = TolerantJsonParser::new(None).unwrap();
        
        let partial_json = r#"{
            "status": "success",
            "data": {
                "items": [
                    {"id": 1, "name": "item1"},
                    {"id": 2, "name": "item2"
                    // 这里缺少闭合括号和逗号
        "#;
        
        let (result, stats) = parser.parse(partial_json).unwrap();
        println!("部分损坏JSON解析结果: {:?}", result);
        println!("错误率: {:.2}%", stats.error_rate * 100.0);
        
        // 即使JSON不完整，也应该能解析出部分内容
        assert!(result.is_object() || result.is_string());
        assert!(stats.error_rate > 0.0);
    }

    /// 示例7: 批量处理多个JSON
    #[test]
    fn example_batch_processing() {
        let cached_parser = CachedTolerantJsonParser::new(None, Some(50)).unwrap();
        
        let json_samples = vec![
            r#"{"type": "user", "id": 1}"#,
            r#"{type: "product", id: 2,}"#,
            r#"```json
            {"type": "order", "id": 3}
            ```"#,
            r#"{"type": "invalid", "id": "#, // 不完整的JSON
        ];
        
        let mut results = Vec::new();
        let mut total_errors = 0;
        
        for (i, json_text) in json_samples.iter().enumerate() {
            match cached_parser.parse(json_text) {
                Ok((result, stats)) => {
                    results.push(result);
                    if stats.error_rate > 0.0 {
                        total_errors += 1;
                    }
                    println!("样本 {}: 解析成功，错误率 {:.2}%", i + 1, stats.error_rate * 100.0);
                }
                Err(e) => {
                    println!("样本 {}: 解析失败 - {}", i + 1, e);
                    total_errors += 1;
                }
            }
        }
        
        println!("批量处理完成: {} 个样本，{} 个有错误", json_samples.len(), total_errors);
        println!("缓存统计: {:?}", cached_parser.get_cache_stats());
        
        assert!(results.len() > 0);
    }

    /// 示例8: 错误处理和恢复策略
    #[test]
    fn example_error_handling() {
        let mut parser = TolerantJsonParser::new(None).unwrap();
        
        let problematic_inputs = vec![
            (r#"{'single': 'quotes'}"#, "单引号"),
            (r#"{unquoted: "keys"}"#, "无引号键"),
            (r#"{"trailing": "comma",}"#, "尾随逗号"),
            (r#"{"mixed": 'quotes'}"#, "混合引号"),
        ];
        
        for (input, description) in problematic_inputs {
            match parser.parse(input) {
                Ok((result, stats)) => {
                    println!("{}: 解析成功", description);
                    println!("  结果: {:?}", result);
                    println!("  恢复策略: {:?}", stats.recovery_strategies_used);
                    println!("  错误率: {:.2}%", stats.error_rate * 100.0);
                }
                Err(e) => {
                    println!("{}: 解析失败 - {}", description, e);
                }
            }
            println!("---");
        }
    }

    /// 示例9: 性能测试
    #[test]
    fn example_performance_test() {
        let mut parser = TolerantJsonParser::new(None).unwrap();
        let cached_parser = CachedTolerantJsonParser::new(None, Some(1000)).unwrap();
        
        // 创建一个较大的JSON
        let large_json = json!({
            "users": (0..100).map(|i| json!({
                "id": i,
                "name": format!("user_{}", i),
                "email": format!("user_{}@example.com", i)
            })).collect::<Vec<_>>()
        });
        let json_text = serde_json::to_string(&large_json).unwrap();
        
        // 测试普通解析器
        let start = std::time::Instant::now();
        for _ in 0..10 {
            let _ = parser.parse(&json_text).unwrap();
        }
        let normal_duration = start.elapsed();
        
        // 测试缓存解析器
        let start = std::time::Instant::now();
        for _ in 0..10 {
            let _ = cached_parser.parse(&json_text).unwrap();
        }
        let cached_duration = start.elapsed();
        
        println!("普通解析器 10 次解析耗时: {:?}", normal_duration);
        println!("缓存解析器 10 次解析耗时: {:?}", cached_duration);
        println!("性能提升: {:.2}x", normal_duration.as_nanos() as f64 / cached_duration.as_nanos() as f64);
        
        // 缓存解析器应该更快
        assert!(cached_duration < normal_duration);
    }

    /// 示例10: 实际应用场景 - 处理AI模型响应
    #[test]
    fn example_ai_model_response() {
        let mut parser = TolerantJsonParser::new(None).unwrap();
        
        // 模拟AI模型返回的响应
        let ai_responses = vec![
            // GPT风格响应
            r#"
            根据您的请求，这里是分析结果：
            
            ```json
            {
                "analysis": {
                    "sentiment": "positive",
                    "confidence": 0.85,
                    "keywords": ["good", "excellent", "satisfied"]
                },
                "recommendation": "continue current strategy"
            }
            ```
            
            希望这个分析对您有帮助。
            "#,
            
            // Claude风格响应（可能包含格式错误）
            r#"Here's the structured data you requested:
            
            {
                task: "data_extraction",
                results: [
                    {id: 1, status: "completed"},
                    {id: 2, status: "pending",}
                ],
                summary: {
                    total: 2,
                    completed: 1,
                    pending: 1
                }
            }"#,
        ];
        
        for (i, response) in ai_responses.iter().enumerate() {
            match parser.parse(response) {
                Ok((result, stats)) => {
                    println!("AI响应 {} 解析成功:", i + 1);
                    println!("  数据: {:?}", result);
                    println!("  统计: 错误率 {:.2}%, 恢复策略 {:?}", 
                            stats.error_rate * 100.0, stats.recovery_strategies_used);
                }
                Err(e) => {
                    println!("AI响应 {} 解析失败: {}", i + 1, e);
                }
            }
            println!("---");
        }
    }
}
