name: release

on:
  push:
    tags:
      - "v*.*.*"

jobs:
  # ─── Gate：所有 publish/deploy 前先跑 test+lint ───
  test:
    name: test + lint（gate）
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/setup-uv@v4
        with: { version: "latest", enable-cache: true }
      - run: uv sync --all-groups
      - run: uv run pytest -q
      - run: uv run ruff check src test scripts
      - run: uv run ruff format --check src test scripts

  # ─── 发 PyPI ───
  publish-pypi:
    name: 发 PyPI
    needs: [test]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/setup-uv@v4
        with: { version: "latest" }
      - run: uv sync --all-groups
      - run: |
          rm -rf dist/
          uv build
      - name: 发布到 PyPI
        env:
          UV_PUBLISH_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
        run: uv publish

  # ─── 同步 SKILL.md 到 acong-tech-skills/xiangqin 仓（skills.sh 分发源）───
  sync-skills-sh:
    name: 同步 skills.sh GitHub 仓
    needs: [test]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: webfactory/ssh-agent@v0.9.0
        with:
          ssh-private-key: ${{ secrets.SKILL_REPO_DEPLOY_KEY }}
      - name: clone skill 仓
        run: |
          ssh-keyscan github.com >> ~/.ssh/known_hosts
          git clone git@github.com:acong-tech-skills/xiangqin.git /tmp/skill
      - name: 同步 SKILL.md + README.md + tag
        env:
          TAG: ${{ github.ref_name }}
        run: |
          # 主仓双源（SKILL.md + SKILL-REPO-README.md）同步到 skill 仓两个文件
          cp SKILL.md /tmp/skill/SKILL.md
          cp SKILL-REPO-README.md /tmp/skill/README.md
          cd /tmp/skill
          if git diff --quiet; then
            echo "SKILL.md + README.md 未变化，跳过 commit（仍打 tag）"
          else
            git -c user.email="actions@github.com" -c user.name="GitHub Actions" \
              commit -am "sync SKILL.md + README.md $TAG"
            git push origin main
          fi
          git tag "$TAG"
          git push origin "$TAG"

  # ─── 发 ClawHub ───
  publish-clawhub:
    name: 发 ClawHub
    needs: [test]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: 装 clawhub CLI
        run: npm install -g clawhub
      - name: 配 clawhub 认证
        env:
          CLAWHUB_TOKEN: ${{ secrets.CLAWHUB_TOKEN }}
        run: |
          mkdir -p ~/.config/clawhub
          printf '{"registry":"https://clawhub.ai","token":"%s"}\n' "$CLAWHUB_TOKEN" > ~/.config/clawhub/config.json
          chmod 600 ~/.config/clawhub/config.json
      - name: 准备 skill 目录（SKILL.md + README.md 从主仓源文件）
        run: |
          mkdir -p /tmp/skill-publish
          cp SKILL.md /tmp/skill-publish/SKILL.md
          cp SKILL-REPO-README.md /tmp/skill-publish/README.md
      - name: clawhub publish
        env:
          TAG: ${{ github.ref_name }}
        run: |
          VERSION="${TAG#v}"
          clawhub publish /tmp/skill-publish \
            --slug acong-tech-xiangqin \
            --name "xiangqin" \
            --version "$VERSION" \
            --changelog "xiangqin $TAG —— 详见 https://github.com/yarnovo/xiangqin/blob/$TAG/CHANGELOG.md"

      - name: 发布后扫描结果 verify（API 权威，不走 GUI）
        env:
          TAG: ${{ github.ref_name }}
          CLAWHUB_TOKEN: ${{ secrets.CLAWHUB_TOKEN }}
        run: |
          # 等 30 秒让扫描 pipeline 跑完
          sleep 30
          VERSION="${TAG#v}"
          # retry 3 次（LLM 扫描异步，可能要多等）
          for i in 1 2 3; do
            if ./scripts/check-clawhub-scan.sh "$VERSION"; then
              exit 0
            fi
            echo "attempt $i not clean yet, waiting 30s..."
            sleep 30
          done
          echo "✗ ClawHub scan 3 次重试都不 clean，检查 VT Code insights + 修 SKILL.md"
          exit 1

  # ─── Chain：PyPI 发完自动 deploy 生产 ───
  deploy-production:
    name: 部署到 epsilon 生产
    needs: [publish-pypi]
    runs-on: ubuntu-latest
    environment:
      name: production
      url: http://112.124.27.213/health
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.ref_name }}
      - uses: webfactory/ssh-agent@v0.9.0
        with:
          ssh-private-key: ${{ secrets.EPSILON_SSH_KEY }}
      - name: known_hosts
        run: |
          mkdir -p ~/.ssh
          ssh-keyscan ${{ secrets.EPSILON_HOST }} >> ~/.ssh/known_hosts
      - name: rsync 源码（保留 .env / logs / data 运行时资产）
        run: |
          rsync -az --delete \
            --exclude '.venv' --exclude '__pycache__' --exclude '.pytest_cache' \
            --exclude 'data' --exclude 'logs' --exclude '*.db*' --exclude '.git' \
            --exclude '.github' --exclude 'site' --exclude '.env' --exclude '.vault' \
            ./ root@${{ secrets.EPSILON_HOST }}:/opt/xiangqin/
      - name: 远端 mkdir 运行时目录 + uv sync + chown
        run: |
          ssh root@${{ secrets.EPSILON_HOST }} "cd /opt/xiangqin && \
            mkdir -p /opt/xiangqin/logs /opt/xiangqin/data && \
            UV_PYTHON_INSTALL_DIR=/opt/uv-python \
            UV_PYTHON_PREFERENCE=only-managed UV_PYTHON=3.12 \
            UV_HTTP_TIMEOUT=120 \
            /root/.local/bin/uv sync --no-group dev && \
            chown -R xiangqin:xiangqin /opt/xiangqin"
      - name: systemd + 重启
        run: |
          ssh root@${{ secrets.EPSILON_HOST }} "cp /opt/xiangqin/systemd/xiangqin.service /etc/systemd/system/ && \
            systemctl daemon-reload && \
            systemctl enable xiangqin && \
            systemctl restart xiangqin && \
            sleep 2 && \
            systemctl is-active xiangqin"
      - name: smoke test
        run: |
          ssh root@${{ secrets.EPSILON_HOST }} 'for i in $(seq 1 15); do \
            curl -sf http://127.0.0.1/health >/dev/null && break; sleep 1; done; \
            curl -s http://127.0.0.1/health'
