use serde_json::Value;
use std::collections::HashMap;
use std::fs;

use crate::template_engine::{TemplateEngine, TemplateContext, MainIndexContext, ApiMethod, ApiParameter, TypeDefinition, TypeProperty, EnumValue, FolderInfo};

#[derive(Debug, Clone)]
pub struct TypeScriptGenerator {
    pub schemas: HashMap<String, Value>,
    pub paths: HashMap<String, Value>,
    pub folder_structure: HashMap<String, Vec<String>>, // folder_name -> list of paths
    pub template_engine: Option<TemplateEngine>,
}

impl TypeScriptGenerator {
    pub fn new(openapi_doc: &Value) -> Self {
        let schemas = openapi_doc
            .get("components")
            .and_then(|c| c.get("schemas"))
            .and_then(|s| s.as_object())
            .map(|obj| {
                obj.iter()
                    .map(|(k, v)| (k.clone(), v.clone()))
                    .collect()
            })
            .unwrap_or_default();

        let paths = openapi_doc
            .get("paths")
            .and_then(|p| p.as_object())
            .map(|obj| {
                obj.iter()
                    .map(|(k, v)| (k.clone(), v.clone()))
                    .collect()
            })
            .unwrap_or_default();

        // 分析文件夹结构
        let folder_structure = Self::analyze_folder_structure(&paths);

        Self { 
            schemas, 
            paths, 
            folder_structure,
            template_engine: None,
        }
    }

    fn analyze_folder_structure(paths: &HashMap<String, Value>) -> HashMap<String, Vec<String>> {
        let mut folder_structure: HashMap<String, Vec<String>> = HashMap::new();
        
        for (path, path_item) in paths {
            if let Some(methods) = path_item.as_object() {
                for (_method, operation) in methods {
                    if let Some(operation_obj) = operation.as_object() {
                        if let Some(folder_name) = operation_obj.get("x-apifox-folder").and_then(|f| f.as_str()) {
                            let folder_name = if folder_name.is_empty() { "未分类" } else { folder_name };
                            folder_structure
                                .entry(folder_name.to_string())
                                .or_insert_with(Vec::new)
                                .push(path.clone());
                        }
                    }
                }
            }
        }
        
        folder_structure
    }

    pub fn with_templates(mut self, template_dir: &str) -> Result<Self, Box<dyn std::error::Error>> {
        let template_engine = TemplateEngine::new(template_dir)?;
        self.template_engine = Some(template_engine);
        Ok(self)
    }

    pub fn generate_types(&self) -> String {
        let mut output = String::new();
        
        // 添加文件头注释
        output.push_str("// 此文件由 apifox-flow 自动生成，请勿手动修改\n");
        output.push_str("// Generated by apifox-flow, do not edit manually\n\n");

        // 生成所有 schema 类型
        for (name, schema) in &self.schemas {
            if let Some(ts_type) = self.schema_to_typescript(name, schema) {
                output.push_str(&ts_type);
                output.push_str("\n\n");
            }
        }

        output
    }

    fn schema_to_typescript(&self, name: &str, schema: &Value) -> Option<String> {
        let mut output = String::new();
        
        // 处理枚举类型
        if let Some(enum_values) = schema.get("enum") {
            output.push_str(&format!("export enum {} {{\n", name));
            if let Some(descriptions) = schema.get("x-apifox").and_then(|x| x.get("enumDescriptions")) {
                for value in enum_values.as_array()?.iter() {
                    if let Some(desc) = descriptions.get(value.as_str()?) {
                        if !desc.as_str()?.is_empty() {
                            output.push_str(&format!("  // {}\n", desc.as_str()?));
                        }
                    }
                    output.push_str(&format!("  {} = \"{}\",\n", 
                        value.as_str()?.to_uppercase().replace("-", "_"), 
                        value.as_str()?));
                }
            } else {
                for value in enum_values.as_array()? {
                    output.push_str(&format!("  {} = \"{}\",\n", 
                        value.as_str()?.to_uppercase().replace("-", "_"), 
                        value.as_str()?));
                }
            }
            output.push_str("}\n");
            return Some(output);
        }

        // 处理对象类型
        if let Some(properties) = schema.get("properties") {
            output.push_str(&format!("export interface {} {{\n", name));
            
            if let Some(required) = schema.get("required").and_then(|r| r.as_array()) {
                for (prop_name, prop_schema) in properties.as_object()? {
                    let is_required = required.contains(&Value::String(prop_name.clone()));
                    let prop_type = self.property_to_typescript(prop_schema)?;
                    let optional = if is_required { "" } else { "?" };
                    
                    output.push_str(&format!("  {}{}: {};\n", prop_name, optional, prop_type));
                }
            } else {
                for (prop_name, prop_schema) in properties.as_object()? {
                    let prop_type = self.property_to_typescript(prop_schema)?;
                    output.push_str(&format!("  {}?: {};\n", prop_name, prop_type));
                }
            }
            
            output.push_str("}\n");
            return Some(output);
        }

        // 处理数组类型
        if let Some(items) = schema.get("items") {
            let item_type = self.property_to_typescript(items)?;
            output.push_str(&format!("export type {} = {}[];\n", name, item_type));
            return Some(output);
        }

        // 处理基本类型
        if let Some(type_str) = schema.get("type").and_then(|t| t.as_str()) {
            let ts_type = match type_str {
                "string" => "string",
                "number" | "integer" => "number",
                "boolean" => "boolean",
                "array" => "any[]",
                _ => "any",
            };
            output.push_str(&format!("export type {} = {};\n", name, ts_type));
            return Some(output);
        }

        None
    }

