#!/usr/bin/env bash
# 架构约束自动检查
# 用法: bash scripts/check-architecture.sh

set -euo pipefail

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

ERRORS=0

echo "==> 检查架构约束"

# ── 检查循环导入 ──────────────────────────────────────────
echo "    检查循环导入..."
if command -v python &> /dev/null; then
  # 使用 Python AST 简单检测可疑的循环引用模式
  python -c "
import ast, sys, os
from pathlib import Path

src = Path('src')
if not src.exists():
    sys.exit(0)

modules = {}
for f in src.rglob('*.py'):
    if f.name == '__init__.py':
        continue
    try:
        tree = ast.parse(f.read_text())
        imports = []
        for node in ast.walk(tree):
            if isinstance(node, ast.ImportFrom) and node.module:
                imports.append(node.module)
        modules[str(f)] = imports
    except SyntaxError:
        print(f'    [警告] 语法错误: {f}')

# 简单的双向引用检测
for f1, imps1 in modules.items():
    for f2, imps2 in modules.items():
        if f1 >= f2:
            continue
        m1 = str(Path(f1).with_suffix('')).replace('/', '.')
        m2 = str(Path(f2).with_suffix('')).replace('/', '.')
        if any(m2.endswith(i) or i.endswith(m2.split('.')[-1]) for i in imps1) and \
           any(m1.endswith(i) or i.endswith(m1.split('.')[-1]) for i in imps2):
            print(f'    [可疑] 可能的循环引用: {f1} <-> {f2}')
" || true
fi

# ── 检查敏感文件 ──────────────────────────────────────────
echo "    检查敏感文件..."
if git ls-files --cached | grep -qE '\.env$|credentials|secret'; then
  echo "    [错误] 发现敏感文件在 git 追踪中:"
  git ls-files --cached | grep -E '\.env$|credentials|secret'
  ERRORS=$((ERRORS + 1))
fi

# ── 检查调试代码残留 ──────────────────────────────────────
echo "    检查调试代码残留..."
if [ -d "src" ]; then
  DEBUG_HITS=$(grep -rn "breakpoint()\|pdb\.set_trace()\|import pdb" src/ 2>/dev/null || true)
  if [ -n "$DEBUG_HITS" ]; then
    echo "    [错误] 发现调试代码残留:"
    echo "$DEBUG_HITS"
    ERRORS=$((ERRORS + 1))
  fi
fi

# ── 检查 .gitignore 基本项 ────────────────────────────────
echo "    检查 .gitignore..."
if [ -f ".gitignore" ]; then
  for pattern in "venv" "__pycache__" ".env"; do
    if ! grep -q "$pattern" .gitignore; then
      echo "    [警告] .gitignore 缺少 $pattern"
    fi
  done
else
  echo "    [警告] 未找到 .gitignore 文件"
fi

# ── 汇总 ─────────────────────────────────────────────────
echo ""
if [ $ERRORS -gt 0 ]; then
  echo "==> 发现 $ERRORS 个架构违规。请修复后再提交。"
  exit 1
else
  echo "==> 架构检查通过。"
  exit 0
fi
