#!/usr/bin/env bash
# ==============================================================================
# jpman — Zero-dependency CLI for jupyter-podman-rootless container management
#
# Quick start:
#   # From WSL (after running: bash bin/jpman install):
#   jpman start && jpman info
#
# Usage (WSL/Linux) — from project root:
#   bash bin/jpman <command>
#   # Or after 'jpman install', from anywhere:
#   jpman <command>
#
# Usage (Windows PowerShell/cmd) — from project root:
#   bin\jpman.cmd <command>
#   # PowerShell 7+ native version:
#   pwsh -File bin/jpman.ps1 <command>
#
# Commands:
#   start       Start container (idempotent; creates if not exists)
#               -w, --workspace PATH  Mount host PATH to /workspace in container
#   stop        Stop and remove container
#   restart     Stop then start
#   status      Show container status
#   shell       Enter container shell (devuser by default, --root for root)
#   logs        View container logs (-f for follow)
#   exec CMD    Execute command in container (devuser)
#   root CMD    Execute command in container (root)
#   info        Show access info (URL, credentials, ports)
#   url         Print Jupyter Lab URL (for quick copy-paste)
#   save        Save image to .image-cache/ for backup
#   load        Load image from .image-cache/
#   rebuild     Incremental rebuild (config changes only, <10s)
#   rebuild-all Full rebuild from Containerfile (slow, needs network)
#   wsl-export  Export image cache as WSL2 distro (one-click convert)
#   wsl-verify  Verify WSL2 distro environment (Smoke Test)
#   keepalive   Start WSL keepalive process (prevents container auto-exit)
#   install     Install symlink to ~/.local/bin/jpman for global WSL access
#   help        Show this help message
#
# All defaults can be overridden via environment variables or a .env file
# in the project root. Key variables:
#   WORKSPACE           Host directory to mount to /workspace (default: <project>/workspace)
#                       Relative paths in env var resolve against current directory;
#                       -w/--workspace resolves relative paths against current directory.
#   JUPYTER_WORKSPACE   Fallback for WORKSPACE (backward compatibility)
#   JUPYTER_CONTAINER_NAME, JUPYTER_IMAGE, JUPYTER_SSH_PORT, JUPYTER_PORT,
#   JUPYTER_PASSWORD, JUPYTER_TOKEN, etc. (see source for full list)
# ==============================================================================
set -euo pipefail