    fn property_to_typescript(&self, prop: &Value) -> Option<String> {
        // 处理引用
        if let Some(ref_path) = prop.get("$ref").and_then(|r| r.as_str()) {
            if let Some(type_name) = ref_path.split('/').last() {
                return Some(type_name.to_string());
            }
        }

        // 处理枚举
        if let Some(enum_values) = prop.get("enum") {
            let mut enum_str = String::new();
            for (i, value) in enum_values.as_array()?.iter().enumerate() {
                if i > 0 {
                    enum_str.push_str(" | ");
                }
                enum_str.push_str(&format!("\"{}\"", value.as_str()?));
            }
            return Some(enum_str);
        }

        // 处理数组
        if let Some(items) = prop.get("items") {
            let item_type = self.property_to_typescript(items)?;
            return Some(format!("{}[]", item_type));
        }

        // 处理基本类型
        if let Some(type_str) = prop.get("type").and_then(|t| t.as_str()) {
            match type_str {
                "string" => {
                    if prop.get("nullable").and_then(|n| n.as_bool()).unwrap_or(false) {
                        return Some("string | null".to_string());
                    }
                    return Some("string".to_string());
                }
                "number" | "integer" => {
                    if prop.get("nullable").and_then(|n| n.as_bool()).unwrap_or(false) {
                        return Some("number | null".to_string());
                    }
                    return Some("number".to_string());
                }
                "boolean" => {
                    if prop.get("nullable").and_then(|n| n.as_bool()).unwrap_or(false) {
                        return Some("boolean | null".to_string());
                    }
                    return Some("boolean".to_string());
                }
                "array" => return Some("any[]".to_string()),
                "object" => {
                    // 如果有 properties，生成一个内联接口
                    if let Some(properties) = prop.get("properties") {
                        if let Some(properties_obj) = properties.as_object() {
                            if !properties_obj.is_empty() {
                                let mut interface_str = String::new();
                                interface_str.push_str("{\n");
                                
                                for (prop_name, prop_schema) in properties_obj {
                                    if let Some(prop_type) = self.property_to_typescript(prop_schema) {
                                        let required = prop_schema.get("required").and_then(|r| r.as_bool()).unwrap_or(false);
                                        let optional = if required { "" } else { "?" };
                                        interface_str.push_str(&format!("  {}{}: {};\n", prop_name, optional, prop_type));
                                    }
                                }
                                
                                interface_str.push_str("}");
                                return Some(interface_str);
                            }
                        }
                    }
                    return Some("Record<string, any>".to_string());
                },
                _ => return Some("any".to_string()),
            }
        }

        Some("any".to_string())
    }

    pub fn generate_api_client(&self) -> String {
        let mut output = String::new();
        
        output.push_str("// API 客户端\n");
        output.push_str("// API Client\n\n");
        output.push_str("export class ApiClient {\n");
        output.push_str("  private baseUrl: string;\n");
        output.push_str("  private headers: Record<string, string>;\n\n");
        
        output.push_str("  constructor(baseUrl: string = '', headers: Record<string, string> = {}) {\n");
        output.push_str("    this.baseUrl = baseUrl;\n");
        output.push_str("    this.headers = { 'Content-Type': 'application/json', ...headers };\n");
        output.push_str("  }\n\n");

        // 生成 API 方法
        for (path, path_item) in &self.paths {
            if let Some(methods) = path_item.as_object() {
                for (method, operation) in methods {
                    if let Some(operation_obj) = operation.as_object() {
                        if let Some(summary) = operation_obj.get("summary").and_then(|s| s.as_str()) {
                            let method_name = self.path_to_method_name(path, method, summary);
                            let parameters = self.extract_parameters(&Value::Object(operation_obj.clone()));
                            let response_type = self.extract_response_type_with_method_name(&Value::Object(operation_obj.clone()), path, method, summary);
                            
                            output.push_str(&format!("  // {}\n", summary));
                            output.push_str(&format!("  async {}(", method_name));
                            
                            if !parameters.is_empty() {
                                output.push_str(&format!("params: {{ {} }}", parameters.join(", ")));
                            }
                            
                            output.push_str(&format!("): Promise<{}> {{\n", response_type));
                            output.push_str(&format!("    const response = await fetch(`${{this.baseUrl}}{}`, {{\n", path));
                            output.push_str(&format!("      method: '{}',\n", method.to_uppercase()));
                            output.push_str("      headers: this.headers,\n");
                            
                            if method.to_lowercase() != "get" {
                                output.push_str("      body: JSON.stringify(params),\n");
                            }
                            
                            output.push_str("    });\n");
                            output.push_str("    return response.json();\n");
                            output.push_str("  }\n\n");
                        }
                    }
                }
            }
        }

        output.push_str("}\n");
        output
    }

    fn path_to_method_name(&self, path: &str, method: &str, _summary: &str) -> String {
        // 使用路径和方法的组合来生成唯一的方法名
        let path_method_key = format!("{}_{}", path, method);
        // 从路径和方法生成方法名，确保唯一性
        let path_parts: Vec<&str> = path.split('/').filter(|p| !p.is_empty() && !p.starts_with('{')).collect();
        let method_prefix = match method.to_lowercase().as_str() {
            "get" => "get",
            "post" => "create",
            "put" => "update",
            "delete" => "delete",
            "patch" => "patch",
            _ => "call",
        };
        
        if path_parts.is_empty() {
            return format!("{}Api", method_prefix);
        }
        
        // 构建更完整的方法名，包含路径的关键部分
        let mut method_name = method_prefix.to_string();
        
        // 过滤掉常见的通用词，保留有意义的路径部分
        let meaningful_parts: Vec<&str> = path_parts.iter()
            .filter(|part| {
                let part_lower = part.to_lowercase();
                !part_lower.contains("api") && 
                !part_lower.contains("v1") && 
                !part_lower.contains("v2") &&
                !part_lower.contains("oboss")
            })
            .cloned()
            .collect();
        
        if meaningful_parts.len() >= 2 {
            // 使用最后两个有意义的部分
            let last_two: Vec<&str> = meaningful_parts.iter().rev().take(2).cloned().collect();
            for part in last_two.iter().rev() {
                let clean_part = part.replace("-", "").replace("_", "");
                if !clean_part.is_empty() {
                    method_name.push_str(&self.to_pascal_case(&clean_part));
                }
            }
        } else if meaningful_parts.len() == 1 {
            // 只有一个有意义的部分
            let clean_part = meaningful_parts[0].replace("-", "").replace("_", "");
            method_name.push_str(&self.to_pascal_case(&clean_part));
        } else {
            // 没有有意义的部分，使用原始路径的最后部分
            let resource = path_parts.last().unwrap_or(&"resource");
            let clean_resource = resource.replace("-", "").replace("_", "");
            method_name.push_str(&self.to_pascal_case(&clean_resource));
        }
        
        // 为了确保唯一性，使用路径和方法的组合哈希
        let path_method_signature = path_method_key.replace("/", "").replace("-", "").replace("_", "").replace("{", "").replace("}", "");
        if !path_method_signature.is_empty() {
            // 使用路径+方法的签名来确保唯一性
            let suffix_length = (path_method_signature.len() / 2).max(4).min(8);
            let suffix = &path_method_signature[..suffix_length];
            method_name.push_str(&self.to_pascal_case(suffix));
        }
        
        method_name
    }

