#!/bin/bash

# Local CI Validation Script
# Tests all CI checks locally before pushing

set -e

echo "=========================================="
echo "Local CI Validation"
echo "=========================================="
echo ""

cd "$(git rev-parse --show-toplevel)/backend"

# Test 1: Format check
echo "🔍 Test 1: Code Formatting Check"
echo "Command: cargo fmt --all -- --check"
if cargo fmt --all -- --check; then
    echo "✅ PASS - Code is properly formatted"
else
    echo "❌ FAIL - Code needs formatting"
    echo "Run: cargo fmt --all"
    exit 1
fi
echo ""

# Test 2: Clippy
echo "🔍 Test 2: Clippy Lint"
echo "Command: cargo clippy --all-targets --all-features -- -D warnings"
if cargo clippy --all-targets --all-features -- -D warnings; then
    echo "✅ PASS - No clippy warnings"
else
    echo "❌ FAIL - Clippy found issues"
    exit 1
fi
echo ""

# Test 3: Build
echo "🔍 Test 3: Build Release Binary"
echo "Command: cargo build --release"
if cargo build --release; then
    echo "✅ PASS - Build successful"
    BINARY_SIZE=$(du -h target/release/normogen-backend | cut -f1)
    echo "Binary size: $BINARY_SIZE"
else
    echo "❌ FAIL - Build failed"
    exit 1
fi
echo ""

# Test 4: Verify binary exists
echo "🔍 Test 4: Verify Binary"
if [ -f target/release/normogen-backend ]; then
    echo "✅ PASS - Binary exists"
    file target/release/normogen-backend
else
    echo "❌ FAIL - Binary not found"
    exit 1
fi
echo ""

# Test 5: Docker build (only if Docker is available locally)
if command -v docker &> /dev/null && docker info &> /dev/null; then
    echo "🔍 Test 5: Docker Build"
    echo "Command: docker build -f docker/Dockerfile -t normogen-backend:test ."
    if docker build -f docker/Dockerfile -t normogen-backend:test .; then
        echo "✅ PASS - Docker image built"
        docker images normogen-backend:test
    else
        echo "❌ FAIL - Docker build failed"
        exit 1
    fi
    echo ""
else
    echo "⚠️  SKIP - Docker not available locally"
    echo "   Note: Docker build will run in Forgejo CI on Solaria"
    echo "   This is expected and OK!"
    echo ""
fi

echo "=========================================="
echo "✅ All Local CI Checks Passed!"
echo "=========================================="
echo ""
echo "Changes ready to commit:"
echo "  ✅ Code formatting"
echo "  ✅ Clippy linting"
echo "  ✅ Build successful"
echo "  ✅ Binary created"
echo ""
echo "Next steps:"
echo "  1. Commit the changes"
echo "  2. Push to Forgejo"
echo "  3. Watch CI run at: http://gitea.solivarez.com.ar/alvaro/normogen/actions"
echo ""
echo "The Forgejo CI will also:"
echo "  • Verify formatting (same as local)"
echo "  • Run Clippy (same as local)"
echo "  • Build the binary (same as local)"
echo "  • Build Docker image with Buildx (runs on Solaria)"
