#!/usr/bin/env bash
# Verify skeleton templates are correct and in-sync with committed example.
#
# This script:
# 1. Builds the render-skeleton tool
# 2. Renders a fresh skeleton to a temp directory
# 3. Compares with the committed examples/full-monorepo
# 4. Attempts to build Go and TypeScript code
#
# Usage:
#   ./scripts/verify-skeleton.sh           # Full verification
#   ./scripts/verify-skeleton.sh --quick   # Skip TypeScript (faster)
#   ./scripts/verify-skeleton.sh --update  # Update examples/full-monorepo
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$SCRIPT_DIR/.."
EXAMPLE_DIR="$ROOT_DIR/examples/full-monorepo"

# Parse args
QUICK_MODE=false
UPDATE_MODE=false
for arg in "$@"; do
    case $arg in
        --quick)
            QUICK_MODE=true
            ;;
        --update)
            UPDATE_MODE=true
            ;;
    esac
done

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

info() { echo -e "${GREEN}==>${NC} $1"; }
warn() { echo -e "${YELLOW}==>${NC} $1"; }
error() { echo -e "${RED}==>${NC} $1"; }

# Build render tool
info "Building render-skeleton tool..."
go build -o /tmp/render-skeleton ./cmd/render-skeleton

# Handle update mode
if [ "$UPDATE_MODE" = true ]; then
    info "Updating examples/full-monorepo..."
    /tmp/render-skeleton -output "$EXAMPLE_DIR"
    info "Done! Review changes with: git diff examples/full-monorepo"
    exit 0
fi

# Render to temp directory
TEMP_DIR=$(mktemp -d)
trap 'rm -rf "$TEMP_DIR"' EXIT

info "Rendering skeleton to temp directory..."
/tmp/render-skeleton -output "$TEMP_DIR" > /dev/null

# Compare with committed example
info "Comparing with committed example..."

# Check if example directory exists
if [ ! -d "$EXAMPLE_DIR" ]; then
    error "examples/full-monorepo does not exist!"
    echo ""
    echo "Run: ./scripts/verify-skeleton.sh --update"
    exit 1
fi

# Compare directories (excluding common build artifacts)
DIFF_OUTPUT=$(diff -rq \
    --exclude='.git' \
    --exclude='node_modules' \
    --exclude='pnpm-lock.yaml' \
    --exclude='.next' \
    --exclude='.astro' \
    --exclude='dist' \
    --exclude='go.sum' \
    --exclude='go.work.sum' \
    "$TEMP_DIR" "$EXAMPLE_DIR" 2>&1 || true)

if [ -n "$DIFF_OUTPUT" ]; then
    error "examples/full-monorepo is OUT OF SYNC with templates!"
    echo ""
    echo "$DIFF_OUTPUT" | head -20
    echo ""
    echo "To update, run: ./scripts/verify-skeleton.sh --update"
    exit 1
fi
info "Example in sync with templates"

# Build Go code
info "Building Go code..."

pushd "$EXAMPLE_DIR" > /dev/null

# Sync go.work first
if ! go work sync 2>&1; then
    warn "go work sync had warnings (may need network)"
fi

# Try to build all modules in the workspace
# Build each module explicitly since go.work doesn't have root go.mod
BUILD_OUTPUT=""
for mod_dir in pkg services/example-api workers/example-worker cli/example-cli; do
    if [ -d "$mod_dir" ]; then
        MOD_OUTPUT=$(cd "$mod_dir" && go build ./... 2>&1 || true)
        if [ -n "$MOD_OUTPUT" ]; then
            BUILD_OUTPUT="${BUILD_OUTPUT}${MOD_OUTPUT}\n"
        fi
    fi
done
if [ -n "$BUILD_OUTPUT" ]; then
    warn "Go build has errors:"
    echo "$BUILD_OUTPUT" | head -30
    echo ""
    echo "These are likely template bugs that need fixing."
    # Don't exit - continue to show all issues
else
    info "Go builds successfully"
fi

popd > /dev/null

# TypeScript type check (unless --quick)
if [ "$QUICK_MODE" = false ]; then
    info "Installing TypeScript dependencies..."
    pushd "$EXAMPLE_DIR" > /dev/null

    if command -v pnpm &> /dev/null; then
        if ! pnpm install --prefer-offline 2>&1 | tail -5; then
            warn "pnpm install had issues"
        fi

        info "Running TypeScript type check..."
        if ! pnpm -r typecheck 2>&1; then
            warn "TypeScript type check failed"
        else
            info "TypeScript types check"
        fi
    else
        warn "pnpm not found, skipping TypeScript checks"
    fi

    popd > /dev/null
fi

# Summary
echo ""
if [ -z "$BUILD_OUTPUT" ]; then
    info "All skeleton verification passed!"
else
    warn "Skeleton rendered but has build errors - templates need fixes"
    exit 1
fi
