#!/usr/bin/env python3
"""
移除重复的状态变量声明
"""

import os
import re
from pathlib import Path

def remove_duplicate_declarations(file_path):
    """移除文件中的重复状态变量声明"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 分割成行以便处理
        lines = content.split('\n')
        new_lines = []
        seen_declarations = set()
        
        i = 0
        while i < len(lines):
            line = lines[i].strip()
            
            # 检查是否是状态变量声明
            if line.startswith('val stableData') and 'by remember' in line:
                if line in seen_declarations:
                    # 跳过重复声明
                    i += 1
                    continue
                else:
                    seen_declarations.add(line)
            
            new_lines.append(lines[i])
            i += 1
        
        # 重新组合内容
        content = '\n'.join(new_lines)
        
        # 写回文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
            
        return True
        
    except Exception as e:
        print(f"处理文件时出错 {file_path}: {e}")
        return False

def main():
    base_path = Path("/Users/dongsq/TestDemo/IR013/TestProject/MaxHap")
    nested_libs = ["nestedlib1", "nestedlib2", "nestedlib3", "nestedlib4", "nestedlib5"]
    
    total_files = 0
    fixed_files = 0
    
    for lib in nested_libs:
        lib_path = base_path / lib / "src/commonMain/kotlin/com/dong/maxhap" / lib
        if not lib_path.exists():
            continue
            
        # 处理该库中的所有NestedPage文件
        for file_path in lib_path.glob("NestedPage*.kt"):
            if file_path.is_file():
                total_files += 1
                if remove_duplicate_declarations(file_path):
                    fixed_files += 1
    
    print(f"\n重复声明清理完成!")
    print(f"总文件数: {total_files}")
    print(f"成功处理: {fixed_files}")

if __name__ == "__main__":
    main()