#!/bin/bash

# Parse command-line arguments
while [[ $# -gt 0 ]]; do
  case $1 in
    -e|--extensions)
      EXTENSIONS="$2"
      shift; shift
      ;;
    -d|--directory)
      DIRECTORY="$2"
      shift; shift
      ;;
    -o|--output-dir)
      OUTPUT_DIR="$2"
      shift; shift
      ;;
    *)
      echo "Unknown argument: $1"
      exit 1
      ;;
  esac
done

# Get the directory where this script is located
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo "Script directory: $SCRIPT_DIR"

OS=$(uname -s)
ARCH=$(uname -m)

# Normalize OS and ARCH identifiers
case $OS in
  "Darwin")
    OS="macos"
    ;;
  "Linux")
    OS="linux"
    ;;
  "CYGWIN"*|"MINGW"*|"MSYS"*)
    OS="windows"
    ;;
  *)
    echo "Unknown operating system: $OS"
    exit 1
    ;;
esac

case $ARCH in
  "x86_64")
    ARCH="x64"
    ;;
  "arm64"|"aarch64")
    ARCH="arm64"
    ;;
  *)
    echo "Unsupported architecture: $ARCH"
    exit 1
    ;;
esac

echo "Detected OS: $OS"
echo "Detected Architecture: $ARCH"

# Use tw directory in script location
BINARY="${SCRIPT_DIR}/tw/${OS}-${ARCH}"
if [ "$OS" = "windows" ]; then
  BINARY="${BINARY}.exe"
fi

echo "Looking for binary at: $BINARY"

# Check if binary exists
if [ ! -f "$BINARY" ]; then
    echo "Binary not found: $BINARY"
    echo "Contents of ${SCRIPT_DIR}/tw/:"
    ls -la "${SCRIPT_DIR}/tw/"
    exit 1
fi

# Make binary executable
chmod +x "$BINARY"

echo "Using binary: $BINARY"
echo "Extensions: $EXTENSIONS"
echo "Directory: $DIRECTORY"
echo "Output Directory: $OUTPUT_DIR"

# Initialize an array for name conditions
name_conditions=()

# Assuming $EXTENSIONS is a comma-separated list of extensions
IFS=',' read -ra ADDR <<< "$EXTENSIONS"
for ext in "${ADDR[@]}"; do
    name_conditions+=(-name "*.$ext")
done

# Use find with the array of conditions
INCLUDE_FILES=$(find "$DIRECTORY" -type f \( "${name_conditions[@]}" \))

echo "Files found: $INCLUDE_FILES"

INCLUDE_FILES_ARRAY=$(echo "$INCLUDE_FILES" | awk '{printf "\"%s\",", $0}' | sed 's/,$//')

# Generate Tailwind config in script directory
CONFIG_FILE="${SCRIPT_DIR}/tailwind.config.js"
echo "module.exports = {
  content: [$INCLUDE_FILES_ARRAY],
  theme: {
    extend: {},
  },
  daisyui: {
    themes: [\"night\"],
  },
  plugins: [require('daisyui'), require('@tailwindcss/typography')],
}" > "$CONFIG_FILE"

# Run the binary with the generated config
"$BINARY" build -i "${SCRIPT_DIR}/base.css" -c "$CONFIG_FILE" -o "${OUTPUT_DIR}/styles.css" --minify

# Wait for all background processes to finish
wait
