#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
智能 SDK 添加器
结合文本处理的可靠性和智能文件类型处理
framework 作为整体添加，不单独处理内部文件
"""

import sys
import os
import shutil
import uuid
import re

class SmartSDKAdder:
    """智能 SDK 添加器类"""
    
    def __init__(self, pbxproj_path):
        """
        初始化 SDK 添加器
        
        参数:
            pbxproj_path (str): project.pbxproj 文件路径
        """
        self.pbxproj_path = pbxproj_path
        
        if not os.path.exists(pbxproj_path):
            raise FileNotFoundError(f"项目文件不存在: {pbxproj_path}")
    
    def add_sdk_folder(self, sdk_folder_path, group_name="SDK"):
        """
        添加 SDK 文件夹到项目中
        
        参数:
            sdk_folder_path (str): SDK 文件夹路径
            group_name (str): 在项目中创建的组名，默认为 "SDK"
            
        返回:
            bool: 操作是否成功
        """
        print(f"📁 开始添加 SDK 文件夹: {sdk_folder_path}")
        print(f"📂 目标组名: {group_name}")
        
        if not os.path.exists(sdk_folder_path):
            print(f"❌ SDK 文件夹不存在: {sdk_folder_path}")
            return False
        
        try:
            # 创建备份
            backup_path = f"{self.pbxproj_path}.backup_smart"
            shutil.copy2(self.pbxproj_path, backup_path)
            print(f"✅ 已创建备份: {backup_path}")
            
            # 读取项目文件内容
            with open(self.pbxproj_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            # 智能扫描 SDK 文件夹
            sdk_items = self._smart_scan_sdk_folder(sdk_folder_path)
            print(f"📊 扫描到 {len(sdk_items)} 个项目")
            
            # 添加文件到项目
            modified_content = self._add_items_to_project(content, sdk_items, sdk_folder_path, group_name)
            
            # 验证修改后的内容
            if self._validate_project_structure(modified_content):
                # 保存修改后的文件
                with open(self.pbxproj_path, 'w', encoding='utf-8') as f:
                    f.write(modified_content)
                
                print("✅ SDK 文件夹添加完成")
                return True
            else:
                print("❌ 项目结构验证失败，恢复备份")
                shutil.copy2(backup_path, self.pbxproj_path)
                return False
                
        except Exception as e:
            print(f"❌ 添加 SDK 文件夹失败: {e}")
            import traceback
            traceback.print_exc()
            
            # 恢复备份
            if os.path.exists(backup_path):
                shutil.copy2(backup_path, self.pbxproj_path)
                print("✅ 已恢复备份文件")
            
            return False
    
    def _smart_scan_sdk_folder(self, sdk_folder_path):
        """
        智能扫描 SDK 文件夹，优先处理 framework 和 bundle 作为整体
        
        参数:
            sdk_folder_path (str): SDK 文件夹路径
            
        返回:
            list: 项目信息列表
        """
        print("🔍 智能扫描 SDK 文件夹...")
        
        sdk_items = []
        processed_paths = set()  # 避免重复处理
        
        for root, dirs, files in os.walk(sdk_folder_path):
            # 计算相对路径
            relative_root = os.path.relpath(root, sdk_folder_path)
            if relative_root == '.':
                relative_root = ''
            
            # 检查当前目录是否是 framework
            if root.endswith('.framework'):
                if root not in processed_paths:
                    framework_info = {
                        'type': 'framework',
                        'name': os.path.basename(root),
                        'path': root,
                        'relative_path': os.path.relpath(root, sdk_folder_path),
                        'parent_dir': os.path.dirname(relative_root) if relative_root else ''
                    }
                    sdk_items.append(framework_info)
                    processed_paths.add(root)
                    print(f"  📦 {framework_info['relative_path']} (framework)")
                
                # 标记 framework 内部所有路径为已处理
                for sub_root, sub_dirs, sub_files in os.walk(root):
                    processed_paths.add(sub_root)
                continue
            
            # 检查当前目录是否是 bundle
            if root.endswith('.bundle'):
                if root not in processed_paths:
                    bundle_info = {
                        'type': 'bundle',
                        'name': os.path.basename(root),
                        'path': root,
                        'relative_path': os.path.relpath(root, sdk_folder_path),
                        'parent_dir': os.path.dirname(relative_root) if relative_root else ''
                    }
                    sdk_items.append(bundle_info)
                    processed_paths.add(root)
                    print(f"  📦 {bundle_info['relative_path']} (bundle)")
                
                # 标记 bundle 内部所有路径为已处理
                for sub_root, sub_dirs, sub_files in os.walk(root):
                    processed_paths.add(sub_root)
                continue
            
            # 跳过已经作为 framework/bundle 处理的路径
            if root in processed_paths:
                continue
            
            # 处理普通文件
            for file_name in files:
                file_path = os.path.join(root, file_name)
                
                # 跳过已经作为 framework/bundle 处理的文件
                if any(file_path.startswith(processed_path) for processed_path in processed_paths):
                    continue
                
                # 跳过系统文件和不需要的文件
                if self._should_skip_file(file_name):
                    continue
                
                file_type = self._get_file_type(file_name)
                
                if file_type:  # 只处理支持的文件类型
                    relative_path = os.path.join(relative_root, file_name) if relative_root else file_name
                    
                    file_info = {
                        'type': file_type,
                        'name': file_name,
                        'path': file_path,
                        'relative_path': relative_path,
                        'parent_dir': relative_root,
                        'extension': os.path.splitext(file_name)[1].lower()
                    }
                    sdk_items.append(file_info)
                    print(f"  📄 {relative_path} ({file_type})")
        
        return sdk_items
    
    def _should_skip_file(self, file_name):
        """判断是否应该跳过文件"""
        # 跳过系统文件
        if file_name.startswith('.') and file_name != '.DS_Store':
            return True
        
        # 跳过 .DS_Store 文件
        if file_name == '.DS_Store':
            return True
        
        # 跳过代码签名文件
        if file_name in ['CodeResources', 'CodeDirectory', 'CodeRequirements', 'CodeRequirements-1', 'CodeSignature']:
            return True
        
        return False
    
    def _get_file_type(self, file_name):
        """
        根据文件名确定文件类型
        
        参数:
            file_name (str): 文件名
            
        返回:
            str: 文件类型
        """
        ext = os.path.splitext(file_name)[1].lower()
        
        if ext == '.a':
            return 'library'
        elif ext == '.framework':
            return 'framework'  # 这种情况应该在上层处理
        elif ext == '.bundle':
            return 'bundle'     # 这种情况应该在上层处理
        elif ext == '.plist':
            return 'resource'
        elif ext == '.h':
            return 'header'
        elif ext in ['.m', '.mm', '.c', '.cpp', '.swift']:
            return 'source'
        elif ext in ['.png', '.jpg', '.jpeg', '.gif', '.json', '.txt', '.xml', '.xcprivacy']:
            return 'resource'
        elif ext in ['.swiftinterface', '.swiftdoc', '.swiftsourceinfo', '.modulemap']:
            return 'resource'
        else:
            # 对于其他文件类型，也作为资源处理
            return 'resource'
    
    def _add_items_to_project(self, content, sdk_items, sdk_folder_path, group_name):
        """
        添加项目到 Xcode 项目中
        
        参数:
            content (str): 项目文件内容
            sdk_items (list): 项目信息列表
            sdk_folder_path (str): SDK 文件夹路径
            group_name (str): 组名
            
        返回:
            str: 修改后的项目文件内容
        """
        print("📝 添加项目到 Xcode...")
        
        # 1. 添加文件引用
        content = self._add_file_references(content, sdk_items, sdk_folder_path)
        
        # 2. 创建组结构
        content = self._create_group_structure(content, sdk_items, group_name)
        
        # 3. 添加构建文件
        content = self._add_build_files(content, sdk_items)
        
        # 4. 添加到构建阶段
        content = self._add_to_build_phases(content, sdk_items)

        # 5. 添加搜索路径
        content = self._add_search_paths(content, sdk_items, sdk_folder_path)

        return content
    
    def _generate_uuid(self):
        """生成 24 位的唯一 ID"""
        return str(uuid.uuid4()).replace('-', '').upper()[:24]
    
    def _validate_project_structure(self, content):
        """验证项目结构完整性"""
        print("🔍 验证项目结构...")
        
        # 检查基本结构
        required_sections = [
            '/* Begin PBXFileReference section */',
            '/* End PBXFileReference section */',
            '/* Begin PBXGroup section */',
            '/* End PBXGroup section */',
            '/* Begin PBXNativeTarget section */',
            '/* End PBXNativeTarget section */',
            '/* Begin PBXProject section */',
            '/* End PBXProject section */'
        ]
        
        for section in required_sections:
            if section not in content:
                print(f"❌ 缺少必要的节: {section}")
                return False
        
        # 检查括号匹配
        open_braces = content.count('{')
        close_braces = content.count('}')
        if open_braces != close_braces:
            print(f"❌ 括号不匹配: {{ {open_braces} vs }} {close_braces}")
            return False
        
        # 检查根对象（动态检测）
        root_object_pattern = r'rootObject = [A-F0-9]{24}'
        if not re.search(root_object_pattern, content):
            print("❌ 缺少根对象引用")
            return False
        
        print("✅ 项目结构验证通过")
        return True

    def _add_file_references(self, content, sdk_items, sdk_folder_path):
        """添加文件引用到 PBXFileReference 节"""
        print("📄 添加文件引用...")

        # 找到 PBXFileReference 节的结束位置
        file_ref_end = content.find('/* End PBXFileReference section */')
        if file_ref_end == -1:
            print("❌ 找不到 PBXFileReference 节")
            return content

        new_file_refs = []

        for item in sdk_items:
            file_id = self._generate_uuid()
            file_name = item['name']
            item_type = item['type']

            # 根据文件类型生成不同的文件引用
            if item_type == 'framework':
                file_ref = f'\t\t{file_id} /* {file_name} */ = {{isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = {file_name}; sourceTree = "<group>"; }};'
            elif item_type == 'bundle':
                file_ref = f'\t\t{file_id} /* {file_name} */ = {{isa = PBXFileReference; lastKnownFileType = "wrapper.plug-in"; path = {file_name}; sourceTree = "<group>"; }};'
            elif item_type == 'library':
                file_ref = f'\t\t{file_id} /* {file_name} */ = {{isa = PBXFileReference; lastKnownFileType = archive.ar; path = {file_name}; sourceTree = "<group>"; }};'
            elif item_type == 'header':
                file_ref = f'\t\t{file_id} /* {file_name} */ = {{isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = {file_name}; sourceTree = "<group>"; }};'
            elif item_type == 'source':
                if file_name.endswith('.m'):
                    file_ref = f'\t\t{file_id} /* {file_name} */ = {{isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = {file_name}; sourceTree = "<group>"; }};'
                elif file_name.endswith('.mm'):
                    file_ref = f'\t\t{file_id} /* {file_name} */ = {{isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = {file_name}; sourceTree = "<group>"; }};'
                elif file_name.endswith('.swift'):
                    file_ref = f'\t\t{file_id} /* {file_name} */ = {{isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = {file_name}; sourceTree = "<group>"; }};'
                else:
                    file_ref = f'\t\t{file_id} /* {file_name} */ = {{isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = {file_name}; sourceTree = "<group>"; }};'
            else:  # resource
                if file_name.endswith('.plist'):
                    file_ref = f'\t\t{file_id} /* {file_name} */ = {{isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = {file_name}; sourceTree = "<group>"; }};'
                else:
                    file_ref = f'\t\t{file_id} /* {file_name} */ = {{isa = PBXFileReference; lastKnownFileType = file; path = {file_name}; sourceTree = "<group>"; }};'

            new_file_refs.append(file_ref)

            # 保存文件ID以供后续使用
            item['file_id'] = file_id

            print(f"  📄 添加文件引用: {file_name}")

        # 插入新的文件引用
        if new_file_refs:
            insert_content = '\n' + '\n'.join(new_file_refs) + '\n'
            content = content[:file_ref_end] + insert_content + content[file_ref_end:]

        return content

    def _create_group_structure(self, content, sdk_items, group_name):
        """创建组结构"""
        print("📂 创建组结构...")

        # 找到 PBXGroup 节的结束位置
        group_end = content.find('/* End PBXGroup section */')
        if group_end == -1:
            print("❌ 找不到 PBXGroup 节")
            return content

        # 创建组层次结构
        groups_to_create = {}

        # 收集所有需要创建的组
        for item in sdk_items:
            parent_dir = item['parent_dir']
            if parent_dir:
                # 分解路径，创建层次结构
                path_parts = parent_dir.split(os.sep)
                current_path = ''
                for part in path_parts:
                    if current_path:
                        current_path = os.path.join(current_path, part)
                    else:
                        current_path = part

                    if current_path not in groups_to_create:
                        groups_to_create[current_path] = {
                            'id': self._generate_uuid(),
                            'name': part,
                            'path': current_path,
                            'children': [],
                            'files': []
                        }

        # 添加文件到对应的组
        for item in sdk_items:
            parent_dir = item['parent_dir']
            if parent_dir and parent_dir in groups_to_create:
                groups_to_create[parent_dir]['files'].append(item)
            elif not parent_dir:
                # 根级别文件，添加到主 SDK 组
                if 'root' not in groups_to_create:
                    groups_to_create['root'] = {
                        'id': self._generate_uuid(),
                        'name': group_name,
                        'path': '',
                        'children': [],
                        'files': []
                    }
                groups_to_create['root']['files'].append(item)

        # 建立父子关系
        for path, group_info in groups_to_create.items():
            if path != 'root':
                parent_path = os.path.dirname(path)
                if parent_path and parent_path in groups_to_create:
                    groups_to_create[parent_path]['children'].append(group_info['id'])
                elif not parent_path:
                    # 顶级组，添加到根组
                    if 'root' not in groups_to_create:
                        groups_to_create['root'] = {
                            'id': self._generate_uuid(),
                            'name': group_name,
                            'path': '',
                            'children': [],
                            'files': []
                        }
                    groups_to_create['root']['children'].append(group_info['id'])

        # 生成组定义
        new_groups = []
        for path, group_info in groups_to_create.items():
            group_id = group_info['id']
            group_name_attr = group_info['name']

            children_list = []
            # 添加子组
            for child_id in group_info['children']:
                child_name = self._get_group_name_by_id(child_id, groups_to_create)
                children_list.append(f'\t\t\t\t{child_id} /* {child_name} */,')

            # 添加文件
            for item in group_info['files']:
                children_list.append(f'\t\t\t\t{item["file_id"]} /* {item["name"]} */,')

            children_content = '\n'.join(children_list) if children_list else ''

            if group_info['path']:
                group_def = f'''\t\t{group_id} /* {group_name_attr} */ = {{
\t\t\tisa = PBXGroup;
\t\t\tchildren = (
{children_content}
\t\t\t);
\t\t\tpath = {group_name_attr};
\t\t\tsourceTree = "<group>";
\t\t}};'''
            else:
                # 根组需要设置 path 指向 SDK 文件夹
                group_def = f'''\t\t{group_id} /* {group_name_attr} */ = {{
\t\t\tisa = PBXGroup;
\t\t\tchildren = (
{children_content}
\t\t\t);
\t\t\tpath = {group_name_attr};
\t\t\tsourceTree = "<group>";
\t\t}};'''

            new_groups.append(group_def)
            print(f"  📂 创建组: {group_name_attr}")

        # 插入新的组定义
        if new_groups:
            insert_content = '\n' + '\n'.join(new_groups) + '\n'
            content = content[:group_end] + insert_content + content[group_end:]

        # 将主 SDK 组添加到项目的主组中
        if 'root' in groups_to_create:
            content = self._add_to_main_group(content, groups_to_create['root']['id'], group_name)

        return content

    def _get_group_name_by_id(self, group_id, groups_dict):
        """根据组ID获取组名"""
        for path, group_info in groups_dict.items():
            if group_info['id'] == group_id:
                return group_info['name']
        return 'Unknown'

    def _add_to_main_group(self, content, sdk_group_id, group_name):
        """将 SDK 组添加到项目的主组中"""
        print(f"📂 将 {group_name} 组添加到主组...")

        # 查找主组（通常是第一个没有 name 属性的组）
        main_group_pattern = r'([A-F0-9]{24}) = \{\s*isa = PBXGroup;\s*children = \(\s*([^}]*?)\s*\);\s*sourceTree = "<group>";\s*\};'

        match = re.search(main_group_pattern, content, re.DOTALL)
        if match:
            main_group_id = match.group(1)
            children_content = match.group(2)

            # 添加 SDK 组到主组的子项中
            new_child = f'\t\t\t\t{sdk_group_id} /* {group_name} */,'

            if children_content.strip():
                new_children = children_content.rstrip() + '\n' + new_child
            else:
                new_children = new_child

            # 替换主组定义
            old_group_def = match.group(0)
            new_group_def = f'''{main_group_id} = {{
\t\t\tisa = PBXGroup;
\t\t\tchildren = (
{new_children}
\t\t\t);
\t\t\tsourceTree = "<group>";
\t\t}};'''

            content = content.replace(old_group_def, new_group_def)
            print(f"  ✅ 已将 {group_name} 添加到主组")

        return content

    def _add_build_files(self, content, sdk_items):
        """添加构建文件到 PBXBuildFile 节"""
        print("🔧 添加构建文件...")

        # 找到 PBXBuildFile 节的结束位置
        build_file_end = content.find('/* End PBXBuildFile section */')
        if build_file_end == -1:
            print("❌ 找不到 PBXBuildFile 节")
            return content

        new_build_files = []

        for item in sdk_items:
            item_type = item['type']
            file_name = item['name']
            file_id = item['file_id']

            # 只为需要构建的文件类型创建构建文件
            if item_type in ['library', 'framework']:
                build_file_id = self._generate_uuid()
                build_file = f'\t\t{build_file_id} /* {file_name} in Frameworks */ = {{isa = PBXBuildFile; fileRef = {file_id} /* {file_name} */; }};'
                new_build_files.append(build_file)
                item['build_file_id'] = build_file_id
                print(f"  🔧 添加构建文件: {file_name}")
            elif item_type in ['bundle', 'resource']:
                build_file_id = self._generate_uuid()
                build_file = f'\t\t{build_file_id} /* {file_name} in Resources */ = {{isa = PBXBuildFile; fileRef = {file_id} /* {file_name} */; }};'
                new_build_files.append(build_file)
                item['build_file_id'] = build_file_id
                print(f"  🔧 添加资源构建文件: {file_name}")
            elif item_type == 'source':
                build_file_id = self._generate_uuid()
                build_file = f'\t\t{build_file_id} /* {file_name} in Sources */ = {{isa = PBXBuildFile; fileRef = {file_id} /* {file_name} */; }};'
                new_build_files.append(build_file)
                item['build_file_id'] = build_file_id
                print(f"  🔧 添加源码构建文件: {file_name}")

        # 插入新的构建文件
        if new_build_files:
            insert_content = '\n' + '\n'.join(new_build_files) + '\n'
            content = content[:build_file_end] + insert_content + content[build_file_end:]

        return content

    def _add_to_build_phases(self, content, sdk_items):
        """添加文件到构建阶段"""
        print("⚙️ 添加文件到构建阶段...")

        # 添加到 Frameworks 构建阶段
        content = self._add_to_frameworks_build_phase(content, sdk_items)

        # 添加到 Resources 构建阶段
        content = self._add_to_resources_build_phase(content, sdk_items)

        # 添加到 Sources 构建阶段
        content = self._add_to_sources_build_phase(content, sdk_items)

        return content

    def _add_to_frameworks_build_phase(self, content, sdk_items):
        """添加到 Frameworks 构建阶段"""
        framework_files = [f for f in sdk_items if f['type'] in ['library', 'framework'] and 'build_file_id' in f]

        if not framework_files:
            return content

        # 查找 Frameworks 构建阶段
        frameworks_pattern = r'([A-F0-9]{24} /\* Frameworks \*/ = \{\s*isa = PBXFrameworksBuildPhase;\s*buildActionMask = [^;]+;\s*files = \(\s*)(.*?)(\s*\);\s*runOnlyForDeploymentPostprocessing = 0;\s*\};)'

        match = re.search(frameworks_pattern, content, re.DOTALL)
        if match:
            prefix = match.group(1)
            existing_files = match.group(2)
            suffix = match.group(3)

            new_files = []
            for item in framework_files:
                build_file_id = item['build_file_id']
                file_name = item['name']
                new_files.append(f'\t\t\t\t{build_file_id} /* {file_name} in Frameworks */,')
                print(f"  ⚙️ 添加到 Frameworks 构建阶段: {file_name}")

            if existing_files.strip():
                new_files_content = existing_files.rstrip() + '\n' + '\n'.join(new_files)
            else:
                new_files_content = '\n'.join(new_files)

            new_phase_def = prefix + new_files_content + suffix
            content = content.replace(match.group(0), new_phase_def)

        return content

    def _add_to_resources_build_phase(self, content, sdk_items):
        """添加到 Resources 构建阶段"""
        resource_files = [f for f in sdk_items if f['type'] in ['bundle', 'resource'] and 'build_file_id' in f]

        if not resource_files:
            return content

        # 查找 Resources 构建阶段
        resources_pattern = r'([A-F0-9]{24} /\* Resources \*/ = \{\s*isa = PBXResourcesBuildPhase;\s*buildActionMask = [^;]+;\s*files = \(\s*)(.*?)(\s*\);\s*runOnlyForDeploymentPostprocessing = 0;\s*\};)'

        match = re.search(resources_pattern, content, re.DOTALL)
        if match:
            prefix = match.group(1)
            existing_files = match.group(2)
            suffix = match.group(3)

            new_files = []
            for item in resource_files:
                build_file_id = item['build_file_id']
                file_name = item['name']
                new_files.append(f'\t\t\t\t{build_file_id} /* {file_name} in Resources */,')
                print(f"  ⚙️ 添加到 Resources 构建阶段: {file_name}")

            if existing_files.strip():
                new_files_content = existing_files.rstrip() + '\n' + '\n'.join(new_files)
            else:
                new_files_content = '\n'.join(new_files)

            new_phase_def = prefix + new_files_content + suffix
            content = content.replace(match.group(0), new_phase_def)

        return content

    def _add_to_sources_build_phase(self, content, sdk_items):
        """添加到 Sources 构建阶段"""
        source_files = [f for f in sdk_items if f['type'] == 'source' and 'build_file_id' in f]

        if not source_files:
            return content

        # 查找 Sources 构建阶段
        sources_pattern = r'([A-F0-9]{24} /\* Sources \*/ = \{\s*isa = PBXSourcesBuildPhase;\s*buildActionMask = [^;]+;\s*files = \(\s*)(.*?)(\s*\);\s*runOnlyForDeploymentPostprocessing = 0;\s*\};)'

        match = re.search(sources_pattern, content, re.DOTALL)
        if match:
            prefix = match.group(1)
            existing_files = match.group(2)
            suffix = match.group(3)

            new_files = []
            for item in source_files:
                build_file_id = item['build_file_id']
                file_name = item['name']
                new_files.append(f'\t\t\t\t{build_file_id} /* {file_name} in Sources */,')
                print(f"  ⚙️ 添加到 Sources 构建阶段: {file_name}")

            if existing_files.strip():
                new_files_content = existing_files.rstrip() + '\n' + '\n'.join(new_files)
            else:
                new_files_content = '\n'.join(new_files)

            new_phase_def = prefix + new_files_content + suffix
            content = content.replace(match.group(0), new_phase_def)

        return content

    def _add_search_paths(self, content, sdk_items, sdk_folder_path):
        """添加搜索路径配置"""
        print("🔍 添加搜索路径配置...")

        # 使用 PROJECT_DIR 而不是 SRCROOT，这样更符合 Xcode 的标准做法
        sdk_folder_name = os.path.basename(sdk_folder_path)

        # 收集需要添加的搜索路径
        framework_paths = set()
        library_paths = set()
        header_paths = set()

        # 添加主 SDK 路径
        framework_paths.add(f'"$(PROJECT_DIR)/{sdk_folder_name}"')
        library_paths.add(f'"$(PROJECT_DIR)/{sdk_folder_name}"')
        header_paths.add(f'"$(PROJECT_DIR)/{sdk_folder_name}"')

        # 为子文件夹添加具体路径
        for item in sdk_items:
            if item['parent_dir']:
                sub_path = f'"$(PROJECT_DIR)/{sdk_folder_name}/{item["parent_dir"]}"'

                if item['type'] == 'framework':
                    framework_paths.add(sub_path)
                elif item['type'] == 'library':
                    library_paths.add(sub_path)
                elif item['type'] == 'header':
                    header_paths.add(sub_path)

        # 添加到构建配置
        content = self._add_framework_search_paths(content, framework_paths)
        content = self._add_library_search_paths(content, library_paths)
        content = self._add_header_search_paths(content, header_paths)

        return content

    def _add_framework_search_paths(self, content, framework_paths):
        """添加 FRAMEWORK_SEARCH_PATHS"""
        if not framework_paths:
            return content

        print("  🔍 添加 FRAMEWORK_SEARCH_PATHS...")

        # 查找构建配置节
        build_config_pattern = r'([A-F0-9]{24} /\* (Debug|Release) \*/ = \{\s*isa = XCBuildConfiguration;\s*buildSettings = \{)(.*?)(\s*\};\s*name = (Debug|Release);\s*\};)'

        matches = list(re.finditer(build_config_pattern, content, re.DOTALL))

        for match in matches:
            prefix = match.group(1)
            build_settings = match.group(3)
            suffix = match.group(4)
            config_name = match.group(2)

            # 检查是否已经有 FRAMEWORK_SEARCH_PATHS
            if 'FRAMEWORK_SEARCH_PATHS' in build_settings:
                # 已存在，需要添加到现有配置中
                framework_pattern = r'(FRAMEWORK_SEARCH_PATHS = \()(.*?)(\);)'
                framework_match = re.search(framework_pattern, build_settings, re.DOTALL)

                if framework_match:
                    existing_paths = framework_match.group(2)
                    new_paths = []
                    for path in framework_paths:
                        new_paths.append(f'\t\t\t\t{path},')

                    new_framework_config = framework_match.group(1) + existing_paths.rstrip() + '\n' + '\n'.join(new_paths) + '\n\t\t\t' + framework_match.group(3)
                    build_settings = build_settings.replace(framework_match.group(0), new_framework_config)
            else:
                # 不存在，创建新的配置，包含 $(inherited)
                new_paths = ['\t\t\t\t"$(inherited)",']
                for path in framework_paths:
                    new_paths.append(f'\t\t\t\t{path},')

                framework_config = f'''FRAMEWORK_SEARCH_PATHS = (
{chr(10).join(new_paths)}
\t\t\t);'''

                # 在 buildSettings 末尾添加
                build_settings = build_settings.rstrip() + '\n\t\t\t' + framework_config + '\n'

            # 替换整个构建配置
            new_config = prefix + build_settings + suffix
            content = content.replace(match.group(0), new_config)

            print(f"    ✅ 已添加到 {config_name} 配置")

        return content

    def _add_library_search_paths(self, content, library_paths):
        """添加 LIBRARY_SEARCH_PATHS"""
        if not library_paths:
            return content

        print("  🔍 添加 LIBRARY_SEARCH_PATHS...")

        # 查找构建配置节
        build_config_pattern = r'([A-F0-9]{24} /\* (Debug|Release) \*/ = \{\s*isa = XCBuildConfiguration;\s*buildSettings = \{)(.*?)(\s*\};\s*name = (Debug|Release);\s*\};)'

        matches = list(re.finditer(build_config_pattern, content, re.DOTALL))

        for match in matches:
            prefix = match.group(1)
            build_settings = match.group(3)
            suffix = match.group(4)
            config_name = match.group(2)

            # 检查是否已经有 LIBRARY_SEARCH_PATHS
            if 'LIBRARY_SEARCH_PATHS' in build_settings:
                # 已存在，需要添加到现有配置中
                library_pattern = r'(LIBRARY_SEARCH_PATHS = \()(.*?)(\);)'
                library_match = re.search(library_pattern, build_settings, re.DOTALL)

                if library_match:
                    existing_paths = library_match.group(2)
                    new_paths = []
                    for path in library_paths:
                        new_paths.append(f'\t\t\t\t{path},')

                    new_library_config = library_match.group(1) + existing_paths.rstrip() + '\n' + '\n'.join(new_paths) + '\n\t\t\t' + library_match.group(3)
                    build_settings = build_settings.replace(library_match.group(0), new_library_config)
            else:
                # 不存在，创建新的配置，包含 $(inherited)
                new_paths = ['\t\t\t\t"$(inherited)",']
                for path in library_paths:
                    new_paths.append(f'\t\t\t\t{path},')

                library_config = f'''LIBRARY_SEARCH_PATHS = (
{chr(10).join(new_paths)}
\t\t\t);'''

                # 在 buildSettings 末尾添加
                build_settings = build_settings.rstrip() + '\n\t\t\t' + library_config + '\n'

            # 替换整个构建配置
            new_config = prefix + build_settings + suffix
            content = content.replace(match.group(0), new_config)

            print(f"    ✅ 已添加到 {config_name} 配置")

        return content

    def _add_header_search_paths(self, content, header_paths):
        """添加 HEADER_SEARCH_PATHS"""
        if not header_paths:
            return content

        print("  🔍 添加 HEADER_SEARCH_PATHS...")

        # 查找构建配置节
        build_config_pattern = r'([A-F0-9]{24} /\* (Debug|Release) \*/ = \{\s*isa = XCBuildConfiguration;\s*buildSettings = \{)(.*?)(\s*\};\s*name = (Debug|Release);\s*\};)'

        matches = list(re.finditer(build_config_pattern, content, re.DOTALL))

        for match in matches:
            prefix = match.group(1)
            build_settings = match.group(3)
            suffix = match.group(4)
            config_name = match.group(2)

            # 检查是否已经有 HEADER_SEARCH_PATHS
            if 'HEADER_SEARCH_PATHS' in build_settings:
                # 已存在，需要添加到现有配置中
                header_pattern = r'(HEADER_SEARCH_PATHS = \()(.*?)(\);)'
                header_match = re.search(header_pattern, build_settings, re.DOTALL)

                if header_match:
                    existing_paths = header_match.group(2)
                    new_paths = []
                    for path in header_paths:
                        new_paths.append(f'\t\t\t\t{path},')

                    new_header_config = header_match.group(1) + existing_paths.rstrip() + '\n' + '\n'.join(new_paths) + '\n\t\t\t' + header_match.group(3)
                    build_settings = build_settings.replace(header_match.group(0), new_header_config)
            else:
                # 不存在，创建新的配置，包含 $(inherited)
                new_paths = ['\t\t\t\t"$(inherited)",']
                for path in header_paths:
                    new_paths.append(f'\t\t\t\t{path},')

                header_config = f'''HEADER_SEARCH_PATHS = (
{chr(10).join(new_paths)}
\t\t\t);'''

                # 在 buildSettings 末尾添加
                build_settings = build_settings.rstrip() + '\n\t\t\t' + header_config + '\n'

            # 替换整个构建配置
            new_config = prefix + build_settings + suffix
            content = content.replace(match.group(0), new_config)

            print(f"    ✅ 已添加到 {config_name} 配置")

        return content


def main():
    """主函数 - 命令行接口"""
    if len(sys.argv) < 3:
        print("用法: python sdk_adder_smart.py <project.pbxproj路径> <SDK文件夹路径> [组名]")
        print("示例: python sdk_adder_smart.py project.pbxproj SDK MySDK")
        print("      python sdk_adder_smart.py project.pbxproj SDK  # 默认组名为 'SDK'")
        sys.exit(1)

    pbxproj_path = sys.argv[1]
    sdk_folder_path = sys.argv[2]
    group_name = sys.argv[3] if len(sys.argv) > 3 else "SDK"

    # 创建 SDK 添加器并处理
    try:
        adder = SmartSDKAdder(pbxproj_path)
        success = adder.add_sdk_folder(sdk_folder_path, group_name)

        if success:
            print("✅ SDK 文件夹添加成功！")
            print("🎉 现在可以在 Xcode 中看到添加的 SDK 文件了！")
            print("📝 Framework 作为整体添加，不会单独处理内部文件")
            sys.exit(0)
        else:
            print("❌ SDK 文件夹添加失败！")
            sys.exit(1)

    except Exception as e:
        print(f"❌ 处理过程中出现错误: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)


if __name__ == "__main__":
    main()
