name: Sync Assets to Private B Repo
on:
  push:
    branches: [ main ]
    paths:
      - 'public/assets/**'
  workflow_dispatch:

jobs:
  sync:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout A Repo
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.x'

      - name: Prepare files and remove XML comments
        run: |
          # 创建临时目录
          mkdir -p temp-b-repo/out/assets
          
          # 检查源目录是否存在
          if [ ! -d "public/assets" ]; then
            echo "Error: public/assets directory not found!" && exit 1
          fi
          
          # 复制源文件到临时目录
          cp -rv public/assets/* public/assets/.* temp-b-repo/resource/xml/ 2>/dev/null || true
          echo "Files copied to temp directory (before processing):"
          ls -la temp-b-repo/out/assets
          
          # 生成Python脚本（逐行写入避免语法问题）
          echo "import xml.etree.ElementTree as ET" > remove_xml_comments.py
          echo "import os" >> remove_xml_comments.py
          echo "" >> remove_xml_comments.py
          echo "def remove_comments_from_xml(file_path):" >> remove_xml_comments.py
          echo "    try:" >> remove_xml_comments.py
          echo "        # 解析XML并保留注释" >> remove_xml_comments.py
          echo "        parser = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True))" >> remove_xml_comments.py
          echo "        tree = ET.parse(file_path, parser=parser)" >> remove_xml_comments.py
          echo "        root = tree.getroot()" >> remove_xml_comments.py
          echo "" >> remove_xml_comments.py
          echo "        # 递归删除注释节点" >> remove_xml_comments.py
          echo "        def remove_comments(element):" >> remove_xml_comments.py
          echo "            for child in list(element):" >> remove_xml_comments.py
          echo "                if child.tag is ET.Comment:" >> remove_xml_comments.py
          echo "                    element.remove(child)" >> remove_xml_comments.py
          echo "                else:" >> remove_xml_comments.py
          echo "                    remove_comments(child)" >> remove_xml_comments.py
          echo "" >> remove_xml_comments.py
          echo "        remove_comments(root)" >> remove_xml_comments.py
          echo "" >> remove_xml_comments.py
          echo "        # 保存修改后的文件" >> remove_xml_comments.py
          echo "        tree.write(file_path, encoding='utf-8', xml_declaration=True)" >> remove_xml_comments.py
          echo "        print(f'Processed: {file_path}')" >> remove_xml_comments.py
          echo "    except Exception as e:" >> remove_xml_comments.py
          echo "        print(f'Error processing {file_path}: {e}')" >> remove_xml_comments.py
          echo "" >> remove_xml_comments.py
          echo "# 遍历所有XML文件并处理" >> remove_xml_comments.py
          echo "for root_dir, _, files in os.walk('temp-b-repo/out/assets'):" >> remove_xml_comments.py
          echo "    for file in files:" >> remove_xml_comments.py
          echo "        if file.endswith('.xml'):" >> remove_xml_comments.py
          echo "            file_path = os.path.join(root_dir, file)" >> remove_xml_comments.py
          echo "            remove_comments_from_xml(file_path)" >> remove_xml_comments.py
          
          # 运行Python脚本
          python remove_xml_comments.py
          
          echo "Files in temp directory after comment removal:"
          ls -la temp-b-repo/out/assets

      - name: Push to Private B Repo
        env:
          B_REPO_TOKEN: ${{ secrets.B_REPO_TOKEN }}
          B_REPO_URL: https://github.com/TO-teams/flash.git  # 已修正为github.com
          B_BRANCH: main
        run: |
          git config --global user.name "GitHub Actions"
          git config --global user.email "actions@github.com"
          
          rm -rf b-repo
          git clone https://$B_REPO_TOKEN@${B_REPO_URL#https://} b-repo || { echo "Failed to clone B repo"; exit 1; }
          
          cd b-repo
          git checkout $B_BRANCH || { echo "Failed to checkout B branch"; exit 1; }
          git pull origin $B_BRANCH || { echo "Failed to pull B repo"; exit 1; }
          
          mkdir -p out/assets
          cp -rv ../temp-b-repo/resource/xml/* ../temp-b-repo/resource/xml/.* resource/xml/ 2>/dev/null || true
          echo "Files in B repo target directory after copy:"
          ls -la out/assets
          
          git add out/assets
          git commit -m "Sync assets (no comments): $(date +'%Y-%m-%d %H:%M:%S')"
          git push origin $B_BRANCH || { echo "Failed to push to B repo"; exit 1; }
          echo "Sync completed successfully."
