#!/bin/bash

set -e

GREEN='\033[0;32m'
RED='\033[0;31m'
BOLD='\033[1m'
NC='\033[0m'

EXTENSION_NAME="tile-props"
SOURCE_DIR="$(cd "$(dirname "$0")" && pwd)/$EXTENSION_NAME"
ZIP_FILE="$(cd "$(dirname "$0")" && pwd)/${EXTENSION_NAME}.aseprite-extension"

print_error() {
    echo -e "${RED}${BOLD}[$(timestamp) ERROR]${NC} $1" >&2
}

print_info() {
    echo -e "${GREEN}${BOLD}[$(timestamp) INFO]${NC} $1"
}

print_usage() {
    echo -e "${BOLD}pxl8-ase${NC} - aseprite tools"
    echo
    echo -e "${BOLD}COMMANDS:${NC}"
    echo "    clean        Remove packaged extension"
    echo "    help         Show this help message"
    echo "    package      Package extension for installation"
}

timestamp() {
    date +"%H:%M:%S"
}

COMMAND="$1"
shift || true

case "$COMMAND" in
    package)
        print_info "Creating extension package: ${EXTENSION_NAME}.aseprite-extension"
        cd "$(dirname "$SOURCE_DIR")"
        rm -f "$ZIP_FILE"
        zip -q -r "$ZIP_FILE" "$EXTENSION_NAME"
        print_info "Extension package created: $ZIP_FILE"
        echo ""
        echo "To install in Aseprite:"
        echo "1. Open Aseprite"
        echo "2. Go to Edit → Preferences → Extensions"
        echo "3. Click 'Add Extension'"
        echo "4. Select: $ZIP_FILE"
        echo "5. Restart Aseprite"
        ;;

    clean)
        if [[ -f "$ZIP_FILE" ]]; then
            print_info "Removing extension package"
            rm -f "$ZIP_FILE"
            print_info "Cleaned"
        else
            print_info "No extension package to remove"
        fi
        ;;

    help|--help|-h|"")
        print_usage
        ;;

    *)
        print_error "Unknown command: $COMMAND"
        print_usage
        exit 1
        ;;
esac
