import os
import re
import shutil

# ===== 設定 =====
SOURCE_DIR = "."        # 你的 AS 專案資料夾
OUTPUT_DIR = "PL2303G_GPIOB_v1.0.0.5_clean"  # 輸出乾淨版 sample code

# 支援的檔案類型
FILE_EXTS = [".java", ".kt", ".xml"]

# ===== 註解清理函式 =====
def remove_comments(code: str, ext: str) -> str:
    if ext in [".java", ".kt"]:
        # 刪掉多行註解 /* ... */
        code = re.sub(r"/\*[\s\S]*?\*/", "", code)
        # 刪掉單行註解 //
        code = re.sub(r"//.*", "", code)
    elif ext == ".xml":
        # 刪掉 XML 註解 <!-- ... -->
        code = re.sub(r"<!--[\s\S]*?-->", "", code)
    return code

# ===== 遍歷專案 =====
def process_project():
    # 先複製一份專案結構
    if os.path.exists(OUTPUT_DIR):
        shutil.rmtree(OUTPUT_DIR)
    shutil.copytree(SOURCE_DIR, OUTPUT_DIR)

    # 開始處理檔案
    for root, _, files in os.walk(OUTPUT_DIR):
        for file in files:
            ext = os.path.splitext(file)[1]
            if ext in FILE_EXTS:
                file_path = os.path.join(root, file)
                with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
                    code = f.read()
                clean_code = remove_comments(code, ext)
                with open(file_path, "w", encoding="utf-8") as f:
                    f.write(clean_code)

    print(f"✅ 清理完成！乾淨版專案輸出在：{OUTPUT_DIR}")

if __name__ == "__main__":
    process_project()
