#!/bin/bash

# Script to build the Angular application and prepare files for implementation
# Created: 2025-07-22

# Exit on error
set -e

echo "=== Angular Build Script ==="
echo "This script builds the Angular application and prepares files for implementation"

# Check Node.js version
NODE_VERSION=$(node -v | cut -d 'v' -f 2)
NODE_MAJOR_VERSION=$(echo $NODE_VERSION | cut -d '.' -f 1)
NODE_MINOR_VERSION=$(echo $NODE_VERSION | cut -d '.' -f 2)

echo "Detected Node.js version: v$NODE_VERSION"

# Check if Node.js version is compatible (v20.19+ or v22.12+)
if [[ ($NODE_MAJOR_VERSION -eq 20 && $NODE_MINOR_VERSION -ge 19) || ($NODE_MAJOR_VERSION -ge 22 && $NODE_MINOR_VERSION -ge 12) || ($NODE_MAJOR_VERSION -gt 22) ]]; then
    echo "Node.js version is compatible."
else
    echo "Error: Angular CLI requires Node.js version v20.19+ or v22.12+"
    echo "Please update your Node.js version or visit https://nodejs.org/ for additional instructions."
    exit 1
fi

# Build the Angular application
echo "Building Angular application..."
npm run build

# Check if build was successful
if [ $? -ne 0 ]; then
    echo "Error: Angular build failed."
    exit 1
fi

# Define paths
DIST_DIR="dist/my-app/browser"
IMPLEMENTATION_ASSETS_DIR="implementation/assets"

# Create implementation assets directory if it doesn't exist
mkdir -p "$IMPLEMENTATION_ASSETS_DIR"

# Find the CSS and JS files
CSS_FILE=$(find "$DIST_DIR" -name "styles-*.css" | head -n 1)
MAIN_JS_FILE=$(find "$DIST_DIR" -name "main-*.js" | head -n 1)
POLYFILLS_JS_FILE=$(find "$DIST_DIR" -name "polyfills-*.js" | head -n 1)

# Check if files exist
if [ -z "$CSS_FILE" ]; then
    echo "Error: Could not find styles CSS file in $DIST_DIR"
    exit 1
fi

if [ -z "$MAIN_JS_FILE" ]; then
    echo "Error: Could not find main JS file in $DIST_DIR"
    exit 1
fi

# Copy and rename CSS file
echo "Copying CSS file to implementation assets..."
cp "$CSS_FILE" "$IMPLEMENTATION_ASSETS_DIR/design-system.css"

# Combine JS files if polyfills exist, otherwise just use main JS
if [ -n "$POLYFILLS_JS_FILE" ]; then
    echo "Combining main and polyfills JS files..."
    cat "$MAIN_JS_FILE" "$POLYFILLS_JS_FILE" > "$IMPLEMENTATION_ASSETS_DIR/design-system.js"
else
    echo "Copying main JS file to implementation assets..."
    cp "$MAIN_JS_FILE" "$IMPLEMENTATION_ASSETS_DIR/design-system.js"
fi

echo "Build completed successfully!"
echo "Files have been copied to $IMPLEMENTATION_ASSETS_DIR:"
echo "- design-system.css"
echo "- design-system.js"

# Show file sizes
echo "File sizes:"
ls -lh "$IMPLEMENTATION_ASSETS_DIR/design-system.css" | awk '{print "- CSS: " $5}'
ls -lh "$IMPLEMENTATION_ASSETS_DIR/design-system.js" | awk '{print "- JS: " $5}'

echo "=== Done ==="
