#!/bin/bash

echo "🚀 Starting build..."

SOURCE=${BASH_SOURCE[0]}
DIR_OF_THIS_SCRIPT="$( dirname "$SOURCE" )"
ABS_DIR_OF_SCRIPT="$( realpath "$DIR_OF_THIS_SCRIPT" )"

# Detect platform for Tailwind binary
ASSET="tailwindcss"
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
    ASSET="$ASSET-linux"
elif [[ "$OSTYPE" == "darwin"* ]]; then
    ASSET="$ASSET-macos"
fi

if [[ "$(uname -m)" == "x86_64"* ]]; then
    ASSET="$ASSET-x64"
elif [[ "$(uname -m)" == "arm64"* ]]; then
    ASSET="$ASSET-arm64"
fi

# Get latest Tailwind version from GitHub
LATEST_VERSION=$(curl -s https://api.github.com/repos/tailwindlabs/tailwindcss/releases/latest | grep '"tag_name":' | cut -d '"' -f 4)

# Check current version
CURRENT_VERSION=""
if [[ -f "./tailwindcss" ]]; then
    CURRENT_VERSION=$(./tailwindcss -v | awk '{print $2}')
fi

echo "Current Tailwind version: $CURRENT_VERSION"
echo "Latest Tailwind version: $LATEST_VERSION"

# Download Tailwind binary if needed
if [[ "$CURRENT_VERSION" != "$LATEST_VERSION" ]]; then
    echo "⬇️ Downloading latest Tailwind..."
    rm -f tailwindcss
    curl -sLO "https://github.com/tailwindlabs/tailwindcss/releases/download/${LATEST_VERSION}/${ASSET}"
    chmod +x $ASSET
    mv $ASSET tailwindcss
else
    echo "✅ Tailwind is up to date."
fi

# Initialize Tailwind config if needed
if [[ ! -f "tailwind.config.js" ]]; then
    echo "🛠 Initializing Tailwind config..."
    ./tailwindcss init
    sed -i.bak "s|  content: \[\],|  content: \['./templates/**/*.html'\],|g" tailwind.config.js
fi

# Ensure static/css exists
mkdir -p static/css

# Clean previous build
rm -rf public

# Compile Tailwind
echo "🧵 Building Tailwind CSS..."

./tailwindcss -i css/index.css -o static/css/index.css --minify

# Build Zola site
echo "🏗 Running Zola..."
zola --root "$ABS_DIR_OF_SCRIPT" build

# Ensure CSS is in the public directory
echo "📋 Ensuring CSS is in public directory..."
mkdir -p public/css
cp static/css/index.css public/css/

echo "✅ Build complete. Check public/ folder."
