#!/bin/bash
# Start script for Cat-Knows
# Starts Nim server and Tauri app, cleans up on exit

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"

# =========================================================
# Apply pending update (staged by in-app update)
# =========================================================
if [ -f "tmp/pending_update.json" ]; then
    echo "=== Pending update found ==="

    # Read version from marker
    UPDATE_VERSION=$(grep -o '"version"[[:space:]]*:[[:space:]]*"[^"]*"' tmp/pending_update.json | head -1 | sed 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/')
    echo "Applying update v${UPDATE_VERSION}..."

    if [ -d "tmp/pending_update" ]; then
        # Copy files, skipping protected paths
        cd tmp/pending_update
        find . -type f | while read -r file; do
            # Strip leading ./
            rel="${file#./}"

            # Skip protected files and active launcher scripts
            case "$rel" in
                catknows.db|catknows.db-shm|catknows.db-wal|config.ini|credentials.enc)
                    echo "  [SKIP] $rel (protected file)"
                    continue
                    ;;
                start.sh|start.bat)
                    echo "  [DEFER] $rel (active launcher - updated after copy)"
                    continue
                    ;;
                cache/*|tmp/*)
                    echo "  [SKIP] $rel (protected dir)"
                    continue
                    ;;
            esac

            # Create parent directory if needed
            dest_dir="$(dirname "$SCRIPT_DIR/$rel")"
            mkdir -p "$dest_dir"

            # Copy file
            cp -f "$file" "$SCRIPT_DIR/$rel"
            echo "  [COPY] $rel"
        done
        cd "$SCRIPT_DIR"

        # Update version in config.ini if we have a version
        if [ -n "$UPDATE_VERSION" ] && [ -f "config.ini" ]; then
            # Replace version line in [launcher] section
            sed -i "/^\[launcher\]/,/^\[/ s/^version\b.*/version = \"${UPDATE_VERSION}\"/" config.ini
            echo "Updated version to ${UPDATE_VERSION} in config.ini"
        fi

        # Update launcher scripts atomically (mv = new inode, safe for running script)
        if [ -f "tmp/pending_update/start.sh" ]; then
            cp -f "tmp/pending_update/start.sh" "start.sh.tmp"
            mv -f "start.sh.tmp" "start.sh"
            chmod +x "start.sh"
            echo "  [COPY] start.sh (launcher updated atomically)"
        fi
        if [ -f "tmp/pending_update/start.bat" ]; then
            cp -f "tmp/pending_update/start.bat" "start.bat"
            echo "  [COPY] start.bat"
        fi

        # Cleanup staging directory and marker
        rm -rf tmp/pending_update
        rm -f tmp/pending_update.json
        echo "=== Update v${UPDATE_VERSION} applied successfully ==="
    else
        echo "WARNING: Marker exists but tmp/pending_update/ directory missing. Removing stale marker."
        rm -f tmp/pending_update.json
    fi

    echo ""
fi

# =========================================================
# Cleanup function
# =========================================================
cleanup() {
    echo "Shutting down..."
    if [ -n "$SERVER_PID" ] && kill -0 "$SERVER_PID" 2>/dev/null; then
        kill "$SERVER_PID" 2>/dev/null
        echo "Server stopped"
    fi
    exit 0
}

trap cleanup EXIT INT TERM

# Start desktop app (server + webview in one process)
echo "Starting Cat-Knows..."
./server --base-dir "$SCRIPT_DIR"

# Cleanup happens via trap
