#!/bin/bash
set -e

# Configuration - Paths relative to project root
POC_REPO_PATH="../client-krow-poc"
WEB_POC_SOURCE="$POC_REPO_PATH/prototypes/web/krow_web_application"
WEB_DEST="internal/launchpad/prototypes/web"

MOBILE_CLIENT_SOURCE="$POC_REPO_PATH/prototypes/mobile/client/client_mobile_application"
MOBILE_CLIENT_DEST="internal/launchpad/prototypes/mobile/client"
MOBILE_CLIENT_HREF="/prototypes/mobile/client/"

MOBILE_STAFF_SOURCE="$POC_REPO_PATH/prototypes/mobile/staff/staff_mobile_application"
MOBILE_STAFF_DEST="internal/launchpad/prototypes/mobile/staff"
MOBILE_STAFF_HREF="/prototypes/mobile/staff/"

# Source code destinations (for AI/Claude context)
WEB_SRC_DEST="internal/launchpad/prototypes-src/web"
MOBILE_CLIENT_SRC_DEST="internal/launchpad/prototypes-src/mobile/client"
MOBILE_STAFF_SRC_DEST="internal/launchpad/prototypes-src/mobile/staff"

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m' # No Color

echo -e "${BLUE}🚀 Starting Prototypes Synchronization...${NC}"

# Check if POC repo exists
if [ ! -d "$POC_REPO_PATH" ]; then
    echo -e "${RED}❌ Error: POC repository not found at $POC_REPO_PATH${NC}"
    echo "Please clone the repository adjacent to this one:"
    echo "  cd .. && git clone git@github.com:Oloodi/client-krow-poc.git"
    exit 1
fi

