#!/bin/bash

# Shopify Theme CLI - Local Development Script
# ------------------------------------------
# This script runs the theme CLI locally for development without needing to publish to npm

# Colors for terminal output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Configuration
CLI_ENTRY_POINT="./dist/index.js"
THEME_DIR="my-shop-theme"
SERVER_PORT="3000"
THEME_NAME="Development Theme"

# Parse command line arguments
while [[ $# -gt 0 ]]; do
  case $1 in
    --port)
      SERVER_PORT="$2"
      shift 2
      ;;
    --theme-dir)
      THEME_DIR="$2"
      shift 2
      ;;
    --theme-name)
      THEME_NAME="$2"
      shift 2
      ;;
    *)
      # Store other arguments to pass through
      EXTRA_ARGS="$EXTRA_ARGS $1"
      shift
      ;;
  esac
done

# Load environment variables
if [ ! -f .env ]; then
  echo -e "${YELLOW}⚠️  No .env file found. Creating one from template...${NC}"
  cp .env.example .env || touch .env
fi

source .env

# Debug: Print loaded environment variables (redacting sensitive values)
echo -e "${BLUE}Loaded environment variables:${NC}"
echo "SHOPIFY_STORE=$SHOPIFY_STORE"
echo "SHOPIFY_API_KEY=${SHOPIFY_API_KEY:0:8}..."
echo "SHOPIFY_PASSWORD=${SHOPIFY_PASSWORD:0:8}..."

# Validate environment
if [ ! -f "package.json" ]; then
  echo -e "${RED}Error: Must be run from the root of the theme-cli project${NC}"
  exit 1
fi

# Function to show credential help
show_credential_help() {
  echo -e "\n${YELLOW}Credential Help:${NC}"
  echo "1. Go to your Shopify Admin > Apps > Develop apps"
  echo "2. Create a new app or select an existing one"
  echo "3. Under 'API credentials', ensure you have:"
  echo "   - Admin API access token (starts with shpat_)"
  echo "   - Required scopes: write_themes, read_themes"
  echo "4. Add these to your .env file:"
  echo "   SHOPIFY_STORE=your-store-name"
  echo "   SHOPIFY_API_KEY=your-api-key"
  echo "   SHOPIFY_PASSWORD=your-access-token"
}

# Build the project
echo -e "${BLUE}Building project...${NC}"
npm run build

if [ $? -ne 0 ]; then
  echo -e "${RED}Build failed. Please fix the errors and try again.${NC}"
  exit 1
fi

echo -e "${GREEN}✓ Build successful${NC}"

# Test API connection
echo -e "\n${BLUE}Testing Shopify API connection...${NC}"
SHOPIFY_STORE="$SHOPIFY_STORE" SHOPIFY_API_KEY="$SHOPIFY_API_KEY" SHOPIFY_PASSWORD="$SHOPIFY_PASSWORD" node "$CLI_ENTRY_POINT" shopify theme test-connection

if [ $? -ne 0 ]; then
  echo -e "${RED}API connection test failed.${NC}"
  show_credential_help
  
  echo -e "\n${YELLOW}Do you want to continue anyway? (y/n)${NC} "
  read -r CONTINUE
  if [[ ! "$CONTINUE" =~ ^[Yy]$ ]]; then
    echo -e "Exiting."
    exit 1
  fi
  echo -e "${YELLOW}Continuing with potentially invalid credentials...${NC}"
else
  echo -e "${GREEN}✓ API connection successful${NC}"
fi

# Step 1: Initialize the theme using node directly (ES module compatible)
echo -e "\n${BLUE}Step 1: Initializing new Shopify theme...${NC}"
node "$CLI_ENTRY_POINT" shopify theme init --name "$THEME_DIR" --force

# Check if theme initialization was successful
if [ $? -ne 0 ]; then
  echo -e "${YELLOW}⚠️  Theme initialization failed. Exiting.${NC}"
  exit 1
fi

echo -e "${GREEN}✓ Theme initialized successfully in ./$THEME_DIR${NC}"

# Step 2: Start the development server
echo -e "\n${BLUE}Step 2: Starting development server...${NC}"
echo -e "Using Shopify store: ${SHOPIFY_STORE}.myshopify.com"

# Build the command based on whether a theme ID was provided
DEV_COMMAND="node \"$CLI_ENTRY_POINT\" shopify theme dev --store \"$SHOPIFY_STORE\" --api-key \"$SHOPIFY_API_KEY\" --password \"$SHOPIFY_PASSWORD\" --theme-dir \"./$THEME_DIR\" --port \"$SERVER_PORT\""

if [ ! -z "$SHOPIFY_THEME_ID" ]; then
  echo -e "Using existing theme ID: ${SHOPIFY_THEME_ID}"
  DEV_COMMAND="$DEV_COMMAND --theme-id \"$SHOPIFY_THEME_ID\""
else
  echo -e "No theme ID provided. A new development theme named \"$THEME_NAME\" will be created automatically."
  DEV_COMMAND="$DEV_COMMAND --theme-name \"$THEME_NAME\""
fi

# Add any extra arguments
if [ ! -z "$EXTRA_ARGS" ]; then
  DEV_COMMAND="$DEV_COMMAND $EXTRA_ARGS"
fi

echo -e "\n${BLUE}Starting development server...${NC}"
echo -e "This will connect to your Shopify store and either:"
echo -e "1. Use the existing theme if you provided a theme ID, or"
echo -e "2. Create a new development theme in your Shopify admin"
echo -e "\nThe server will provide a local preview interface at http://localhost:${SERVER_PORT}"

# Run the command
eval $DEV_COMMAND

# Capture exit code to check for errors
DEV_EXIT_CODE=$?

if [ $DEV_EXIT_CODE -ne 0 ]; then
  echo -e "${RED}Development server failed to start properly.${NC}"
  if [[ -z "$SHOPIFY_THEME_ID" ]]; then
    echo -e "\n${YELLOW}Fallback option: Try using an existing theme ID${NC}"
    echo -e "1. Go to your Shopify Admin > Online Store > Themes"
    echo -e "2. Find the theme ID in the URL when you edit a theme"
    echo -e "3. Add SHOPIFY_THEME_ID=your_theme_id to your .env file"
  fi
  show_credential_help
fi

# Script will end when dev server is stopped 