#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

echo "== 后端编译检查 =="
cd "$ROOT_DIR/apps/backend"
./.venv/bin/python -m compileall app

echo "== 后端 OpenAPI 检查 =="
DATABASE_URL=sqlite:///:memory: ./.venv/bin/python - <<'PY'
from app.main import app
paths = app.openapi().get("paths", {})
print(f"OpenAPI paths: {len(paths)}")
assert len(paths) >= 32
PY

echo "== 后端关键测试 =="
./.venv/bin/python -m pytest -q

echo "== Alembic MySQL 静态 SQL 检查 =="
./.venv/bin/alembic upgrade head --sql >/tmp/ai_kb_v2_migration.sql
wc -l /tmp/ai_kb_v2_migration.sql

echo "== 用户端 H5 构建 =="
cd "$ROOT_DIR/apps/user-client"
npm run build

echo "== 管理后台构建 =="
cd "$ROOT_DIR/apps/admin-web"
npm run build

echo "== Docker Compose 配置检查 =="
cd "$ROOT_DIR"
docker compose -f docker-compose.dev.yml config --quiet

echo "== 生产 Docker Compose 配置检查 =="
MYSQL_ROOT_PASSWORD=test-root \
MYSQL_PASSWORD=test-db \
REDIS_PASSWORD=test-redis \
DATABASE_URL='mysql+pymysql://ai_kb:test-db@mysql:3306/ai_knowledge_base_v2?charset=utf8mb4' \
REDIS_URL='redis://:test-redis@redis:6379/0' \
JWT_SECRET_KEY='test-jwt-secret-at-least-32-characters' \
CONFIG_ENCRYPTION_KEY='MDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDA=' \
BOOTSTRAP_ADMIN_USERNAME=admin \
BOOTSTRAP_ADMIN_PASSWORD='Strong-Test-Password-2026' \
docker compose -f docker-compose.prod.yml config --quiet

echo "== 备份恢复脚本语法检查 =="
bash -n scripts/mysql_backup.sh
bash -n scripts/mysql_restore.sh
bash -n scripts/production_smoke_test.sh

echo "阶段六自动验证完成"