# --- Sync Web Dashboard ---
echo -e "${BLUE}📦 Building Web Dashboard Prototype...${NC}"
if [ -d "$WEB_POC_SOURCE" ]; then
    cd "$WEB_POC_SOURCE"
    
    echo "  -> Installing dependencies..."
    pnpm install --silent
    
    # Temporarily patch vite.config to enforce relative base path
    # This is necessary because command line args --base=./ might be ignored by some npm scripts
    CONFIG_FILE=""
    if [ -f "vite.config.ts" ]; then CONFIG_FILE="vite.config.ts"; fi
    if [ -f "vite.config.js" ]; then CONFIG_FILE="vite.config.js"; fi
    
    if [ -n "$CONFIG_FILE" ]; then
        echo "  -> Patching $CONFIG_FILE for relative paths..."
        cp "$CONFIG_FILE" "$CONFIG_FILE.bak"
        # Insert base: './', inside defineConfig({ or export default {
        if [[ "$OSTYPE" == "darwin"* ]]; then
            sed -i '' 's/defineConfig({/defineConfig({ base: "\.\/",/g' "$CONFIG_FILE" || sed -i '' 's/export default {/export default { base: "\.\/",/g' "$CONFIG_FILE"
        else
            sed -i 's/defineConfig({/defineConfig({ base: "\.\/",/g' "$CONFIG_FILE" || sed -i 's/export default {/export default { base: "\.\/",/g' "$CONFIG_FILE"
        fi
    else
        echo -e "${RED}⚠️  Warning: No vite.config.js/ts found. Build might fail to use relative paths.${NC}"
    fi

    echo "  -> Building dist..."
    pnpm run build
    
    # Restore original config
    if [ -n "$CONFIG_FILE" ]; then
        mv "$CONFIG_FILE.bak" "$CONFIG_FILE"
    fi
    
    # Go back to project root
    cd - > /dev/null
    
    echo "  -> Deploying to Launchpad..."
    # Ensure destination exists and is clean (remove old files but keep .keep if needed, though usually we wipe for a clean build)
    rm -rf "$WEB_DEST"/*
    mkdir -p "$WEB_DEST"
    
    # Copy build artifacts
    cp -R "$WEB_POC_SOURCE/dist/"* "$WEB_DEST/"
    
    echo -e "${GREEN}✅ Web Dashboard synced successfully.${NC}"

    # Copy source code for AI context
    echo "  -> Copying source code for AI context..."
    rm -rf "$WEB_SRC_DEST"
    mkdir -p "$WEB_SRC_DEST"
    cp -R "$WEB_POC_SOURCE/src" "$WEB_SRC_DEST/"
    [ -f "$WEB_POC_SOURCE/package.json" ] && cp "$WEB_POC_SOURCE/package.json" "$WEB_SRC_DEST/"
    [ -f "$WEB_POC_SOURCE/tsconfig.json" ] && cp "$WEB_POC_SOURCE/tsconfig.json" "$WEB_SRC_DEST/"
    [ -f "$WEB_POC_SOURCE/vite.config.ts" ] && cp "$WEB_POC_SOURCE/vite.config.ts" "$WEB_SRC_DEST/"
    echo -e "${GREEN}✅ Web source code copied.${NC}"
else
    echo -e "${RED}⚠️  Warning: Web POC source directory not found at $WEB_POC_SOURCE${NC}"
fi

# --- Determine Flutter Command ---

# Helper: Add FVM default to PATH if it exists (fixes Make environment missing user PATH)
if [ -d "$HOME/fvm/default/bin" ]; then
    export PATH="$HOME/fvm/default/bin:$PATH"
fi

if command -v flutter &> /dev/null; then
    FLUTTER_CMD="flutter"
    echo -e "${BLUE}ℹ️  Using Flutter: $(which flutter)${NC}"
elif command -v fvm &> /dev/null; then
    FLUTTER_CMD="fvm flutter"
    echo -e "${BLUE}ℹ️  Using FVM: $FLUTTER_CMD${NC}"
else
    echo -e "${RED}❌ Error: 'flutter' command not found. Please ensure Flutter is in your PATH or FVM is configured.${NC}"
    # Try to provide a helpful hint based on user environment
    if [ -d "$HOME/fvm/versions" ]; then
        echo -e "${BLUE}💡 Hint: You seem to have FVM versions. Try running 'fvm global <version>' to set a default.${NC}"
    fi
    exit 1
fi

# --- Sync Mobile Client (Flutter) ---
echo -e "${BLUE}📱 Building Mobile Client Prototype (Flutter)...${NC}"

if [ -d "$MOBILE_CLIENT_SOURCE" ]; then
    cd "$MOBILE_CLIENT_SOURCE"
    
    echo "  -> Getting packages..."
    $FLUTTER_CMD pub get
    
    echo "  -> Building web bundle (base-href: $MOBILE_CLIENT_HREF)..."
    $FLUTTER_CMD build web --base-href "$MOBILE_CLIENT_HREF" --release
    
    cd - > /dev/null
    
    echo "  -> Deploying to Launchpad..."
    rm -rf "$MOBILE_CLIENT_DEST"/*
    mkdir -p "$MOBILE_CLIENT_DEST"
    cp -R "$MOBILE_CLIENT_SOURCE/build/web/"* "$MOBILE_CLIENT_DEST/"
    
    echo -e "${GREEN}✅ Mobile Client synced successfully.${NC}"

    # Copy source code for AI context
    echo "  -> Copying source code for AI context..."
    rm -rf "$MOBILE_CLIENT_SRC_DEST"
    mkdir -p "$MOBILE_CLIENT_SRC_DEST"
    cp -R "$MOBILE_CLIENT_SOURCE/lib" "$MOBILE_CLIENT_SRC_DEST/"
    [ -f "$MOBILE_CLIENT_SOURCE/pubspec.yaml" ] && cp "$MOBILE_CLIENT_SOURCE/pubspec.yaml" "$MOBILE_CLIENT_SRC_DEST/"
    echo -e "${GREEN}✅ Mobile Client source code copied.${NC}"
else
    echo -e "${RED}⚠️  Warning: Mobile Client source not found at $MOBILE_CLIENT_SOURCE${NC}"
fi

# --- Sync Mobile Staff (Flutter) ---
echo -e "${BLUE}🍳 Building Mobile Staff Prototype (Flutter)...${NC}"
if [ -d "$MOBILE_STAFF_SOURCE" ]; then
    cd "$MOBILE_STAFF_SOURCE"
    
    echo "  -> Getting packages..."
    $FLUTTER_CMD pub get
    
    echo "  -> Building web bundle (base-href: $MOBILE_STAFF_HREF)..."
    $FLUTTER_CMD build web --base-href "$MOBILE_STAFF_HREF" --release
    
    cd - > /dev/null
    
    echo "  -> Deploying to Launchpad..."
    rm -rf "$MOBILE_STAFF_DEST"/*
    mkdir -p "$MOBILE_STAFF_DEST"
    cp -R "$MOBILE_STAFF_SOURCE/build/web/"* "$MOBILE_STAFF_DEST/"
    
    echo -e "${GREEN}✅ Mobile Staff synced successfully.${NC}"

    # Copy source code for AI context
    echo "  -> Copying source code for AI context..."
    rm -rf "$MOBILE_STAFF_SRC_DEST"
    mkdir -p "$MOBILE_STAFF_SRC_DEST"
    cp -R "$MOBILE_STAFF_SOURCE/lib" "$MOBILE_STAFF_SRC_DEST/"
    [ -f "$MOBILE_STAFF_SOURCE/pubspec.yaml" ] && cp "$MOBILE_STAFF_SOURCE/pubspec.yaml" "$MOBILE_STAFF_SRC_DEST/"
    echo -e "${GREEN}✅ Mobile Staff source code copied.${NC}"
else
    echo -e "${RED}⚠️  Warning: Mobile Staff source not found at $MOBILE_STAFF_SOURCE${NC}"
fi

echo -e "${GREEN}🎉 Synchronization complete!${NC}"
echo "You can now verify the prototypes in internal/launchpad/prototypes/ and commit the changes."
