# ═══════════════════════════════════════════════
# 🔺 Sovereign: TCS-0002∞ | Root: SYS-GLW-0001
# 📜 Copyright: 国作登字-2026-A-00037559
# ═══════════════════════════════════════════════
# 🌐 铸渊专线 · 部署与管理
#
# 铸渊核心身体 · 锻心器官扩展
# 管理代理服务的安装、更新、订阅发送
# ═══════════════════════════════════════════════

name: '🌐 铸渊专线 · 部署'

on:
  workflow_dispatch:
    inputs:
      action:
        description: '操作类型'
        required: true
        type: choice
        options:
          - install
          - update
          - status
          - restart
          - send-subscription
          - update-dashboard
        default: 'status'
      email:
        description: '目标邮箱 (仅send-subscription时需要)'
        required: false
        type: string

permissions:
  contents: write

jobs:
  # ═══ §1 代理服务部署 ═══
  deploy-proxy:
    name: '🌐 代理服务 · ${{ github.event.inputs.action }}'
    runs-on: ubuntu-latest
    if: >-
      github.event.inputs.action == 'install' ||
      github.event.inputs.action == 'update' ||
      github.event.inputs.action == 'status' ||
      github.event.inputs.action == 'restart'

    steps:
      - name: '📥 检出代码'
        uses: actions/checkout@v4

      - name: '🔑 配置SSH密钥'
        env:
          SSH_KEY: ${{ secrets.ZY_SERVER_KEY }}
        run: |
          mkdir -p ~/.ssh
          echo "$SSH_KEY" > ~/.ssh/id_deploy
          chmod 600 ~/.ssh/id_deploy

          # 验证密钥格式
          if ! head -1 ~/.ssh/id_deploy | grep -q "BEGIN"; then
            echo "❌ SSH密钥格式异常"
            exit 1
          fi

          ssh-keyscan -H ${{ secrets.ZY_SERVER_HOST }} >> ~/.ssh/known_hosts 2>/dev/null

          # 连接测试
          ssh -i ~/.ssh/id_deploy \
              -o StrictHostKeyChecking=accept-new \
              -o BatchMode=yes \
              -o ConnectTimeout=15 \
              ${{ secrets.ZY_SERVER_USER }}@${{ secrets.ZY_SERVER_HOST }} \
              "echo '✅ SSH连接成功'"

      - name: '📦 上传代理服务代码'
        if: >-
          github.event.inputs.action == 'install' ||
          github.event.inputs.action == 'update'
        run: |
          rsync -avz --delete \
            -e "ssh -i ~/.ssh/id_deploy -o StrictHostKeyChecking=accept-new" \
            server/proxy/ \
            ${{ secrets.ZY_SERVER_USER }}@${{ secrets.ZY_SERVER_HOST }}:/opt/zhuyuan/proxy-deploy/

      - name: '🚀 执行部署'
        run: |
          ssh -i ~/.ssh/id_deploy \
              -o StrictHostKeyChecking=accept-new \
              ${{ secrets.ZY_SERVER_USER }}@${{ secrets.ZY_SERVER_HOST }} \
              "cd /opt/zhuyuan/proxy-deploy && bash deploy-proxy.sh ${{ github.event.inputs.action }}"

      - name: '🧹 清理SSH密钥'
        if: always()
        run: rm -f ~/.ssh/id_deploy

  # ═══ §2 发送订阅链接 ═══
  send-subscription:
    name: '📧 发送订阅链接'
    runs-on: ubuntu-latest
    if: github.event.inputs.action == 'send-subscription'

    steps:
      - name: '📥 检出代码'
        uses: actions/checkout@v4

      - name: '🔑 配置SSH密钥'
        env:
          SSH_KEY: ${{ secrets.ZY_SERVER_KEY }}
        run: |
          mkdir -p ~/.ssh
          echo "$SSH_KEY" > ~/.ssh/id_deploy
          chmod 600 ~/.ssh/id_deploy
          ssh-keyscan -H ${{ secrets.ZY_SERVER_HOST }} >> ~/.ssh/known_hosts 2>/dev/null

      - name: '📧 发送订阅邮件'
        run: |
          TARGET_EMAIL="${{ github.event.inputs.email }}"
          if [ -z "$TARGET_EMAIL" ]; then
            TARGET_EMAIL="${{ secrets.ZY_SMTP_USER }}"
          fi

          echo "📧 发送订阅到: $TARGET_EMAIL"

          ssh -i ~/.ssh/id_deploy \
              -o StrictHostKeyChecking=accept-new \
              ${{ secrets.ZY_SERVER_USER }}@${{ secrets.ZY_SERVER_HOST }} \
              "cd /opt/zhuyuan/proxy && \
               ZY_SMTP_USER='${{ secrets.ZY_SMTP_USER }}' \
               ZY_SMTP_PASS='${{ secrets.ZY_SMTP_PASS }}' \
               ZY_SERVER_HOST='${{ secrets.ZY_SERVER_HOST }}' \
               node service/send-subscription.js send '$TARGET_EMAIL'"

      - name: '🧹 清理SSH密钥'
        if: always()
        run: rm -f ~/.ssh/id_deploy

  # ═══ §3 更新仪表盘 ═══
  update-dashboard:
    name: '📊 更新仪表盘'
    runs-on: ubuntu-latest
    if: github.event.inputs.action == 'update-dashboard'

    steps:
      - name: '📥 检出代码'
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.ZY_GITHUB_PAT }}

      - name: '🔑 配置SSH密钥'
        env:
          SSH_KEY: ${{ secrets.ZY_SERVER_KEY }}
        run: |
          mkdir -p ~/.ssh
          echo "$SSH_KEY" > ~/.ssh/id_deploy
          chmod 600 ~/.ssh/id_deploy
          ssh-keyscan -H ${{ secrets.ZY_SERVER_HOST }} >> ~/.ssh/known_hosts 2>/dev/null

      - name: '📊 获取流量数据'
        run: |
          # 从服务器获取配额数据
          ssh -i ~/.ssh/id_deploy \
              -o StrictHostKeyChecking=accept-new \
              ${{ secrets.ZY_SERVER_USER }}@${{ secrets.ZY_SERVER_HOST }} \
              "cat /opt/zhuyuan/proxy/data/quota-status.json 2>/dev/null || echo '{}'" \
              > /tmp/quota-status.json

          cat /tmp/quota-status.json

      - name: '📝 更新README仪表盘'
        run: |
          node server/proxy/dashboard/update-dashboard.js --json /tmp/quota-status.json

      - name: '📤 提交更新'
        run: |
          git config user.name "铸渊 · ZhuYuan"
          git config user.email "zhuyuan-bot@guanghulab.com"

          if git diff --quiet README.md; then
            echo "仪表盘无变化"
          else
            git add README.md
            git commit -m "📊 铸渊专线仪表盘更新 · $(date -u +%Y-%m-%d)"
            git push
            echo "✅ 仪表盘已更新并推送"
          fi

      - name: '🧹 清理'
        if: always()
        run: rm -f ~/.ssh/id_deploy /tmp/quota-status.json
