# ═══════════════════════════════════════════════
# 🔺 Sovereign: TCS-0002∞ | Root: SYS-GLW-0001
# 📜 Copyright: 国作登字-2026-A-00037559
# ═══════════════════════════════════════════════
# ♾️ 光湖语言世界 · 自主进化定时工作流
#
# 触发条件:
#   - push到main: ∞版本文件变更时自动部署 (deploy-infinity)
#   - 每月1号: 月度进化 (LLM分析 + 流量重置邮件)
#   - 手动触发: 任意∞版本操作
#
# 注: 大部分定时任务由服务器上的PM2进程 (auto-evolution.js)
#     自动执行。此工作流作为补充/备份触发机制。
# ═══════════════════════════════════════════════

name: '♾️ 光湖∞ · 自主进化'

on:
  push:
    branches: [main]
    paths:
      - 'server/proxy/service/auto-evolution.js'
      - 'server/proxy/service/email-hub.js'
      - 'server/proxy/service/protocol-mirror.js'
      - 'server/proxy/service/bandwidth-pool-agent.js'
      - 'server/proxy/service/swarm-defense-agent.js'
      - 'server/proxy/service/user-guardian-agent.js'
      - 'server/proxy/service/subscription-server-v3.js'
      - 'server/proxy/config/release-notes.json'
      - 'server/proxy/ecosystem.brain-proxy-v3.config.js'
  schedule:
    # 每月1号 UTC 16:00 = CST 00:00 (月度进化)
    - cron: '0 16 1 * *'
  workflow_dispatch:
    inputs:
      action:
        description: '操作类型'
        required: true
        type: choice
        options:
          - monthly-evolution
          - deploy-infinity
          - status
          - add-user
          - remove-user
          - list-users
          - send-subscription-v3
          - send-monthly-reset
          - send-update-notify
          - send-update-notify-single
          - send-traffic-warn
          - send-bandwidth-auth
          - send-bandwidth-auth-single
          - send-threat-alert
          - send-threat-cleared
          - list-user-emails
        default: 'status'
      message:
        description: '附加消息 (update-notify描述 / traffic-warn百分比 / threat-alert消息) · 描述支持分号分隔多条内容'
        required: false
        type: string
      email:
        description: '目标邮箱 (add-user/remove-user/send-subscription-v3/send-update-notify-single/send-bandwidth-auth-single时需要)'
        required: false
        type: string
      quota_gb:
        description: '月配额GB (add-user时可选，默认500)'
        required: false
        type: string
        default: '500'

permissions:
  contents: read

concurrency:
  group: infinity-evolution
  cancel-in-progress: false