# ---------------------------------------------------------------------------
# Auto-locate project root (script lives in <project>/bin/jpman)
# ---------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# ---------------------------------------------------------------------------
# Path conversion helper: Windows path -> WSL path
#   D:\foo\bar  -> /mnt/d/foo/bar
#   D:/foo/bar  -> /mnt/d/foo/bar
#   /mnt/d/...  -> returned as-is (already WSL)
#   ./foo, ~/foo, /absolute -> returned as-is
# ---------------------------------------------------------------------------
_win_to_wsl_path() {
    local p="$1"
    # Already a WSL/Linux path (starts with / or ./ or ~/ or relative without drive letter)
    if [[ "$p" == /* ]] || [[ "$p" == ./* ]] || [[ "$p" == ~/* ]] || [[ "$p" == "" ]]; then
        echo "$p"
        return
    fi
    # Match Windows drive letter: C:\..., D:/..., etc.
    if [[ "$p" =~ ^([A-Za-z]):[\\/](.*)$ ]]; then
        local drive="${BASH_REMATCH[1],,}"  # lowercase
        local rest="${BASH_REMATCH[2]}"
        rest="${rest//\\//}"  # backslashes -> forward slashes
        echo "/mnt/$drive/$rest"
        return
    fi
    # Broken path from bash source (backslashes eaten): D:spacesSpecWeave -> can't auto-fix
    # Return as-is; caller will handle
    echo "$p"
}

# ---------------------------------------------------------------------------
# Load .env file safely — parses KEY=VALUE line by line without shell interpretation,
# so Windows paths with backslashes (D:\foo\bar) are preserved correctly.
# Also strips CRLF and auto-converts Windows paths (WORKSPACE) to WSL paths.
# ---------------------------------------------------------------------------
load_env() {
    local env_files=("$PROJECT_ROOT/.env" "$PWD/.env")
    for f in "${env_files[@]}"; do
        if [[ -f "$f" ]]; then
            while IFS= read -r line || [[ -n "$line" ]]; do
                # Strip CR and leading/trailing whitespace
                line="${line//$'\r'/}"
                line="${line#"${line%%[![:space:]]*}"}"
                line="${line%"${line##*[![:space:]]}"}"
                # Skip comments and empty lines
                [[ -z "$line" || "$line" == \#* ]] && continue
                # Parse KEY=VALUE (first = only, value may contain =)
                if [[ "$line" =~ ^([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
                    local key="${BASH_REMATCH[1]}"
                    local val="${BASH_REMATCH[2]}"
                    # Strip surrounding quotes if present
                    if [[ "$val" =~ ^\"(.*)\"$ ]] || [[ "$val" =~ ^\'(.*)\'$ ]]; then
                        val="${BASH_REMATCH[1]}"
                    fi
                    # Only set if not already set by an earlier (higher priority) file or env
                    # Priority: existing env > $PWD/.env > $PROJECT_ROOT/.env
                    # But since we iterate project-root first, then PWD, and PWD should override:
                    # We use a simpler approach: always export (later files override earlier)
                    # and pre-existing env vars take precedence (checked in defaults section)
                    export "$key"="$val"
                fi
            done < "$f"
        fi
    done

    # Auto-convert WORKSPACE from Windows path to WSL path if needed
    if [[ -n "${WORKSPACE:-}" ]]; then
        WORKSPACE="$(_win_to_wsl_path "$WORKSPACE")"
        export WORKSPACE
    fi
}
load_env

# ---------------------------------------------------------------------------
# Default configuration (overridable via env vars or .env)
# Priority: CLI args (-w) > JUPYTER_* env > short-name env (from .env) > hardcoded defaults
# Note: WORKSPACE is handled separately below because it needs path resolution.
# ---------------------------------------------------------------------------
CONTAINER_NAME="${JUPYTER_CONTAINER_NAME:-${CONTAINER_NAME:-jupyter-chaos-test}}"
IMAGE="${JUPYTER_IMAGE:-${IMAGE_TAG:-localhost/jupyter-podman-rootless:latest}}"
# IMAGE_TAG from .env may be just "name:tag" without registry; ensure localhost/ prefix for podman images
if [[ "$IMAGE" != */* ]]; then
    IMAGE="localhost/$IMAGE"
fi
SSH_PORT="${JUPYTER_SSH_PORT:-${SSH_PORT:-2222}}"
JUPYTER_PORT="${JUPYTER_PORT:-8888}"
PASSWORD="${JUPYTER_PASSWORD:-${USER_PASSWORD:-devpass123}}"
TOKEN="${JUPYTER_TOKEN:-chaostest2026}"
# WORKSPACE: host directory to mount to /workspace
# Priority: --workspace CLI arg > WORKSPACE env > JUPYTER_WORKSPACE env (compat) > $PROJECT_ROOT/workspace default
# - CLI arg (-w) and env var relative paths: resolved against user's current working directory
# - Default: $PROJECT_ROOT/workspace (stable, inside the app directory)
if [[ -n "${WORKSPACE:-}" ]]; then
    # WORKSPACE explicitly set via env — keep as-is (resolved in cmd_start against cwd)
    :
elif [[ -n "${JUPYTER_WORKSPACE:-}" ]]; then
    WORKSPACE="$JUPYTER_WORKSPACE"
else
    WORKSPACE="$PROJECT_ROOT/workspace"
fi
CACHE_DIR="$PROJECT_ROOT/.image-cache"
WSL_CACHE_DIR="$PROJECT_ROOT/.wsl-cache"
WSL_DISTRO="${JUPYTER_WSL_DISTRO:-Ubuntu}"
WSL_TARGET_DISTRO="${JUPYTER_WSL_TARGET_DISTRO:-jupyter-podman-rootless}"
WSL_INSTALL_DIR="${JUPYTER_WSL_INSTALL_DIR:-}"
WSL_DEFAULT_USER="${JUPYTER_WSL_DEFAULT_USER:-devuser}"
CONDA_PATH="${JUPYTER_CONDA_PATH:-/opt/conda}"

# Colors (disable if not a tty)
if [[ -t 1 ]]; then
    C_RESET='\033[0m'; C_GREEN='\033[0;32m'; C_YELLOW='\033[0;33m'
    C_RED='\033[0;31m'; C_CYAN='\033[0;36m'; C_BOLD='\033[1m'
else
    C_RESET=''; C_GREEN=''; C_YELLOW=''; C_RED=''; C_CYAN=''; C_BOLD=''
fi

info()  { echo -e "${C_GREEN}[INFO]${C_RESET}  $*"; }
warn()  { echo -e "${C_YELLOW}[WARN]${C_RESET}  $*"; }
error() { echo -e "${C_RED}[ERROR]${C_RESET} $*" >&2; }
die()   { error "$*"; exit 1; }

# ---------------------------------------------------------------------------
# Pre-flight checks
# ---------------------------------------------------------------------------
check_podman() {
    command -v podman &>/dev/null || die "podman not found. Install podman in WSL first."
}

container_exists() {
    podman ps -a --format '{{.Names}}' 2>/dev/null | grep -qx "$CONTAINER_NAME"
}

container_running() {
    podman ps --format '{{.Names}}' 2>/dev/null | grep -qx "$CONTAINER_NAME"
}

image_exists() {
    podman image exists "$IMAGE" 2>/dev/null
}

ensure_image() {
    if ! image_exists; then
        # Check cache
        local cached="$CACHE_DIR/jupyter-podman-rootless-latest.tar.gz"
        if [[ -f "$cached" ]]; then
            warn "Image not found locally but cache exists. Loading from cache..."
            cmd_load
        else
            die "Image '$IMAGE' not found. Build it first: $0 rebuild-all"
        fi
    fi
}

ensure_wsl_keepalive() {
    # If running inside WSL and keepalive not running, start it
    if grep -qi microsoft /proc/version 2>/dev/null; then
        if ! pgrep -f "sleep infinity" &>/dev/null; then
            setsid sleep infinity & disown
            info "Started WSL keepalive (sleep infinity)"
        fi
    fi
}

# ---------------------------------------------------------------------------
# WSL helper functions
# ---------------------------------------------------------------------------
in_wsl() {
    grep -qi microsoft /proc/version 2>/dev/null
}

wsl_exe() {
    # Find wsl.exe (Windows interop)
    if command -v wsl.exe &>/dev/null; then
        echo "wsl.exe"
    elif [[ -x "/mnt/c/Windows/System32/wsl.exe" ]]; then
        echo "/mnt/c/Windows/System32/wsl.exe"
    else
        echo ""
    fi
}

check_wsl() {
    in_wsl || die "This command must run inside WSL."
    local wsl
    wsl=$(wsl_exe)
    [[ -n "$wsl" ]] || die "wsl.exe not found. Ensure WSL Interop is enabled."
    echo "$wsl"
}

wsl_to_win_path() {
    # Convert WSL path (/mnt/d/...) to Windows path (D:\...)
    local wsl_path="$1"
    if command -v wslpath &>/dev/null; then
        wslpath -w "$wsl_path"
    else
        die "wslpath not found; cannot convert paths. Ensure you are running in a modern WSL distribution."
    fi
}

win_to_wsl_path() {
    # Convert Windows path (D:\...) to WSL path (/mnt/d/...)
    local win_path="$1"
    if command -v wslpath &>/dev/null; then
        wslpath -u "$win_path"
    else
        die "wslpath not found; cannot convert paths. Ensure you are running in a modern WSL distribution."
    fi
}

wsl_distro_exists() {
    local distro="$1"
    local wsl
    wsl=$(wsl_exe)
    # wsl.exe outputs UTF-16 LE with null bytes; strip them and compare case-insensitively
    "$wsl" -l -q 2>/dev/null | tr -d '\0\r' | tr '[:upper:]' '[:lower:]' | grep -Fxq "$(echo "$distro" | tr '[:upper:]' '[:lower:]')"
}

wsl_terminate() {
    local distro="$1"
    local wsl
    wsl=$(wsl_exe)
    "$wsl" --terminate "$distro" 2>/dev/null || true
}

check_rootful_podman() {
    # Check if sudo podman works (non-interactive)
    if sudo -n podman info &>/dev/null 2>&1; then
        echo "sudo podman"
    elif podman info &>/dev/null 2>&1; then
        warn "Using rootless podman; UID/GID mapping may cause permission issues in WSL distro."
        warn "Consider enabling passwordless sudo for podman, or run 'sudo -v' first."
        echo "podman"
    else
        die "podman not found or not accessible. Install podman and ensure sudo access."
    fi
}

# ---------------------------------------------------------------------------
# stage_upstream: 构建前把工作区 vendor/ 下上游 git submodule 源树复制到构建上下文
#   upstream/<name>（Containerfile 构建依赖，目录已被 .gitignore 忽略）。
#   用法与 python 侧 stage_upstream.py 保持一致，重复执行幂等。
# ---------------------------------------------------------------------------
UPSTREAM_NAMES="podman-compose podman-py toolbox"

# 从 PROJECT_ROOT 逐级向上查找含 .gitmodules 的工作区根目录（SpecWeave root）。
# PROJECT_ROOT 已由脚本自身位置解析为本地（WSL /mnt/... 或 /...）绝对路径，
# 因此对 vendor/ 的定位不依赖任何硬编码盘符。
find_workspace_root() {
    local dir
    dir="$(cd "$PROJECT_ROOT" && pwd)"
    while true; do
        if [[ -f "$dir/.gitmodules" ]]; then
            echo "$dir"
            return 0
        fi
        [[ "$dir" == "/" ]] && return 1
        dir="$(dirname "$dir")"
    done
}

# 幂等 stage：清空旧副本后重新复制（跳过 .git 与 Python 缓存）。源缺失/为空时
# stderr 打印修复提示并返回非 0。
stage_upstream_sources() {
    local ws_root src dst name
    ws_root="$(find_workspace_root)" || die "Cannot locate workspace root (.gitmodules) from $PROJECT_ROOT"
    info "Staging upstream source trees into $PROJECT_ROOT/upstream/"
    for name in $UPSTREAM_NAMES; do
        src="$ws_root/vendor/$name"
        dst="$PROJECT_ROOT/upstream/$name"
        if [[ ! -d "$src" ]] || [[ -z "$(ls -A "$src" 2>/dev/null)" ]]; then
            error "Upstream source tree missing or empty: $src (submodule not initialized?)"
            error "Fix: run 'git submodule update --init vendor/$name' at the SpecWeave root"
            return 1
        fi
        rm -rf "$dst"
        mkdir -p "$dst"
        if ! tar --exclude='*/.git' --exclude='*/__pycache__' --exclude='*.pyc' \
            -C "$src" -cf - . | tar -C "$dst" -xf -; then
            error "Failed to copy upstream source tree: $src -> $dst"
            return 1
        fi
        info "  staged $name"
    done
    info "Upstream source trees staged."
}

# ---------------------------------------------------------------------------
# Commands
# ---------------------------------------------------------------------------
cmd_help() {
    sed -n '2,/^set -euo/p' "$0" | grep -E '^#|^# jpman' | sed 's/^# \?//'
    echo ""
    echo -e "${C_BOLD}Project root:${C_RESET} $PROJECT_ROOT"
    echo -e "${C_BOLD}Container:${C_RESET}    $CONTAINER_NAME"
    echo -e "${C_BOLD}Image:${C_RESET}        $IMAGE"
    echo -e "${C_BOLD}Workspace:${C_RESET}    $WORKSPACE"
}

cmd_start() {
    check_podman
    ensure_image
    ensure_wsl_keepalive

    # Parse start command options: -w/--workspace
    while [[ $# -gt 0 ]]; do
        case "$1" in
            -w|--workspace)
                WORKSPACE="$2"
                shift 2
                ;;
            *)
                error "Unknown option for start: $1"
                echo "Usage: $0 start [-w|--workspace PATH]"
                return 1
                ;;
        esac
    done

    # Convert Windows path to WSL path if needed (e.g. -w D:\my-project from Windows interop)
    WORKSPACE="$(_win_to_wsl_path "$WORKSPACE")"

    # Resolve workspace to absolute path and create if it doesn't exist
    # WORKSPACE is relative to current working directory (where user runs jpman)
    if [[ "$WORKSPACE" != /* ]] && [[ "$WORKSPACE" != ~/* ]]; then
        WORKSPACE="$PWD/$WORKSPACE"
    elif [[ "$WORKSPACE" == ~/* ]]; then
        WORKSPACE="$HOME/${WORKSPACE#~/}"
    fi
    if [[ ! -d "$WORKSPACE" ]]; then
        info "Creating workspace directory: $WORKSPACE"
        mkdir -p "$WORKSPACE"
    fi
    # Resolve to absolute canonical path
    WORKSPACE="$(cd "$WORKSPACE" && pwd)"

    if container_running; then
        info "Container '$CONTAINER_NAME' is already running."
        cmd_info
        return 0
    fi

    if container_exists; then
        info "Removing stopped container '$CONTAINER_NAME'..."
        podman rm -f "$CONTAINER_NAME" &>/dev/null
    fi

    info "Creating container '$CONTAINER_NAME'..."
    info "  Mounting $WORKSPACE -> /workspace"
    podman create \
        --name "$CONTAINER_NAME" \
        --device /dev/fuse \
        --security-opt label=disable \
        --cgroupns=host \
        --restart unless-stopped \
        -p "${SSH_PORT}:22" \
        -p "${JUPYTER_PORT}:8888" \
        -v "${WORKSPACE}:/workspace" \
        -e USER_PASSWORD="$PASSWORD" \
        -e JUPYTER_TOKEN="$TOKEN" \
        -e GRANT_SUDO=yes \
        "$IMAGE"

    info "Starting container..."
    podman start "$CONTAINER_NAME"

    # Wait for healthy
    info "Waiting for services to be ready..."
    local waited=0
    while [[ $waited -lt 60 ]]; do
        if podman healthcheck run "$CONTAINER_NAME" &>/dev/null; then
            break
        fi
        sleep 2
        waited=$((waited + 2))
        echo -n "."
    done
    echo ""

    if container_running; then
        info "Container started successfully."
        cmd_info
    else
        die "Container failed to start. Check logs: $0 logs"
    fi
}

cmd_stop() {
    check_podman
    if container_exists; then
        info "Stopping and removing container '$CONTAINER_NAME'..."
        podman stop -t 5 "$CONTAINER_NAME" 2>/dev/null || true
        podman rm -f "$CONTAINER_NAME" 2>/dev/null || true
        info "Container removed."
    else
        info "Container '$CONTAINER_NAME' does not exist."
    fi
}

cmd_restart() {
    cmd_stop
    cmd_start "$@"
}

cmd_status() {
    check_podman
    if container_running; then
        echo -e "${C_GREEN}●${C_RESET} ${C_BOLD}$CONTAINER_NAME${C_RESET}  ${C_GREEN}running${C_RESET}"
        echo ""
        podman ps --filter "name=$CONTAINER_NAME" --format "table {{.ID}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}"
        echo ""
        podman healthcheck run "$CONTAINER_NAME" 2>/dev/null \
            && echo -e "  Health: ${C_GREEN}healthy${C_RESET}" \
            || echo -e "  Health: ${C_YELLOW}starting/unhealthy${C_RESET}"
    elif container_exists; then
        echo -e "${C_YELLOW}○${C_RESET} ${C_BOLD}$CONTAINER_NAME${C_RESET}  ${C_YELLOW}stopped${C_RESET}"
        podman ps -a --filter "name=$CONTAINER_NAME" --format "table {{.ID}}\t{{.Image}}\t{{.Status}}"
    else
        echo -e "${C_RED}○${C_RESET} ${C_BOLD}$CONTAINER_NAME${C_RESET}  ${C_RED}not created${C_RESET}"
        echo ""
        echo "  Start it with: $0 start"
    fi
    if image_exists; then
        local img_id img_size
        img_id=$(podman images "$IMAGE" --format '{{.ID}}' | head -c12)
        img_size=$(podman images "$IMAGE" --format '{{.Size}}')
        echo -e "  Image: $IMAGE ($img_id, $img_size)"
    else
        echo -e "  Image: ${C_RED}$IMAGE not found${C_RESET}"
    fi
}

cmd_shell() {
    check_podman
    local user="devuser"
    if [[ "${1:-}" == "--root" ]]; then
        user="root"
        shift
    fi
    container_running || die "Container not running. Start it first: $0 start"
    exec podman exec -it -u "$user" "$CONTAINER_NAME" bash -l
}

cmd_logs() {
    check_podman
    container_exists || die "Container does not exist."
    if [[ "${1:-}" == "-f" || "${1:-}" == "--follow" ]]; then
        exec podman logs -f "$CONTAINER_NAME"
    else
        exec podman logs --tail 100 "$CONTAINER_NAME"
    fi
}

cmd_exec() {
    check_podman
    container_running || die "Container not running. Start it first: $0 start"
    exec podman exec -it -u devuser "$CONTAINER_NAME" "$@"
}

cmd_root() {
    check_podman
    container_running || die "Container not running. Start it first: $0 start"
    exec podman exec -it -u root "$CONTAINER_NAME" "$@"
}

cmd_info() {
    check_podman
    echo ""
    echo -e "${C_BOLD}${C_CYAN}╔══════════════════════════════════════════════════╗${C_RESET}"
    echo -e "${C_BOLD}${C_CYAN}║       Jupyter Podman Rootless — Access Info      ║${C_RESET}"
    echo -e "${C_BOLD}${C_CYAN}╚══════════════════════════════════════════════════╝${C_RESET}"
    echo ""
    echo -e "  ${C_BOLD}Jupyter Lab:${C_RESET}  ${C_GREEN}http://localhost:${JUPYTER_PORT}/lab?token=${TOKEN}${C_RESET}"
    echo -e "  ${C_BOLD}SSH:${C_RESET}          ssh -p ${SSH_PORT} devuser@localhost"
    echo -e "  ${C_BOLD}Password:${C_RESET}     ${PASSWORD}"
    echo ""
    echo -e "  ${C_BOLD}Container:${C_RESET}    $CONTAINER_NAME"
    echo -e "  ${C_BOLD}Image:${C_RESET}        $IMAGE"
    echo -e "  ${C_BOLD}Mount:${C_RESET}        $WORKSPACE → /workspace"
    echo ""
    if container_running; then
        echo -e "  ${C_BOLD}Status:${C_RESET}       ${C_GREEN}● running${C_RESET}"
    elif container_exists; then
        echo -e "  ${C_BOLD}Status:${C_RESET}       ${C_YELLOW}○ stopped${C_RESET}"
    else
        echo -e "  ${C_BOLD}Status:${C_RESET}       ${C_RED}○ not created${C_RESET}"
    fi
    echo ""
}

cmd_url() {
    echo "http://localhost:${JUPYTER_PORT}/lab?token=${TOKEN}"
}

cmd_save() {
    check_podman
    image_exists || die "Image '$IMAGE' not found."
    mkdir -p "$CACHE_DIR"

    local image_id timestamp outfile latest_link
    image_id=$(podman images "$IMAGE" --format '{{.ID}}' | head -c12)
    timestamp=$(date +%Y%m%d-%H%M%S)
    outfile="$CACHE_DIR/jupyter-podman-rootless-${image_id}-${timestamp}.tar.gz"
    latest_link="$CACHE_DIR/jupyter-podman-rootless-latest.tar.gz"

    info "Saving image $IMAGE ($image_id)..."
    info "  Output: $outfile"

    local start_ts=$SECONDS
    if command -v pigz &>/dev/null; then
        podman save "$IMAGE" --format docker-archive | pigz -p "$(nproc)" > "$outfile"
    else
        podman save "$IMAGE" --format docker-archive | gzip > "$outfile"
    fi
    local elapsed=$((SECONDS - start_ts))

    local size hash
    size=$(du -sh "$outfile" | cut -f1)
    hash=$(sha256sum "$outfile" | cut -d' ' -f1)
    ln -sf "$(basename "$outfile")" "$latest_link"

    # Write manifest
    cat > "$CACHE_DIR/manifest.txt" <<EOF
# Jupyter Podman Rootless Image Cache
IMAGE_NAME=$IMAGE
IMAGE_ID=$image_id
IMAGE_FILE=$(basename "$outfile")
SIZE=$size
SHA256=$hash
SAVED=$(date -u +%Y-%m-%dT%H:%M:%SZ)
SAVE_TOOK=${elapsed}s
EOF

    gzip -t "$outfile" && info "Integrity: OK"
    info "Saved $size in ${elapsed}s"
    info "Restore with: $0 load"
}

cmd_load() {
    check_podman
    local archive="$CACHE_DIR/jupyter-podman-rootless-latest.tar.gz"
    [[ -f "$archive" ]] || die "No cached image found at $archive. Run '$0 save' first."

    info "Loading image from $archive..."
    local start_ts=$SECONDS
    gunzip -c "$archive" | podman load
    local elapsed=$((SECONDS - start_ts))
    info "Image loaded in ${elapsed}s"
    podman images "$IMAGE"
}

cmd_rebuild() {
    check_podman
    stage_upstream_sources || die "Staging upstream sources failed; aborting rebuild."
    info "Cached incremental rebuild from Containerfile (config-only changes hit Layer 4/5 cache, seconds)..."
    if container_running; then
        info "Stopping running container for rebuild..."
        podman stop -t 5 "$CONTAINER_NAME" 2>/dev/null || true
        podman rm -f "$CONTAINER_NAME" 2>/dev/null || true
    fi

    (cd "$PROJECT_ROOT" && podman build \
        --format docker \
        --build-arg APT_MIRROR=tuna \
        --build-arg CONDA_MIRROR=tuna \
        --build-arg PIP_MIRROR=tuna \
        -t "$IMAGE" -f Containerfile .)
    info "Rebuild complete."
    cmd_start
}

cmd_rebuild_all() {
    check_podman
    stage_upstream_sources || die "Staging upstream sources failed; aborting rebuild-all."
    info "Full rebuild from Containerfile (this may take a while)..."
    # Build from project root for correct context
    (cd "$PROJECT_ROOT" && podman build \
        --format docker \
        --build-arg APT_MIRROR=tuna \
        --build-arg CONDA_MIRROR=tuna \
        --build-arg PIP_MIRROR=tuna \
        -t "$IMAGE" -f Containerfile .)
    info "Full rebuild complete."
}

cmd_keepalive() {
    if grep -qi microsoft /proc/version 2>/dev/null; then
        if pgrep -f "sleep infinity" &>/dev/null; then
            info "WSL keepalive is already running."
        else
            setsid sleep infinity & disown
            info "WSL keepalive started (sleep infinity)."
        fi
    else
        warn "Not running inside WSL, keepalive not needed."
    fi
}

cmd_install() {
    local target="${1:-$HOME/.local/bin}"
    mkdir -p "$target"
    local link="$target/jpman"
    if [[ -L "$link" ]] || [[ -f "$link" ]]; then
        warn "$link already exists, overwriting..."
        rm -f "$link"
    fi
    ln -s "$SCRIPT_DIR/jpman" "$link"
    info "Symlinked jpman CLI to $link"
    if [[ ":$PATH:" != *":$target:"* ]]; then
        warn "$target is not in your PATH."
        echo "  Add this to your ~/.bashrc:"
        echo "    export PATH=\"$target:\$PATH\""
    else
        info "You can now run 'jpman' from anywhere."
        info "  Try: jpman status"
    fi
}

cmd_wsl_export() {
    local distro_name="$WSL_TARGET_DISTRO"
    local install_dir="$WSL_INSTALL_DIR"
    local force=0

    # Parse arguments
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --distro-name|-n) distro_name="$2"; shift 2 ;;
            --install-dir|-d) install_dir="$2"; shift 2 ;;
            --force|-f) force=1; shift ;;
            *) die "Unknown option for wsl-export: $1" ;;
        esac
    done

    local wsl
    wsl=$(check_wsl)
    info "WSL bridge: exporting image as WSL2 distro '$distro_name'..."

    # Determine install directory
    if [[ -z "$install_dir" ]]; then
        install_dir="$WSL_CACHE_DIR/$distro_name"
    fi
    mkdir -p "$install_dir"
    local install_dir_win
    install_dir_win=$(wsl_to_win_path "$install_dir")

    # Check if distro already exists
    if wsl_distro_exists "$distro_name"; then
        if [[ $force -eq 1 ]]; then
            warn "WSL distro '$distro_name' already exists, unregistering (--force)..."
            "$wsl" --unregister "$distro_name"
        else
            die "WSL distro '$distro_name' already exists. Use --force to overwrite, or choose a different name with --distro-name."
        fi
    fi

    # Ensure image is available (load from cache if needed)
    local podman_cmd
    podman_cmd=$(check_rootful_podman)

    # Find cached image archive
    local cached_archive="$CACHE_DIR/jupyter-podman-rootless-latest.tar.gz"
    if [[ ! -f "$cached_archive" ]]; then
        # Try timestamped archives
        cached_archive=$(ls -t "$CACHE_DIR"/jupyter-podman-rootless-*.tar.gz 2>/dev/null | head -1)
    fi
    [[ -f "$cached_archive" ]] || die "No cached image found. Run 'jpman save' first, or build the image."

    info "Using cached image: $cached_archive"
    local rootfs_out="$CACHE_DIR/${distro_name}-rootfs.tar.gz"
    local rootfs_out_win
    rootfs_out_win=$(wsl_to_win_path "$rootfs_out")

    # Step 1: Load image and export rootfs via Podman
    if [[ ! -f "$rootfs_out" ]] || [[ $force -eq 1 ]]; then
        info "Step 1/5: Loading image into Podman..."
        gunzip -c "$cached_archive" | $podman_cmd load

        info "Step 2/5: Creating container and exporting flat rootfs (gzip -1)..."
        local image_tag
        image_tag=$($podman_cmd images --format '{{.Repository}}:{{.Tag}}' | grep -v '<none>' | head -1)
        if [[ -z "$image_tag" ]]; then
            local image_id
            image_id=$($podman_cmd images -q | head -1)
            image_tag="$IMAGE"
            $podman_cmd tag "$image_id" "$image_tag"
        fi
        info "  Image tag: $image_tag"

        local tmp_container="wsl-export-$$"
        # Ensure cleanup of temp container on error/exit
        local cleanup_cmd="$podman_cmd rm -f '$tmp_container' >/dev/null 2>&1 || true"
        trap "$cleanup_cmd" EXIT
        $podman_cmd rm -f "$tmp_container" >/dev/null 2>&1 || true
        $podman_cmd create --name "$tmp_container" "$image_tag" >/dev/null
        $podman_cmd export "$tmp_container" | gzip -1 > "$rootfs_out"
        $podman_cmd rm "$tmp_container" >/dev/null
        trap - EXIT

        local rootfs_size
        rootfs_size=$(du -sh "$rootfs_out" | cut -f1)
        info "  RootFS exported: $rootfs_size"
    else
        info "RootFS already exists, skipping export (use --force to rebuild): $rootfs_out"
    fi

    # Step 2: Import into WSL
    info "Step 3/5: Importing into WSL2 at $install_dir_win..."
    mkdir -p "$install_dir"
    "$wsl" --import "$distro_name" "$install_dir_win" "$rootfs_out_win" --version 2

    # Step 3: Configure wsl.conf and conda
    info "Step 4/5: Configuring wsl.conf and Conda activation..."
    "$wsl" -d "$distro_name" -u root -- sh -c "cat > /etc/wsl.conf << 'EOF'
[user]
default=$WSL_DEFAULT_USER

[boot]
systemd=false

[automount]
enabled=true
mountFsTab=true
options=\"metadata,umask=0022,fmask=0011,dmask=0000\"

[network]
generateHosts=true
generateResolvConf=true
EOF
echo 'wsl.conf written'"

    # Configure conda
    if "$wsl" -d "$distro_name" -u root -- test -f "$CONDA_PATH/etc/profile.d/conda.sh"; then
        "$wsl" -d "$distro_name" -u root -- sh -c "cat > /etc/profile.d/conda.sh << 'EOF'
. $CONDA_PATH/etc/profile.d/conda.sh
conda activate base
EOF
chmod +x /etc/profile.d/conda.sh
echo 'Conda activation configured'"
    else
        warn "Conda init script not found at $CONDA_PATH, skipping conda configuration."
    fi

    # Step 4: Terminate to apply config
    info "Step 5/5: Restarting WSL distro to apply configuration..."
    wsl_terminate "$distro_name"
    sleep 2

    # Verify default user
    local verified_user
    verified_user=$("$wsl" -d "$distro_name" -- sh -l -c "whoami" 2>/dev/null || echo "")
    if [[ "$verified_user" != "$WSL_DEFAULT_USER" ]]; then
        warn "Default user may not be set correctly (got: '$verified_user', expected: '$WSL_DEFAULT_USER')."
        warn "Try: wsl --shutdown then retry. Or manually check /etc/wsl.conf."
    else
        info "Default user verified: $verified_user"
    fi

    # Run smoke test
    echo ""
    info "Running quick verification..."
    cmd_wsl_verify "$distro_name" || true

    echo ""
    info "✅ WSL export complete!"
    echo ""
    echo "  Enter environment:  wsl -d $distro_name"
    echo "  Run JupyterLab:     wsl -d $distro_name -- sh -l -c \"jupyter lab --no-browser --ip=0.0.0.0\""
    echo "  Start SSH+Jupyter:  wsl -d $distro_name -u root -- sh -l -c \"supervisord -c /etc/supervisor/supervisord.conf\""
    echo "  Unregister:         wsl --unregister $distro_name"
    echo ""
    echo "  💡 Tip: Use 'wsl -d $distro_name' to enter interactive shell first,"
    echo "     then run 'jupyter lab' directly (Conda auto-activated in login shell)."
    echo ""
}

cmd_wsl_verify() {
    local distro_name="${1:-$WSL_TARGET_DISTRO}"
    local wsl
    wsl=$(check_wsl)

    if ! wsl_distro_exists "$distro_name"; then
        die "WSL distro '$distro_name' does not exist."
    fi

    echo ""
    echo -e "${C_BOLD}${C_CYAN}🔍 WSL Distro Verification: $distro_name${C_RESET}"
    echo ""

    local pass=0
    local fail=0

    run_check() {
        local name="$1"
        local cmd="$2"
        local expect="${3:-.+}"
        echo -n "  [$name] "
        local result
        result=$("$wsl" -d "$distro_name" -- sh -l -c "$cmd" 2>&1)
        local rc=$?
        if [[ $rc -eq 0 ]] && echo "$result" | grep -Eq "$expect"; then
            echo -e "${C_GREEN}✅ PASS${C_RESET}"
            echo -e "      → $(echo "$result" | head -1)"
            pass=$((pass + 1))
        else
            echo -e "${C_RED}❌ FAIL${C_RESET}"
            echo -e "      → $result"
            fail=$((fail + 1))
        fi
    }

    echo -e "${C_BOLD}  Basic Environment${C_RESET}"
    run_check "Startup"     "echo OK" "OK"
    run_check "User"        "whoami" "^$WSL_DEFAULT_USER$"
    run_check "Writable"    "touch /tmp/test && rm /tmp/test && echo WRITABLE" "WRITABLE"
    run_check "Home dir"    "echo \$HOME" "/home/$WSL_DEFAULT_USER"

    # Check Windows drive mounts (best-effort)
    echo -e "${C_BOLD}  Drive Mounts${C_RESET}"
    if "$wsl" -d "$distro_name" -- sh -l -c "ls /mnt/c/ >/dev/null 2>&1"; then
        run_check "C: drive" "ls /mnt/c/ >/dev/null && echo C-MOUNT-OK" "C-MOUNT-OK"
    else
        echo -e "  [C: drive]  ${C_YELLOW}⚠️  SKIP (C: not mounted)${C_RESET}"
    fi
    if "$wsl" -d "$distro_name" -- sh -l -c "ls /mnt/d/ >/dev/null 2>&1"; then
        run_check "D: drive" "ls /mnt/d/ >/dev/null && echo D-MOUNT-OK" "D-MOUNT-OK"
    else
        echo -e "  [D: drive]  ${C_YELLOW}⚠️  SKIP (D: not mounted)${C_RESET}"
    fi

    echo -e "${C_BOLD}  Python/Conda Environment${C_RESET}"
    run_check "Conda"       "conda --version 2>&1" "conda"
    run_check "Python"      "python --version 2>&1" "Python 3\\.14"
    run_check "Python path" "which python" "$CONDA_PATH"

    # Free-threading check (written separately to avoid nested quote escaping issues with run_check)
    echo -n "  [Free-thread] "
    ft_result=$("$wsl" -d "$distro_name" -- sh -l -c 'python -c "import sys; print(sys._is_gil_enabled() if hasattr(sys, \"_is_gil_enabled\") else True)"' 2>&1)
    ft_rc=$?
    if [[ $ft_rc -eq 0 ]] && [[ "$ft_result" == "False" ]]; then
        echo -e "${C_GREEN}✅ PASS${C_RESET}"
        echo -e "      → GIL disabled (free-threading active)"
        pass=$((pass + 1))
    else
        echo -e "${C_RED}❌ FAIL${C_RESET}"
        echo -e "      → $ft_result"
        fail=$((fail + 1))
    fi

    run_check "Pip"         "pip --version 2>&1" "pip"

    echo -e "${C_BOLD}  Jupyter & Tools${C_RESET}"
    run_check "JupyterLab"  "jupyter lab --version 2>&1" "^[0-9]"
    run_check "Git"         "git --version 2>&1" "git version"
    run_check "Bash"        "bash --version | head -1" "GNU bash"
    run_check "Locale"      "locale 2>/dev/null | grep LANG= | head -1" "zh_CN\\.UTF-8|en_US\\.UTF-8"

    echo ""
    echo -e "${C_BOLD}  Results: ${C_GREEN}$pass passed${C_RESET}, ${C_RED}$fail failed${C_RESET}"
    echo ""

    if [[ $fail -eq 0 ]]; then
        return 0
    else
        return 1
    fi
}

# ---------------------------------------------------------------------------
# Main dispatch
# ---------------------------------------------------------------------------
main() {
    local cmd="${1:-help}"
    shift || true

    case "$cmd" in
        start)      cmd_start "$@" ;;
        stop)       cmd_stop "$@" ;;
        restart)    cmd_restart "$@" ;;
        status|ps)  cmd_status "$@" ;;
        shell|sh)   cmd_shell "$@" ;;
        logs)       cmd_logs "$@" ;;
        exec)       cmd_exec "$@" ;;
        root)       cmd_root "$@" ;;
        info)       cmd_info "$@" ;;
        url)        cmd_url "$@" ;;
        save)       cmd_save "$@" ;;
        load)       cmd_load "$@" ;;
        rebuild)    cmd_rebuild "$@" ;;
        rebuild-all) cmd_rebuild_all "$@" ;;
        wsl-export) cmd_wsl_export "$@" ;;
        wsl-verify) cmd_wsl_verify "$@" ;;
        keepalive)  cmd_keepalive "$@" ;;
        install)    cmd_install "$@" ;;
        help|-h|--help) cmd_help "$@" ;;
        *)
            error "Unknown command: $cmd"
            echo ""
            cmd_help
            exit 1
            ;;
    esac
}

main "$@"
