name: Create README

on:
  push:
    branches:
      - main  # 可根据实际情况修改为你的默认分支,如 master

jobs:
  create-readme:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code from Gitea
        env:
          GITEA_TOKEN: ${{ secrets.AUTOGENERATE }}
          GITEA_REPO_URL: ${{ github.server_url }}/${{ github.repository }}
          CLEAN_REPO_URL: ${{ github.server_url }}/${{ github.repository }}
        run: |
          # 去除多余的 https://
          CLEAN_REPO_URL="${CLEAN_REPO_URL#https://}"
          git clone "https://${GITEA_TOKEN}@${CLEAN_REPO_URL}" .

      - name: Delete existing README if exists
        run: |
          if [ -f README.md ]; then
            rm README.md
          fi

      - name: Get commit history and write to README
        run: |
          # 获取仓库名称
          REPO_NAME=$(basename "$GITHUB_REPOSITORY" .git)
          # 写入仓库名称到 README
          echo "# $REPO_NAME" > README.md
          # 获取所有提交记录并追加到 README
          git log --pretty=format:"- %h %an %ad %s" --date=short >> README.md
          # 显示 README.md 的内容(可选,用于调试)
          cat README.md

      - name: Commit and push changes
        env:
          GITEA_TOKEN: ${{ secrets.AUTOGENERATE }}
          GITEA_REPO_URL: ${{ github.server_url }}/${{ github.repository }}
          CLEAN_REPO_URL: ${{ github.server_url }}/${{ github.repository }}
        run: |
          # 去除多余的 https://
          CLEAN_REPO_URL="${CLEAN_REPO_URL#https://}"
          git config --local user.email "action@github.com"
          git config --local user.name "GitHub Action"
          git add README.md
          if git diff --staged --quiet; then
            echo "No changes to commit."
          else
            git commit -m "Create README with repository name"
            git push "https://${GITEA_TOKEN}@${CLEAN_REPO_URL}"
          fi