jobs:
  # ═══ §1 ∞版本部署/管理 ═══
  infinity-action:
    name: '♾️ ${{ github.event_name == ''push'' && ''deploy-infinity (auto)'' || github.event.inputs.action || ''monthly-evolution'' }}'
    runs-on: ubuntu-latest
    timeout-minutes: 15

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

      - name: '🔑 配置SSH'
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.ZY_BRAIN_KEY }}" > ~/.ssh/brain_key
          chmod 600 ~/.ssh/brain_key
          ssh-keyscan -H ${{ secrets.ZY_BRAIN_HOST }} >> ~/.ssh/known_hosts 2>/dev/null || true

      - name: '♾️ 执行∞操作'
        env:
          ACTION: ${{ github.event_name == 'push' && 'deploy-infinity' || github.event.inputs.action || 'monthly-evolution' }}
          MESSAGE: ${{ github.event.inputs.message || '' }}
          EMAIL: ${{ github.event.inputs.email || '' }}
          QUOTA: ${{ github.event.inputs.quota_gb || '500' }}
          ZY_SMTP_USER: ${{ secrets.ZY_SMTP_USER }}
          ZY_SMTP_PASS: ${{ secrets.ZY_SMTP_PASS }}
        run: |
          SSH_CMD="ssh -i ~/.ssh/brain_key -o StrictHostKeyChecking=no ${{ secrets.ZY_BRAIN_USER }}@${{ secrets.ZY_BRAIN_HOST }}"
          PROXY_DIR="/opt/zhuyuan-brain/proxy"
          SCP_CMD="scp -i ~/.ssh/brain_key -o StrictHostKeyChecking=no"
          REMOTE_HOST="${{ secrets.ZY_BRAIN_USER }}@${{ secrets.ZY_BRAIN_HOST }}"

          # ── 同步邮件模块到服务器 ──
          # 确保服务器上的email-hub.js和相关模块是最新版本
          sync_email_files() {
            echo "📦 同步邮件模块到服务器..."
            $SSH_CMD "mkdir -p $PROXY_DIR/.deploy-tmp $PROXY_DIR/config"
            $SCP_CMD \
              server/proxy/service/email-hub.js \
              server/proxy/service/bandwidth-pool-agent.js \
              server/proxy/service/subscription-server-v3.js \
              server/proxy/config/release-notes.json \
              ${REMOTE_HOST}:$PROXY_DIR/.deploy-tmp/
            $SSH_CMD "
              cp $PROXY_DIR/.deploy-tmp/email-hub.js $PROXY_DIR/service/
              cp $PROXY_DIR/.deploy-tmp/bandwidth-pool-agent.js $PROXY_DIR/service/
              cp $PROXY_DIR/.deploy-tmp/subscription-server-v3.js $PROXY_DIR/service/
              cp $PROXY_DIR/.deploy-tmp/release-notes.json $PROXY_DIR/config/
              rm -rf $PROXY_DIR/.deploy-tmp
            "
            echo "✅ 邮件模块已同步"
          }

          echo "════════════════════════════════════════"
          echo "♾️ 光湖∞ · 自主进化 · action=$ACTION"
          echo "════════════════════════════════════════"

          case "$ACTION" in
            deploy-infinity)
              echo "部署∞版本..."
              # 先同步最新代码到服务器
              $SSH_CMD "mkdir -p $PROXY_DIR/.deploy-tmp"

              scp -i ~/.ssh/brain_key -o StrictHostKeyChecking=no \
                server/proxy/service/auto-evolution.js \
                server/proxy/service/email-hub.js \
                server/proxy/service/protocol-mirror.js \
                server/proxy/service/bandwidth-pool-agent.js \
                server/proxy/service/swarm-defense-agent.js \
                server/proxy/service/user-guardian-agent.js \
                server/proxy/service/subscription-server-v3.js \
                server/proxy/config/release-notes.json \
                server/proxy/ecosystem.brain-proxy-v3.config.js \
                ${{ secrets.ZY_BRAIN_USER }}@${{ secrets.ZY_BRAIN_HOST }}:$PROXY_DIR/.deploy-tmp/

              $SSH_CMD "
                cp $PROXY_DIR/.deploy-tmp/auto-evolution.js $PROXY_DIR/service/
                cp $PROXY_DIR/.deploy-tmp/email-hub.js $PROXY_DIR/service/
                cp $PROXY_DIR/.deploy-tmp/protocol-mirror.js $PROXY_DIR/service/
                cp $PROXY_DIR/.deploy-tmp/bandwidth-pool-agent.js $PROXY_DIR/service/
                cp $PROXY_DIR/.deploy-tmp/swarm-defense-agent.js $PROXY_DIR/service/
                cp $PROXY_DIR/.deploy-tmp/user-guardian-agent.js $PROXY_DIR/service/
                cp $PROXY_DIR/.deploy-tmp/subscription-server-v3.js $PROXY_DIR/service/
                mkdir -p $PROXY_DIR/config
                cp $PROXY_DIR/.deploy-tmp/release-notes.json $PROXY_DIR/config/
                cp $PROXY_DIR/.deploy-tmp/ecosystem.brain-proxy-v3.config.js $PROXY_DIR/
                rm -rf $PROXY_DIR/.deploy-tmp
                mkdir -p $PROXY_DIR/data/evolution-reports
                cd $PROXY_DIR && pm2 startOrRestart ecosystem.brain-proxy-v3.config.js --update-env && pm2 save
                echo '✅ ∞版本已部署'
                pm2 list
              "
              ;;

            monthly-evolution)
              sync_email_files
              echo "触发月度进化..."
              $SSH_CMD "
                cd $PROXY_DIR
                export ZY_SMTP_USER='$ZY_SMTP_USER'
                export ZY_SMTP_PASS='$ZY_SMTP_PASS'
                node service/email-hub.js monthly-reset 2>&1 || echo '⚠️ 月度邮件发送遇到问题'
                echo '✅ 月度进化已触发'
              "
              ;;

            status)
              echo "查询∞版本状态..."
              $SSH_CMD "
                cd $PROXY_DIR
                echo '── PM2进程 ──'
                pm2 list 2>/dev/null || echo '⚠️ PM2不可用'
                echo ''
                echo '── 进化状态 ──'
                cat data/auto-evolution-status.json 2>/dev/null || echo '(未初始化)'
                echo ''
                echo '── 镜像状态 ──'
                cat data/protocol-mirror-status.json 2>/dev/null || echo '(未初始化)'
                echo ''
                echo '── 流量池 ──'
                cat data/pool-quota-status.json 2>/dev/null || echo '(未初始化)'
              "
              ;;

            add-user)
              if [ -z "$EMAIL" ]; then
                echo "❌ 请提供目标邮箱 (email字段)"
                exit 1
              fi
              if ! echo "$EMAIL" | grep -qE '^[^@]+@[^@]+\.[^@]+$'; then
                echo "❌ 邮箱格式不正确: $EMAIL"
                exit 1
              fi
              echo "➕ 新增用户: $EMAIL (配额: ${QUOTA}GB/月)"
              $SSH_CMD "
                cd $PROXY_DIR
                node service/user-manager.js add '$EMAIL' '${QUOTA}'
              "
              echo ""
              echo "════════════════════════════════════════"
              echo "✅ 用户已添加"
              echo "下一步: 运行 send-subscription-v3 发送V3订阅链接到 $EMAIL"
              echo "════════════════════════════════════════"
              ;;

            remove-user)
              if [ -z "$EMAIL" ]; then
                echo "❌ 请提供目标邮箱 (email字段)"
                exit 1
              fi
              if ! echo "$EMAIL" | grep -qE '^[^@]+@[^@]+\.[^@]+$'; then
                echo "❌ 邮箱格式不正确: $EMAIL"
                exit 1
              fi
              echo "➖ 移除用户: $EMAIL"
              $SSH_CMD "
                cd $PROXY_DIR
                node service/user-manager.js remove '$EMAIL'
              "
              ;;

            list-users)
              echo "📋 用户列表:"
              $SSH_CMD "
                cd $PROXY_DIR
                node service/user-manager.js list
              "
              ;;

            send-subscription-v3)
              if [ -z "$EMAIL" ]; then
                echo "❌ 请提供目标邮箱 (email字段)"
                echo "💡 可先使用 list-users 或 list-user-emails 查看用户"
                exit 1
              fi
              if ! echo "$EMAIL" | grep -qE '^[^@]+@[^@]+\.[^@]+$'; then
                echo "❌ 邮箱格式不正确: $EMAIL"
                exit 1
              fi
              sync_email_files
              echo "发送V3订阅链接 (含系统介绍+带宽共享邀请) 给: $EMAIL ..."
              $SSH_CMD "
                cd $PROXY_DIR
                export ZY_SMTP_USER='$ZY_SMTP_USER'
                export ZY_SMTP_PASS='$ZY_SMTP_PASS'
                node service/email-hub.js send-subscription-v3 '$EMAIL'
              "
              ;;

            send-monthly-reset)
              sync_email_files
              echo "发送月初重置邮件..."
              $SSH_CMD "
                cd $PROXY_DIR
                export ZY_SMTP_USER='$ZY_SMTP_USER'
                export ZY_SMTP_PASS='$ZY_SMTP_PASS'
                node service/email-hub.js monthly-reset
              "
              ;;

            send-update-notify)
              sync_email_files
              echo "一键发送更新通知 (全部用户)..."
              $SSH_CMD "
                cd $PROXY_DIR
                export ZY_SMTP_USER='$ZY_SMTP_USER'
                export ZY_SMTP_PASS='$ZY_SMTP_PASS'
                # 有MESSAGE时传入描述，否则省略让email-hub自动读取release-notes.json
                node service/email-hub.js update-notify ${MESSAGE:+'$MESSAGE'}
              "
              ;;

            send-update-notify-single)
              if [ -z "$EMAIL" ]; then
                echo "❌ 请提供目标邮箱 (email字段)"
                echo "💡 可先使用 list-user-emails 查看所有用户邮箱"
                exit 1
              fi
              if ! echo "$EMAIL" | grep -qE '^[^@]+@[^@]+\.[^@]+$'; then
                echo "❌ 邮箱格式不正确: $EMAIL"
                exit 1
              fi
              sync_email_files
              echo "单独发送更新通知给: $EMAIL ..."
              $SSH_CMD "
                cd $PROXY_DIR
                export ZY_SMTP_USER='$ZY_SMTP_USER'
                export ZY_SMTP_PASS='$ZY_SMTP_PASS'
                # 有MESSAGE时传入描述，否则省略让email-hub自动读取release-notes.json
                node service/email-hub.js update-notify-single '$EMAIL' ${MESSAGE:+'$MESSAGE'}
              "
              ;;

            send-traffic-warn)
              sync_email_files
              echo "发送流量预警..."
              $SSH_CMD "
                cd $PROXY_DIR
                export ZY_SMTP_USER='$ZY_SMTP_USER'
                export ZY_SMTP_PASS='$ZY_SMTP_PASS'
                node service/email-hub.js traffic-warn '${MESSAGE:-70}'
              "
              ;;

            send-bandwidth-auth)
              sync_email_files
              echo "一键发送带宽验证码 (全部用户·自动提取邮箱·加密发送)..."
              $SSH_CMD "
                cd $PROXY_DIR
                export ZY_SMTP_USER='$ZY_SMTP_USER'
                export ZY_SMTP_PASS='$ZY_SMTP_PASS'
                node service/email-hub.js bandwidth-auth-all
              "
              ;;

            send-bandwidth-auth-single)
              if [ -z "$EMAIL" ]; then
                echo "❌ 请提供目标邮箱 (email字段)"
                echo "💡 可先使用 list-user-emails 查看所有用户邮箱"
                exit 1
              fi
              if ! echo "$EMAIL" | grep -qE '^[^@]+@[^@]+\.[^@]+$'; then
                echo "❌ 邮箱格式不正确: $EMAIL"
                exit 1
              fi
              sync_email_files
              echo "单独发送带宽验证码给: $EMAIL ..."
              $SSH_CMD "
                cd $PROXY_DIR
                export ZY_SMTP_USER='$ZY_SMTP_USER'
                export ZY_SMTP_PASS='$ZY_SMTP_PASS'
                node service/email-hub.js bandwidth-auth '$EMAIL'
              "
              ;;

            list-user-emails)
              sync_email_files
              echo "查询所有用户邮箱..."
              $SSH_CMD "
                cd $PROXY_DIR
                node service/email-hub.js list-emails
              "
              ;;

            send-threat-alert)
              sync_email_files
              echo "发送全体用户风险提示..."
              if [ -z "$MESSAGE" ]; then
                echo "❌ 请在message中输入风险描述"
                exit 1
              fi
              $SSH_CMD "
                cd $PROXY_DIR
                export ZY_SMTP_USER='$ZY_SMTP_USER'
                export ZY_SMTP_PASS='$ZY_SMTP_PASS'
                node service/email-hub.js threat-alert '$MESSAGE'
              "
              ;;

            send-threat-cleared)
              sync_email_files
              echo "发送全体用户安全恢复通知..."
              $SSH_CMD "
                cd $PROXY_DIR
                export ZY_SMTP_USER='$ZY_SMTP_USER'
                export ZY_SMTP_PASS='$ZY_SMTP_PASS'
                node service/email-hub.js threat-cleared
              "
              ;;

            *)
              echo "❌ 未知操作: $ACTION"
              exit 1
              ;;
          esac
