#!/bin/bash
# =============================================================================
# AWOOOI Guardrails Setup Script
# =============================================================================
# Phase 5: 全自動防禦網安裝腳本
#
# Usage: ./scripts/setup-guardrails.sh
#
# This script:
# 1. Installs pre-commit if not present
# 2. Installs Git hooks
# 3. Creates secrets baseline
# 4. Verifies Ollama connection
# =============================================================================

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

echo ""
echo "============================================================"
echo "🛡️  AWOOOI Guardrails Setup"
echo "============================================================"
echo ""

cd "$PROJECT_ROOT"

# -----------------------------------------------------------------------------
# Step 1: Check Python
# -----------------------------------------------------------------------------
echo "📦 Step 1: Checking Python environment..."

if ! command -v python3 &> /dev/null; then
    echo "❌ Python 3 not found. Please install Python 3.11+"
    exit 1
fi

PYTHON_VERSION=$(python3 --version | cut -d' ' -f2)
echo "   Python version: $PYTHON_VERSION"

# -----------------------------------------------------------------------------
# Step 2: Install pre-commit
# -----------------------------------------------------------------------------
echo ""
echo "📦 Step 2: Installing pre-commit..."

if command -v pre-commit &> /dev/null; then
    echo "   pre-commit already installed: $(pre-commit --version)"
else
    pip3 install pre-commit
    echo "   pre-commit installed: $(pre-commit --version)"
fi

# -----------------------------------------------------------------------------
# Step 3: Install httpx for AI reviewer
# -----------------------------------------------------------------------------
echo ""
echo "📦 Step 3: Installing httpx (for AI reviewer)..."

pip3 install httpx --quiet
echo "   httpx installed"

# -----------------------------------------------------------------------------
# Step 4: Install Git hooks
# -----------------------------------------------------------------------------
echo ""
echo "🔗 Step 4: Installing Git hooks..."

pre-commit install
pre-commit install --hook-type commit-msg

echo "   Git hooks installed"

# -----------------------------------------------------------------------------
# Step 5: Create secrets baseline
# -----------------------------------------------------------------------------
echo ""
echo "🔒 Step 5: Creating secrets baseline..."

if [ ! -f ".secrets.baseline" ]; then
    pip3 install detect-secrets --quiet
    detect-secrets scan > .secrets.baseline
    echo "   .secrets.baseline created"
else
    echo "   .secrets.baseline already exists"
fi

# -----------------------------------------------------------------------------
# Step 6: Verify Ollama connection
# -----------------------------------------------------------------------------
echo ""
echo "🤖 Step 6: Verifying Ollama connection..."

OLLAMA_URL="http://192.168.0.188:11434/api/tags"

if curl -s --connect-timeout 5 "$OLLAMA_URL" > /dev/null 2>&1; then
    echo "   ✅ Ollama reachable at 192.168.0.188:11434"

    # Check if llama3.2:8b is available
    MODELS=$(curl -s "$OLLAMA_URL" | grep -o '"name":"[^"]*"' || echo "")
    if echo "$MODELS" | grep -q "llama3.2:8b"; then
        echo "   ✅ Model llama3.2:8b available"
    else
        echo "   ⚠️  Model llama3.2:8b not found. AI review will fail-open."
    fi
else
    echo "   ⚠️  Cannot reach Ollama. AI review will fail-open."
    echo "      (This is OK - AI review is optional)"
fi

# -----------------------------------------------------------------------------
# Step 7: Summary
# -----------------------------------------------------------------------------
echo ""
echo "============================================================"
echo "✅ Guardrails Setup Complete!"
echo "============================================================"
echo ""
echo "Installed components:"
echo "  📌 Ruff (Python linting)     - Configured in pyproject.toml"
echo "  📌 ESLint (TypeScript)       - Configured in packages/eslint-config"
echo "  📌 pre-commit hooks          - .pre-commit-config.yaml"
echo "  📌 AI Code Reviewer          - scripts/ai_code_reviewer.py"
echo "  📌 Secrets detection         - .secrets.baseline"
echo ""
echo "How it works:"
echo "  1. On 'git commit', pre-commit runs automatically"
echo "  2. Ruff checks Python code style"
echo "  3. ESLint checks TypeScript code style"
echo "  4. detect-secrets scans for leaked credentials"
echo "  5. AI reviewer (Ollama) checks for architecture violations"
echo ""
echo "Commands:"
echo "  pre-commit run --all-files   # Run all checks manually"
echo "  pre-commit autoupdate        # Update hook versions"
echo "  pre-commit uninstall         # Remove hooks"
echo ""
