#!/bin/bash
# 六壬神鉴渐进发布环境配置脚本

set -e

echo "🚀 配置渐进发布环境..."

# 1. 配置 Git 别名简化操作
echo "配置 Git 别名..."
git config alias.deploy-staging '!git push staging staging:main'
git config alias.deploy-prod '!git push origin main'
git config alias.sync-all '!git fetch --all && git push --all'
git config alias.release-start '!git checkout develop && git pull && git checkout -b release/'
git config alias.release-finish '!git checkout main && git merge staging && git tag -a'

# 2. 创建发布分支
echo "创建发布分支..."
git checkout -b staging 2>/dev/null || git checkout staging
git checkout -b develop 2>/dev/null || git checkout develop

# 3. 推送分支到所有远程仓库
echo "推送分支到所有远程仓库..."
git push origin staging:staging 2>/dev/null || true
git push origin develop:develop 2>/dev/null || true
git push staging staging:main 2>/dev/null || true
git push staging develop:develop 2>/dev/null || true

# 4. 设置分支保护（需要管理员权限）
echo "设置分支保护规则..."
echo "⚠️ 请在 GitHub/GitLab/Gitea 后台手动设置以下分支保护："
echo "- main 分支：需要 PR 审查，禁止直接推送"
echo "- staging 分支：需要 PR 审查，禁止直接推送"
echo "- develop 分支：需要 PR 审查，禁止直接推送"

# 5. 创建发布标签模板
echo "创建发布标签模板..."
cat > .gitmessage.txt << 'EOF'
# 发布标签模板
# 格式：v主版本.次版本.修订版本-环境
#
# 示例：
# v1.2.0-canary (灰度发布)
# v1.2.0 (正式版本)
# v1.2.1-hotfix (热修复)
#
# 环境标识：
# -canary: 灰度发布
# -staging: 预发布测试
# -hotfix: 紧急修复
# 无后缀：正式版本

发布类型: [feature/bugfix/hotfix/docs]
影响范围: [core/api/ui/config]
测试状态: [passed/failed/pending]
回滚策略: [已准备/无需回滚]
EOF

git config commit.template .gitmessage.txt

# 6. 创建快速发布脚本
cat > scripts/quick-release.sh << 'EOF'
#!/bin/bash
# 快速发布脚本

VERSION=$1
ENV=$2

if [ -z "$VERSION" ] || [ -z "$ENV" ]; then
    echo "用法: ./quick-release.sh <版本号> <环境>"
    echo "环境选项: dev/staging/prod"
    exit 1
fi

case $ENV in
    dev)
        git checkout develop
        git tag "v${VERSION}-dev"
        git push gitea develop --tags
        ;;
    staging)
        git checkout staging
        git tag "v${VERSION}-staging"
        git push staging staging:main --tags
        ;;
    prod)
        git checkout main
        git tag "v${VERSION}"
        git push origin main --tags
        ;;
    *)
        echo "无效的环境选项"
        exit 1
        ;;
esac

echo "✅ 发布完成: v${VERSION}-${ENV}"
EOF

chmod +x scripts/quick-release.sh

# 7. 创建回滚脚本
cat > scripts/rollback.sh << 'EOF'
#!/bin/bash
# 快速回滚脚本

ENV=$1
VERSION=$2

if [ -z "$ENV" ] || [ -z "$VERSION" ]; then
    echo "用法: ./rollback.sh <环境> <版本号>"
    echo "环境选项: staging/prod"
    exit 1
fi

case $ENV in
    staging)
        git checkout staging
        git reset --hard "v${VERSION}-staging"
        git push staging staging:main --force
        ;;
    prod)
        git checkout main
        git reset --hard "v${VERSION}"
        git push origin main --force
        ;;
    *)
        echo "无效的环境选项"
        exit 1
        ;;
esac

echo "✅ 回滚完成: ${ENV} -> v${VERSION}"
EOF

chmod +x scripts/rollback.sh

# 8. 创建状态检查脚本
cat > scripts/check-status.sh << 'EOF'
#!/bin/bash
# 环境状态检查脚本

echo "📊 环境状态检查"
echo "=================="

# Git 状态
echo "Git 状态:"
git status --short

echo ""

# 远程仓库状态
echo "远程仓库状态:"
git remote -v

echo ""

# 分支状态
echo "分支状态:"
git branch -a

echo ""

# 最新标签
echo "最新标签:"
git tag --sort=-version:refname | head -5

echo ""

# 提交历史
echo "最近提交:"
git log --oneline -5
EOF

chmod +x scripts/check-status.sh

# 9. 创建 GitHub Actions 工作流目录
mkdir -p .github/workflows

# 10. 创建部署验证
echo "创建部署验证..."
cat > .github/workflows/deploy-validation.yml << 'EOF'
name: Deploy Validation

on:
  push:
    branches: [develop, staging, main]

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.9'
          
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt
          
      - name: Run tests
        run: |
          python -m pytest tests/ -v
          
      - name: Validate code style
        run: |
          pip install black flake8
          black --check .
          flake8 .
          
      - name: Security scan
        run: |
          pip install safety bandit
          safety check
          bandit -r . -f json -o security-report.json
EOF

echo "✅ 渐进发布环境配置完成！"
echo ""
echo "📋 使用指南:"
echo "1. 查看状态: ./scripts/check-status.sh"
echo "2. 快速发布: ./scripts/quick-release.sh 1.0.0 staging"
echo "3. 紧急回滚: ./scripts/rollback.sh prod 1.0.0"
echo "4. Git 别名: git deploy-staging, git deploy-prod"
echo ""
echo "📚 详细文档: docs/development/GRADUAL_DEPLOYMENT_PLAN.md"