    fn to_pascal_case(&self, s: &str) -> String {
        let mut result = String::new();
        let mut capitalize = true;
        
        for c in s.chars() {
            if c == '_' || c == '-' {
                capitalize = true;
            } else if capitalize {
                result.push(c.to_uppercase().next().unwrap());
                capitalize = false;
            } else {
                result.push(c);
            }
        }
        
        result
    }

    fn to_camel_case(&self, s: &str) -> String {
        let mut result = String::new();
        let mut capitalize = false;
        
        for c in s.chars() {
            if c == '_' || c == '-' {
                capitalize = true;
            } else if capitalize {
                result.push(c.to_uppercase().next().unwrap());
                capitalize = false;
            } else {
                result.push(c);
            }
        }
        
        result
    }

    fn extract_parameters(&self, operation: &Value) -> Vec<String> {
        let mut params = Vec::new();
        
        if let Some(parameters) = operation.get("parameters").and_then(|p| p.as_array()) {
            for param in parameters {
                if let Some(name) = param.get("name").and_then(|n| n.as_str()) {
                    let camel_case_name = self.to_camel_case(name);
                    let param_type = self.parameter_to_typescript(param);
                    let required = param.get("required").and_then(|r| r.as_bool()).unwrap_or(false);
                    let optional = if required { "" } else { "?" };
                    params.push(format!("{}{}: {}", camel_case_name, optional, param_type));
                }
            }
        }
        
        if operation.get("requestBody").is_some() {
            params.push("body: any".to_string());
        }
        
        params
    }

    fn parameter_to_typescript(&self, param: &Value) -> String {
        if let Some(schema) = param.get("schema") {
            if let Some(type_str) = schema.get("type").and_then(|t| t.as_str()) {
                match type_str {
                    "string" => "string",
                    "number" | "integer" => "number",
                    "boolean" => "boolean",
                    "array" => "any[]",
                    _ => "any",
                }.to_string()
            } else {
                "any".to_string()
            }
        } else {
            "any".to_string()
        }
    }

    fn extract_response_type(&self, operation: &Value) -> String {
        if let Some(responses) = operation.get("responses") {
            // 优先查找 200 响应
            if let Some(success_response) = responses.get("200") {
                return self.extract_data_type_from_response(success_response);
            }
            
            // 如果没有 200，查找其他成功状态码
            for (status_code, response) in responses.as_object().unwrap_or(&serde_json::Map::new()) {
                if status_code.starts_with("2") {
                    return self.extract_data_type_from_response(response);
                }
            }
            
            // 如果都没有，查找第一个响应
            if let Some(first_response) = responses.as_object().and_then(|obj| obj.values().next()) {
                return self.extract_data_type_from_response(first_response);
            }
        }
        "any".to_string()
    }
    
    fn extract_data_type_from_response(&self, response: &Value) -> String {
        if let Some(content) = response.get("content") {
            // 优先查找 application/json
            if let Some(json_content) = content.get("application/json") {
                if let Some(schema) = json_content.get("schema") {
                    // 处理 $ref 引用
                    if let Some(ref_path) = schema.get("$ref").and_then(|r| r.as_str()) {
                        if let Some(type_name) = ref_path.split('/').last() {
                            return type_name.to_string();
                        }
                    }
                    
                    // 处理内联的响应结构
                    if let Some(properties) = schema.get("properties") {
                        // 检查是否是标准的 API 响应格式 (code, message, data)
                        if let Some(data_prop) = properties.get("data") {
                            return self.extract_data_field_type(data_prop);
                        }
                    }
                }
            }
        }
        "any".to_string()
    }
    
    fn extract_data_field_type(&self, data_schema: &Value) -> String {
        // 处理 $ref 引用
        if let Some(ref_path) = data_schema.get("$ref").and_then(|r| r.as_str()) {
            if let Some(type_name) = ref_path.split('/').last() {
                return type_name.to_string();
            }
        }
        
        // 处理直接的类型定义
        if let Some(type_str) = data_schema.get("type").and_then(|t| t.as_str()) {
            match type_str {
                "string" => "string".to_string(),
                "number" | "integer" => "number".to_string(),
                "boolean" => "boolean".to_string(),
                "array" => {
                    if let Some(items) = data_schema.get("items") {
                        let item_type = self.extract_data_field_type(items);
                        format!("{}[]", item_type)
                    } else {
                        "any[]".to_string()
                    }
                },
                "object" => {
                    // 对于对象类型，生成一个具体的接口名
                    if let Some(properties) = data_schema.get("properties") {
                        if let Some(properties_obj) = properties.as_object() {
                            if !properties_obj.is_empty() {
                                // 生成一个基于属性的接口名
                                return "DataObject".to_string();
                            }
                        }
                    }
                    "Record<string, any>".to_string()
                },
                _ => "any".to_string(),
            }
        } else {
            "any".to_string()
        }
    }
    
