#!/bin/bash

set -e
set -o pipefail

UPDATE=false

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --update)
            UPDATE=true
            shift
            ;;
        -h|--help)
            echo "Usage: $0 <app_name> [--update]"
            echo ""
            echo "Fetch an app template from the Wild Cloud repository to cache."
            echo ""
            echo "Options:"
            echo "  --update    Overwrite existing cached files without confirmation"
            echo "  -h, --help  Show this help message"
            exit 0
            ;;
        -*)
            echo "Unknown option $1"
            echo "Usage: $0 <app_name> [--update]"
            exit 1
            ;;
        *)
            if [ -z "${APP_NAME}" ]; then
                APP_NAME="$1"
            else
                echo "Too many arguments"
                echo "Usage: $0 <app_name> [--update]"
                exit 1
            fi
            shift
            ;;
    esac
done

if [ -z "${APP_NAME}" ]; then
    echo "Usage: $0 <app_name> [--update]"
    exit 1
fi

# Initialize Wild Cloud environment
if [ -z "${WC_ROOT}" ]; then
    echo "WC_ROOT is not set."
    exit 1
else
    source "${WC_ROOT}/scripts/common.sh"
    init_wild_env
fi

SOURCE_APP_DIR="${WC_ROOT}/apps/${APP_NAME}"
if [ ! -d "${SOURCE_APP_DIR}" ]; then
    echo "Error: App '${APP_NAME}' not found at ${SOURCE_APP_DIR}"
    exit 1
fi

CACHE_APP_DIR=".wildcloud/cache/apps/${APP_NAME}"
mkdir -p ".wildcloud/cache/apps"

if [ -d "${CACHE_APP_DIR}" ]; then
    if [ "${UPDATE}" = true ]; then
        echo "Updating cached app '${APP_NAME}'"
        rm -rf "${CACHE_APP_DIR}"
    else
        echo "Warning: Cache directory ${CACHE_APP_DIR} already exists"
        read -p "Do you want to overwrite it? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            echo "Fetch cancelled"
            exit 1
        fi
        rm -rf "${CACHE_APP_DIR}"
    fi
fi

echo "Fetching app '${APP_NAME}' from ${SOURCE_APP_DIR} to ${CACHE_APP_DIR}"

# Create destination directory
mkdir -p "${CACHE_APP_DIR}"

# Copy directory structure and files (no template processing)
find "${SOURCE_APP_DIR}" -type d | while read -r src_dir; do
    rel_path="${src_dir#${SOURCE_APP_DIR}}"
    rel_path="${rel_path#/}"  # Remove leading slash if present
    if [ -n "${rel_path}" ]; then
        mkdir -p "${CACHE_APP_DIR}/${rel_path}"
    fi
done

find "${SOURCE_APP_DIR}" -type f | while read -r src_file; do
    rel_path="${src_file#${SOURCE_APP_DIR}}"
    rel_path="${rel_path#/}"  # Remove leading slash if present
    dest_file="${CACHE_APP_DIR}/${rel_path}"
    
    # Ensure destination directory exists
    dest_dir=$(dirname "${dest_file}")
    mkdir -p "${dest_dir}"
    
    # Simple copy without template processing
    cp "${src_file}" "${dest_file}"
done

echo "Successfully fetched app '${APP_NAME}' to cache"