import re
import sys
import os

def remove_comments(file_path, output_path=None):
    """
    移除C/C++文件中的所有注释
    
    参数:
    file_path (str): 输入文件路径
    output_path (str, optional): 输出文件路径，如果不指定则覆盖原文件
    
    返回:
    bool: 操作是否成功
    """
    try:
        # 读取文件内容
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 保存原始文件长度用于报告
        original_length = len(content)
        
        # 移除多行注释 (/* ... */)
        content = re.sub(r'/\*[\s\S]*?\*/', '', content)
        
        # 移除单行注释 (// ...)
        content = re.sub(r'//.*?$', '', content, flags=re.MULTILINE)
        
        # 移除行尾的注释 (如 code; // comment)
        content = re.sub(r'(?<=;)\s*//.*?$', '', content, flags=re.MULTILINE)
        
        # 移除空行，但保留一个换行符
        content = re.sub(r'\n\s*\n', '\n', content)
        
        # 确定输出路径
        if output_path is None:
            output_path = file_path
        
        # 写入结果
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(content)
        
        # 计算移除的字节数
        removed_bytes = original_length - len(content)
        
        print(f"成功处理文件: {file_path}")
        print(f"移除注释: {removed_bytes} 字节")
        print(f"结果保存到: {output_path}")
        
        return True
    
    except Exception as e:
        print(f"处理文件时发生错误: {str(e)}")
        return False

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("用法: python remove_comments.py <输入文件> [输出文件]")
        print("如果不指定输出文件，将覆盖原文件")
    else:
        input_file = sys.argv[1]
        output_file = sys.argv[2] if len(sys.argv) > 2 else None
        
        if not os.path.exists(input_file):
            print(f"错误: 文件 '{input_file}' 不存在")
            sys.exit(1)
        
        success = remove_comments(input_file, output_file)
        sys.exit(0 if success else 1)