    fn extract_response_type_with_method_name(&self, operation: &Value, path: &str, method: &str, summary: &str) -> String {
        if let Some(responses) = operation.get("responses") {
            // 优先查找 200 响应
            if let Some(success_response) = responses.get("200") {
                if let Some(content) = success_response.get("content") {
                    if let Some(json_content) = content.get("application/json") {
                        if let Some(schema) = json_content.get("schema") {
                            // 处理 $ref 引用
                            if let Some(ref_path) = schema.get("$ref").and_then(|r| r.as_str()) {
                                if let Some(type_name) = ref_path.split('/').last() {
                                    return type_name.to_string();
                                }
                            }
                            
                            // 处理内联的响应结构
                            if let Some(properties) = schema.get("properties") {
                                if let Some(data_prop) = properties.get("data") {
                                    let method_name = self.path_to_method_name(path, method, summary);
                                    let data_type_name = format!("{}Data", self.to_pascal_case(&method_name));
                                    
                                    if let Some(data_type) = data_prop.get("type").and_then(|t| t.as_str()) {
                                        if data_type == "object" {
                                            if let Some(_data_properties) = data_prop.get("properties") {
                                                return data_type_name;
                                            }
                                        } else if data_type == "array" {
                                            if let Some(items) = data_prop.get("items") {
                                                if let Some(item_type) = items.get("type").and_then(|t| t.as_str()) {
                                                    if item_type == "object" {
                                                        if let Some(_item_properties) = items.get("properties") {
                                                            let item_type_name = format!("{}Item", data_type_name);
                                                            return format!("{}[]", item_type_name);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    
                                    return self.extract_data_field_type(data_prop);
                                }
                            }
                        }
                    }
                }
            }
        }
        "any".to_string()
    }
    
    fn extract_schema_type(&self, response: &Value) -> String {
        if let Some(content) = response.get("content") {
            // 优先查找 application/json
            if let Some(json_content) = content.get("application/json") {
                return self.response_schema_to_typescript(json_content.get("schema"));
            }
            
            // 查找其他 JSON 类型
            for (content_type, content_data) in content.as_object().unwrap_or(&serde_json::Map::new()) {
                if content_type.contains("json") {
                    return self.response_schema_to_typescript(content_data.get("schema"));
                }
            }
        }
        "any".to_string()
    }
    
    fn response_schema_to_typescript(&self, schema: Option<&Value>) -> String {
        if let Some(schema) = schema {
            // 处理 $ref 引用
            if let Some(ref_path) = schema.get("$ref").and_then(|r| r.as_str()) {
                if let Some(type_name) = ref_path.split('/').last() {
                    return type_name.to_string();
                }
            }
            
            // 处理直接的类型定义
            if let Some(type_str) = schema.get("type").and_then(|t| t.as_str()) {
                match type_str {
                    "string" => "string".to_string(),
                    "number" | "integer" => "number".to_string(),
                    "boolean" => "boolean".to_string(),
                    "array" => {
                        if let Some(items) = schema.get("items") {
                            let item_type = self.response_schema_to_typescript(Some(items));
                            format!("{}[]", item_type)
                        } else {
                            "any[]".to_string()
                        }
                    },
                    "object" => {
                        // 对于对象类型，尝试生成接口名
                        if let Some(title) = schema.get("title").and_then(|t| t.as_str()) {
                            return title.to_string();
                        }
                        // 如果有 properties，尝试解析具体的对象结构
                        if let Some(properties) = schema.get("properties") {
                            // 检查是否是标准的 API 响应格式 (code, message, data)
                            if let (Some(code), Some(message), Some(data)) = (
                                properties.get("code"),
                                properties.get("message"), 
                                properties.get("data")
                            ) {
                                // 这是一个标准的 API 响应格式
                                if let Some(data_schema) = data.get("type").and_then(|t| t.as_str()) {
                                    if data_schema == "object" {
                                        // 如果 data 是对象，尝试解析其结构
                                        if let Some(data_properties) = data.get("properties") {
                                            // 生成一个具体的响应类型名
                                            return "ApiResponse".to_string();
                                        }
                                    }
                                }
                                "ApiResponse".to_string()
                            } else {
                                // 不是标准格式，生成一个通用的响应类型
                                "ApiResponse".to_string()
                            }
                        } else {
                            "Record<string, any>".to_string()
                        }
                    },
                    _ => "any".to_string(),
                }
            } else {
                "any".to_string()
            }
        } else {
            "any".to_string()
        }
    }

    pub fn generate_all(&self) -> String {
        let mut output = String::new();
        output.push_str(&self.generate_types());
        output.push_str("\n");
        output.push_str(&self.generate_api_client());
        output
    }

    pub fn save_to_file(&self, filename: &str) -> Result<(), Box<dyn std::error::Error>> {
        let content = self.generate_all();
        fs::write(filename, content)?;
        Ok(())
    }

    // 按文件夹生成分离的 TypeScript 文件
    pub fn generate_by_folders(&self, output_dir: &str) -> Result<(), Box<dyn std::error::Error>> {
        // 创建输出目录
        fs::create_dir_all(output_dir)?;
        
        // 为每个文件夹生成单独的文件
        for (folder_name, paths) in &self.folder_structure {
            let safe_folder_name = self.sanitize_folder_name(folder_name);
            let folder_dir = format!("{}/{}", output_dir, safe_folder_name);
            fs::create_dir_all(&folder_dir)?;
            
            // 生成该文件夹的 API 客户端
            let api_client_content = self.generate_folder_api_client(folder_name, paths);
            let api_file = format!("{}/api.ts", folder_dir);
            fs::write(&api_file, api_client_content)?;
            
            // 生成该文件夹的类型定义
            let types_content = self.generate_folder_types(folder_name, paths);
            let types_file = format!("{}/types.ts", folder_dir);
            fs::write(&types_file, types_content)?;
            
            // 生成该文件夹的索引文件
            let index_content = self.generate_folder_index(&safe_folder_name);
            let index_file = format!("{}/index.ts", folder_dir);
            fs::write(&index_file, index_content)?;
            
            println!("已生成文件夹 '{}' 的代码到 {}", folder_name, folder_dir);
        }
        
        // 生成主索引文件
        let main_index = self.generate_main_index();
        let main_index_file = format!("{}/index.ts", output_dir);
        fs::write(&main_index_file, main_index)?;
        
        println!("已生成主索引文件到 {}", main_index_file);
        Ok(())
    }

    fn sanitize_folder_name(&self, folder_name: &str) -> String {
        folder_name
            .replace("/", "_")
            .replace(" ", "_")
            .replace("&", "and")
            .replace("(", "")
            .replace(")", "")
            .replace("（", "")
            .replace("）", "")
            .replace("已废弃", "deprecated")
            .to_lowercase()
    }

    fn generate_folder_api_client(&self, folder_name: &str, paths: &[String]) -> String {
        let mut output = String::new();
        let mut used_method_names = std::collections::HashSet::new();
        
        output.push_str(&format!("// {} API 客户端\n", folder_name));
        output.push_str("// Generated by apifox-flow, do not edit manually\n\n");
        output.push_str("export class ApiClient {\n");
        output.push_str("  private baseUrl: string;\n");
        output.push_str("  private headers: Record<string, string>;\n\n");
        
        output.push_str("  constructor(baseUrl: string = '', headers: Record<string, string> = {}) {\n");
        output.push_str("    this.baseUrl = baseUrl;\n");
        output.push_str("    this.headers = { 'Content-Type': 'application/json', ...headers };\n");
        output.push_str("  }\n\n");

        // 生成该文件夹的 API 方法
        for path in paths {
            if let Some(path_item) = self.paths.get(path) {
                if let Some(methods) = path_item.as_object() {
                    for (method, operation) in methods {
                        if let Some(operation_obj) = operation.as_object() {
                            if let Some(folder) = operation_obj.get("x-apifox-folder").and_then(|f| f.as_str()) {
                                if folder == folder_name {
                                    if let Some(summary) = operation_obj.get("summary").and_then(|s| s.as_str()) {
                                        let mut method_name = self.path_to_method_name(path, method, summary);
                                        
                                        // 确保方法名唯一
                                        let mut counter = 1;
                                        let original_method_name = method_name.clone();
                                        while used_method_names.contains(&method_name) {
                                            method_name = format!("{}{}", original_method_name, counter);
                                            counter += 1;
                                        }
                                        used_method_names.insert(method_name.clone());
                                        let parameters = self.extract_parameters(&Value::Object(operation_obj.clone()));
                                        let response_type = self.extract_response_type_with_method_name(&Value::Object(operation_obj.clone()), path, method, summary);
                                        
                                        output.push_str(&format!("  // {}\n", summary));
                                        output.push_str(&format!("  async {}(", method_name));
                                        
                                        if !parameters.is_empty() {
                                            output.push_str(&format!("params: {{ {} }}", parameters.join(", ")));
                                        }
                                        
                                        output.push_str(&format!("): Promise<{}> {{\n", response_type));
                                        output.push_str(&format!("    const response = await fetch(`${{this.baseUrl}}{}`, {{\n", path));
                                        output.push_str(&format!("      method: '{}',\n", method.to_uppercase()));
                                        output.push_str("      headers: this.headers,\n");
                                        
                                        if method.to_lowercase() != "get" {
                                            output.push_str("      body: JSON.stringify(params),\n");
                                        }
                                        
                                        output.push_str("    });\n");
                                        output.push_str("    return response.json();\n");
                                        output.push_str("  }\n\n");
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        output.push_str("}\n");
        output
    }

    fn generate_folder_types(&self, folder_name: &str, paths: &[String]) -> String {
        let mut output = String::new();
        
        output.push_str(&format!("// {} 类型定义\n", folder_name));
        output.push_str("// Generated by apifox-flow, do not edit manually\n\n");
        
        // 添加通用的 API 响应类型
        output.push_str("// 通用 API 响应类型\n");
        output.push_str("export interface ApiResponse {\n");
        output.push_str("  code: string;\n");
        output.push_str("  message?: string;\n");
        output.push_str("  data?: any;\n");
        output.push_str("}\n\n");

        // 收集该文件夹相关的 schema
        let mut related_schemas = std::collections::HashSet::new();
        
        for path in paths {
            if let Some(path_item) = self.paths.get(path) {
                if let Some(methods) = path_item.as_object() {
                    for (_method, operation) in methods {
                        if let Some(operation_obj) = operation.as_object() {
                            if let Some(folder) = operation_obj.get("x-apifox-folder").and_then(|f| f.as_str()) {
                                if folder == folder_name {
                                    // 收集响应类型
                                    if let Some(responses) = operation_obj.get("responses") {
                                        if let Some(success_response) = responses.get("200") {
                                            if let Some(content) = success_response.get("content") {
                                                if let Some(json_content) = content.get("application/json") {
                                                    if let Some(schema) = json_content.get("schema") {
                                                        if let Some(ref_path) = schema.get("$ref").and_then(|r| r.as_str()) {
                                                            if let Some(type_name) = ref_path.split('/').last() {
                                                                related_schemas.insert(type_name.to_string());
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    
                                    // 收集请求体类型
                                    if let Some(request_body) = operation_obj.get("requestBody") {
                                        if let Some(content) = request_body.get("content") {
                                            if let Some(json_content) = content.get("application/json") {
                                                if let Some(schema) = json_content.get("schema") {
                                                    if let Some(ref_path) = schema.get("$ref").and_then(|r| r.as_str()) {
                                                        if let Some(type_name) = ref_path.split('/').last() {
                                                            related_schemas.insert(type_name.to_string());
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // 生成相关的类型定义
        for schema_name in related_schemas {
            if let Some(schema) = self.schemas.get(&schema_name) {
                if let Some(ts_type) = self.schema_to_typescript(&schema_name, schema) {
                    output.push_str(&ts_type);
                    output.push_str("\n\n");
                }
            }
        }

        output
    }

    fn generate_folder_index(&self, safe_folder_name: &str) -> String {
        format!(
            "// {} 模块导出\n\
            // Generated by apifox-flow, do not edit manually\n\n\
            export {{ ApiClient }} from './api';\n\
            export * from './types';\n",
            safe_folder_name
        )
    }

    fn generate_main_index(&self) -> String {
        let mut output = String::new();
        
        output.push_str("// 主索引文件\n");
        output.push_str("// Generated by apifox-flow, do not edit manually\n\n");
        
        for (folder_name, _) in &self.folder_structure {
            let safe_folder_name = self.sanitize_folder_name(folder_name);
            output.push_str(&format!("export * from './{}';\n", safe_folder_name));
        }
        
        output
    }

    // 生成单个文件夹的代码
    pub fn generate_single_folder(&self, folder_name: &str, output_dir: &str) -> Result<(), Box<dyn std::error::Error>> {
        // 检查文件夹是否存在
        if !self.folder_structure.contains_key(folder_name) {
            return Err(format!("文件夹 '{}' 不存在", folder_name).into());
        }

        let paths = &self.folder_structure[folder_name];
        let safe_folder_name = self.sanitize_folder_name(folder_name);
        let folder_dir = format!("{}/{}", output_dir, safe_folder_name);
        
        // 创建输出目录
        fs::create_dir_all(&folder_dir)?;
        
        // 生成该文件夹的 API 客户端
        let api_client_content = self.generate_folder_api_client(folder_name, paths);
        let api_file = format!("{}/api.ts", folder_dir);
        fs::write(&api_file, api_client_content)?;
        
        // 生成该文件夹的类型定义
        let types_content = self.generate_folder_types(folder_name, paths);
        let types_file = format!("{}/types.ts", folder_dir);
        fs::write(&types_file, types_content)?;
        
        // 生成该文件夹的索引文件
        let index_content = self.generate_folder_index(&safe_folder_name);
        let index_file = format!("{}/index.ts", folder_dir);
        fs::write(&index_file, index_content)?;
        
        println!("已生成文件夹 '{}' 的代码到 {}", folder_name, folder_dir);
        Ok(())
    }

    // 使用模板生成单个文件夹的代码
    pub fn generate_single_folder_with_template(
        &self, 
        folder_name: &str, 
        output_dir: &str,
        template_type: &str
    ) -> Result<(), Box<dyn std::error::Error>> {
        let template_engine = self.template_engine.as_ref()
            .ok_or("模板引擎未初始化")?;

        // 检查文件夹是否存在
        if !self.folder_structure.contains_key(folder_name) {
            return Err(format!("文件夹 '{}' 不存在", folder_name).into());
        }

        let paths = &self.folder_structure[folder_name];
        let safe_folder_name = self.sanitize_folder_name(folder_name);
        let folder_dir = format!("{}/{}", output_dir, safe_folder_name);
        
        // 创建输出目录
        fs::create_dir_all(&folder_dir)?;
        
        // 构建模板上下文
        let context = self.build_template_context(folder_name, paths)?;
        
            // 根据模板类型生成不同的文件
            match template_type {
                "advanced" => {
                    let api_content = template_engine.render_advanced_api_client(&context)?;
                    fs::write(format!("{}/api.ts", folder_dir), api_content)?;
                }
                "react" => {
                    let api_content = template_engine.render_api_client(&context)?;
                    fs::write(format!("{}/api.ts", folder_dir), api_content)?;
                    
                    let hooks_content = template_engine.render_react_hooks(&context)?;
                    fs::write(format!("{}/hooks.ts", folder_dir), hooks_content)?;
                }
                "oboss" => {
                    let api_content = template_engine.render_oboss_api(&context)?;
                    fs::write(format!("{}/api.ts", folder_dir), api_content)?;
                }
                _ => {
                    let api_content = template_engine.render_api_client(&context)?;
                    fs::write(format!("{}/api.ts", folder_dir), api_content)?;
                }
            }
        
        // 生成类型定义
        let types_content = template_engine.render_types(&context)?;
        fs::write(format!("{}/types.ts", folder_dir), types_content)?;
        
        // 生成索引文件
        let index_content = template_engine.render_index(&context)?;
        fs::write(format!("{}/index.ts", folder_dir), index_content)?;
        
        println!("已使用模板 '{}' 生成文件夹 '{}' 的代码到 {}", template_type, folder_name, folder_dir);
        Ok(())
    }

    // 使用模板生成所有文件夹的代码
    pub fn generate_by_folders_with_template(
        &self, 
        output_dir: &str,
        template_type: &str
    ) -> Result<(), Box<dyn std::error::Error>> {
        let template_engine = self.template_engine.as_ref()
            .ok_or("模板引擎未初始化")?;

        // 创建输出目录
        fs::create_dir_all(output_dir)?;
        
        // 为每个文件夹生成单独的文件
        for (folder_name, paths) in &self.folder_structure {
            let safe_folder_name = self.sanitize_folder_name(folder_name);
            let folder_dir = format!("{}/{}", output_dir, safe_folder_name);
            fs::create_dir_all(&folder_dir)?;
            
            // 构建模板上下文
            let context = self.build_template_context(folder_name, paths)?;
            
            // 根据模板类型生成不同的文件
            match template_type {
                "advanced" => {
                    let api_content = template_engine.render_advanced_api_client(&context)?;
                    fs::write(format!("{}/api.ts", folder_dir), api_content)?;
                }
                "react" => {
                    let api_content = template_engine.render_api_client(&context)?;
                    fs::write(format!("{}/api.ts", folder_dir), api_content)?;
                    
                    let hooks_content = template_engine.render_react_hooks(&context)?;
                    fs::write(format!("{}/hooks.ts", folder_dir), hooks_content)?;
                }
                "oboss" => {
                    let api_content = template_engine.render_oboss_api(&context)?;
                    fs::write(format!("{}/api.ts", folder_dir), api_content)?;
                }
                _ => {
                    let api_content = template_engine.render_api_client(&context)?;
                    fs::write(format!("{}/api.ts", folder_dir), api_content)?;
                }
            }
            
            // 生成类型定义
            let types_content = template_engine.render_types(&context)?;
            fs::write(format!("{}/types.ts", folder_dir), types_content)?;
            
            // 生成索引文件
            let index_content = template_engine.render_index(&context)?;
            fs::write(format!("{}/index.ts", folder_dir), index_content)?;
            
            println!("已使用模板 '{}' 生成文件夹 '{}' 的代码到 {}", template_type, folder_name, folder_dir);
        }
        
        // 生成主索引文件
        let main_context = self.build_main_index_context();
        let main_index = template_engine.render_main_index(&main_context)?;
        let main_index_file = format!("{}/index.ts", output_dir);
        fs::write(&main_index_file, main_index)?;
        
        println!("已使用模板 '{}' 生成主索引文件到 {}", template_type, main_index_file);
        Ok(())
    }

    fn build_template_context(&self, folder_name: &str, paths: &[String]) -> Result<TemplateContext, Box<dyn std::error::Error>> {
        let safe_folder_name = self.sanitize_folder_name(folder_name);
        let class_name = format!("{}ApiClient", self.to_pascal_case(&safe_folder_name));
        
        // 构建 API 方法列表
        let mut methods = Vec::new();
        let mut used_method_names = std::collections::HashSet::new();
        for path in paths {
            if let Some(path_item) = self.paths.get(path) {
                if let Some(path_methods) = path_item.as_object() {
                    for (method, operation) in path_methods {
                        if let Some(operation_obj) = operation.as_object() {
                            if let Some(folder) = operation_obj.get("x-apifox-folder").and_then(|f| f.as_str()) {
                                if folder == folder_name {
                                    if let Some(summary) = operation_obj.get("summary").and_then(|s| s.as_str()) {
                                        let mut method_name = self.path_to_method_name(path, method, summary);
                                        
                                        // 确保方法名唯一
                                        let mut counter = 1;
                                        let original_method_name = method_name.clone();
                                        while used_method_names.contains(&method_name) {
                                            method_name = format!("{}{}", original_method_name, counter);
                                            counter += 1;
                                        }
                                        used_method_names.insert(method_name.clone());
                                        let parameters = self.extract_parameters(&Value::Object(operation_obj.clone()));
                                        let response_type = self.extract_response_type_with_method_name(&Value::Object(operation_obj.clone()), path, method, summary);
                                        
                                        let api_parameters: Vec<ApiParameter> = parameters.iter()
                                            .map(|p| {
                                                let parts: Vec<&str> = p.split(": ").collect();
                                                let name = parts[0].replace("?", "");
                                                let type_ = parts[1].to_string();
                                                let required = !p.contains("?");
                                                
                                                // 判断参数类型：body 参数通常是对象类型，query 参数通常是基本类型
                                                let is_body_param = type_.contains("object") || type_.contains("Object") || 
                                                                   type_.contains("any") || type_.contains("{}") ||
                                                                   (method.to_lowercase() != "get" && !type_.contains("string") && !type_.contains("number"));
                                                let is_query_param = !is_body_param;
                                                
                                                ApiParameter {
                                                    name,
                                                    type_,
                                                    required,
                                                    is_body_param,
                                                    is_query_param,
                                                }
                                            })
                                            .collect();
                                        
                                        let http_method_lower = method.to_lowercase();
                                        let is_get = http_method_lower == "get";
                                        let has_body = api_parameters.iter().any(|p| p.is_body_param);
                                        let has_query_params = api_parameters.iter().any(|p| p.is_query_param);
                                        
                                        methods.push(ApiMethod {
                                            summary: summary.to_string(),
                                            method_name: method_name.clone(),
                                            method_name_pascal: self.to_pascal_case(&method_name),
                                            http_method: method.to_uppercase(),
                                            http_method_lower,
                                            path: path.clone(),
                                            parameters: api_parameters,
                                            response_type,
                                            is_get,
                                            has_body,
                                            has_query_params,
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // 构建类型定义列表
        let types = self.build_type_definitions(folder_name, paths);

        Ok(TemplateContext {
            folder_name: folder_name.to_string(),
            class_name,
            safe_folder_name,
            methods,
            types,
            imports: vec![],
            import_path: ".".to_string(),
            default_base_url: "".to_string(),
        })
    }

    fn build_type_definitions(&self, folder_name: &str, paths: &[String]) -> Vec<TypeDefinition> {
        let mut related_schemas = std::collections::HashSet::new();
        let mut response_types = std::collections::HashMap::new();
        
        // 收集相关的 schema 和响应类型
        for path in paths {
            if let Some(path_item) = self.paths.get(path) {
                if let Some(methods) = path_item.as_object() {
                    for (method, operation) in methods {
                        if let Some(operation_obj) = operation.as_object() {
                            if let Some(folder) = operation_obj.get("x-apifox-folder").and_then(|f| f.as_str()) {
                                if folder == folder_name {
                                    // 收集响应类型
                                    if let Some(responses) = operation_obj.get("responses") {
                                        if let Some(success_response) = responses.get("200") {
                                            if let Some(content) = success_response.get("content") {
                                                if let Some(json_content) = content.get("application/json") {
                                                    if let Some(schema) = json_content.get("schema") {
                                                        // 处理 $ref 引用
                                                        if let Some(ref_path) = schema.get("$ref").and_then(|r| r.as_str()) {
                                                            if let Some(type_name) = ref_path.split('/').last() {
                                                                related_schemas.insert(type_name.to_string());
                                                            }
                                                        } else {
                                                            // 处理内联的响应结构
                                                            if let Some(properties) = schema.get("properties") {
                                                                if let Some(data_prop) = properties.get("data") {
                                                                    // 为 data 字段生成具体的类型定义
                                                                    let method_name = self.path_to_method_name(path, method, 
                                                                        operation_obj.get("summary").and_then(|s| s.as_str()).unwrap_or(""));
                                                                    let data_type_name = format!("{}Data", self.to_pascal_case(&method_name));
                                                                    
                                                                    if let Some(data_type) = data_prop.get("type").and_then(|t| t.as_str()) {
                                                                        if data_type == "object" {
                                                                            if let Some(data_properties) = data_prop.get("properties") {
                                                                                // 生成一个具体的响应类型
                                                                                response_types.insert(data_type_name.clone(), data_properties.clone());
                                                                                related_schemas.insert(data_type_name);
                                                                            }
                                                                        } else if data_type == "array" {
                                                                            if let Some(items) = data_prop.get("items") {
                                                                                if let Some(item_type) = items.get("type").and_then(|t| t.as_str()) {
                                                                                    if item_type == "object" {
                                                                                        if let Some(item_properties) = items.get("properties") {
                                                                                            // 为数组元素生成类型
                                                                                            let item_type_name = format!("{}Item", data_type_name);
                                                                                            response_types.insert(item_type_name.clone(), item_properties.clone());
                                                                                            related_schemas.insert(item_type_name);
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // 构建类型定义
        let mut types = Vec::new();
        
        // 添加通用的 ApiResponse 类型
        types.push(TypeDefinition {
            name: "ApiResponse".to_string(),
            is_enum: false,
            is_interface: true,
            properties: vec![
                TypeProperty {
                    name: "code".to_string(),
                    type_: "string".to_string(),
                    required: true,
                    description: None,
                },
                TypeProperty {
                    name: "message".to_string(),
                    type_: "string".to_string(),
                    required: false,
                    description: None,
                },
                TypeProperty {
                    name: "data".to_string(),
                    type_: "any".to_string(),
                    required: false,
                    description: None,
                },
            ],
            enum_values: vec![],
            type_: "any".to_string(), // 设置一个默认值，虽然不会被使用
        });
        
        // 生成具体的响应类型
        for (type_name, properties) in response_types {
            println!("Processing response type: {}", type_name);
            if let Some(type_def) = self.properties_to_type_definition(&type_name, &properties) {
                println!("Generated type definition for: {} with {} properties", type_name, type_def.properties.len());
                types.push(type_def);
            } else {
                println!("Failed to generate type definition for: {}", type_name);
            }
        }
        
        println!("Total types generated: {}", types.len());
        
        for schema_name in related_schemas {
            if let Some(schema) = self.schemas.get(&schema_name) {
                if let Some(type_def) = self.schema_to_type_definition(&schema_name, schema) {
                    types.push(type_def);
                }
            }
        }

        // 添加属于当前文件夹的独立 schema
        for (schema_name, schema) in &self.schemas {
            if let Some(schema_obj) = schema.as_object() {
                if let Some(folder) = schema_obj.get("x-apifox-folder").and_then(|f| f.as_str()) {
                    // 处理文件夹名称的匹配，支持空格和驼峰命名的差异
                    let folder_normalized = folder.replace(" ", "").to_lowercase();
                    let folder_name_normalized = folder_name.replace(" ", "").to_lowercase();
                    
                    if folder_normalized == folder_name_normalized {
                        println!("Found schema {} in folder {} (matched with {})", schema_name, folder, folder_name);
                        if let Some(type_def) = self.schema_to_type_definition(schema_name, schema) {
                            types.push(type_def);
                        }
                    }
                }
            }
        }

        types
    }

    fn properties_to_type_definition(&self, name: &str, properties: &Value) -> Option<TypeDefinition> {
        let mut props = Vec::new();
        
        println!("Processing properties for type: {}", name);
        if let Some(properties_obj) = properties.as_object() {
            println!("Found {} properties", properties_obj.len());
            for (prop_name, prop_schema) in properties_obj {
                println!("Processing property: {}", prop_name);
                if let Some(prop_type) = self.property_to_typescript_inline(prop_schema) {
                    println!("Property {} has type: {}", prop_name, prop_type);
                    // 检查是否是 required 字段
                    let required = prop_schema.get("required").and_then(|r| r.as_bool()).unwrap_or(false);
                    
                    props.push(TypeProperty {
                        name: prop_name.clone(),
                        type_: prop_type,
                        required,
                        description: prop_schema.get("description").and_then(|d| d.as_str()).map(|s| s.to_string()),
                    });
                } else {
                    println!("Failed to get type for property: {}", prop_name);
                }
            }
        } else {
            println!("Properties is not an object");
        }

        println!("Generated {} properties for type: {}", props.len(), name);
        // 只有当有属性时才创建接口
        if !props.is_empty() {
            Some(TypeDefinition {
                name: name.to_string(),
                is_enum: false,
                is_interface: true,
                properties: props,
                enum_values: vec![],
                type_: "".to_string(),
            })
        } else {
            None
        }
    }

    fn property_to_typescript_inline(&self, prop: &Value) -> Option<String> {
        // 处理引用
        if let Some(ref_path) = prop.get("$ref").and_then(|r| r.as_str()) {
            if let Some(type_name) = ref_path.split('/').last() {
                return Some(type_name.to_string());
            }
        }

        // 处理枚举
        if let Some(enum_values) = prop.get("enum") {
            let mut enum_str = String::new();
            for (i, value) in enum_values.as_array()?.iter().enumerate() {
                if i > 0 {
                    enum_str.push_str(" | ");
                }
                enum_str.push_str(&format!("\"{}\"", value.as_str()?));
            }
            return Some(enum_str);
        }

        // 处理数组
        if let Some(items) = prop.get("items") {
            let item_type = self.property_to_typescript_inline(items)?;
            return Some(format!("{}[]", item_type));
        }

        // 处理基本类型
        if let Some(type_str) = prop.get("type").and_then(|t| t.as_str()) {
            match type_str {
                "string" => {
                    if prop.get("nullable").and_then(|n| n.as_bool()).unwrap_or(false) {
                        return Some("string | null".to_string());
                    }
                    return Some("string".to_string());
                }
                "number" | "integer" => {
                    if prop.get("nullable").and_then(|n| n.as_bool()).unwrap_or(false) {
                        return Some("number | null".to_string());
                    }
                    return Some("number".to_string());
                }
                "boolean" => {
                    if prop.get("nullable").and_then(|n| n.as_bool()).unwrap_or(false) {
                        return Some("boolean | null".to_string());
                    }
                    return Some("boolean".to_string());
                }
                "array" => return Some("any[]".to_string()),
                "object" => {
                    // 对于内联对象，生成一个内联接口
                    if let Some(properties) = prop.get("properties") {
                        if let Some(properties_obj) = properties.as_object() {
                            if !properties_obj.is_empty() {
                                let mut interface_str = String::new();
                                interface_str.push_str("{\n");
                                
                                for (prop_name, prop_schema) in properties_obj {
                                    if let Some(prop_type) = self.property_to_typescript_inline(prop_schema) {
                                        let required = prop_schema.get("required").and_then(|r| r.as_bool()).unwrap_or(false);
                                        let optional = if required { "" } else { "?" };
                                        interface_str.push_str(&format!("  {}{}: {};\n", prop_name, optional, prop_type));
                                    }
                                }
                                
                                interface_str.push_str("}");
                                return Some(interface_str);
                            }
                        }
                    }
                    return Some("Record<string, any>".to_string());
                },
                "null" => return Some("null".to_string()),
                _ => return Some("any".to_string()),
            }
        }

        Some("any".to_string())
    }

    fn schema_to_type_definition(&self, name: &str, schema: &Value) -> Option<TypeDefinition> {
        // 处理枚举类型
        if let Some(enum_values) = schema.get("enum") {
            let mut enum_vals = Vec::new();
            if let Some(descriptions) = schema.get("x-apifox").and_then(|x| x.get("enumDescriptions")) {
                for value in enum_values.as_array()? {
                    let key = value.as_str()?.to_uppercase().replace("-", "_");
                    let val = value.as_str()?.to_string();
                    let desc = descriptions.get(value.as_str()?).and_then(|d| d.as_str()).map(|s| s.to_string());
                    
                    enum_vals.push(EnumValue { key, value: val, description: desc });
                }
            } else {
                for value in enum_values.as_array()? {
                    let key = value.as_str()?.to_uppercase().replace("-", "_");
                    let val = value.as_str()?.to_string();
                    enum_vals.push(EnumValue { key, value: val, description: None });
                }
            }

            return Some(TypeDefinition {
                name: name.to_string(),
                is_enum: true,
                is_interface: false,
                properties: vec![],
                enum_values: enum_vals,
                type_: "".to_string(),
            });
        }

        // 处理对象类型
        if let Some(properties) = schema.get("properties") {
            let mut props = Vec::new();
            let required_fields: Vec<String> = schema.get("required")
                .and_then(|r| r.as_array())
                .map(|arr| arr.iter().filter_map(|v| v.as_str()).map(|s| s.to_string()).collect())
                .unwrap_or_default();

            for (prop_name, prop_schema) in properties.as_object()? {
                let prop_type = self.property_to_typescript(prop_schema)?;
                let required = required_fields.contains(prop_name);
                
                props.push(TypeProperty {
                    name: prop_name.clone(),
                    type_: prop_type,
                    required,
                    description: None,
                });
            }

            return Some(TypeDefinition {
                name: name.to_string(),
                is_enum: false,
                is_interface: true,
                properties: props,
                enum_values: vec![],
                type_: "".to_string(),
            });
        }

        // 处理基本类型
        if let Some(type_str) = schema.get("type").and_then(|t| t.as_str()) {
            let ts_type = match type_str {
                "string" => "string",
                "number" | "integer" => "number",
                "boolean" => "boolean",
                "array" => "any[]",
                _ => "any",
            };

            return Some(TypeDefinition {
                name: name.to_string(),
                is_enum: false,
                is_interface: false,
                properties: vec![],
                enum_values: vec![],
                type_: ts_type.to_string(),
            });
        }

        None
    }

    fn build_main_index_context(&self) -> MainIndexContext {
        let folders: Vec<FolderInfo> = self.folder_structure.keys()
            .map(|name| FolderInfo {
                name: name.clone(),
                safe_name: self.sanitize_folder_name(name),
            })
            .collect();

        MainIndexContext { folders }
    }
}
