#!/bin/bash
# scripts/claude-session.sh
# Description: Manage persistent Claude Code sessions for AI Stack Deployer
# Usage: bash scripts/claude-session.sh [list|delete <name>|help]

# Configuration
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
# Store sessions in user's home directory, NOT in project root
SESSION_DIR="$HOME/.claude/sessions/ai-stack-deployer"
mkdir -p "$SESSION_DIR"

# Claude Code built-in session storage
CLAUDE_BUILTIN_DIR="$HOME/.claude/projects/-home-odouhou-locale-projects-ai-stack-deployer"

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

# Helper functions
function success() {
    echo -e "${GREEN}✅ $1${NC}"
}

function error() {
    echo -e "${RED}❌ $1${NC}"
    return 1
}

function info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

function warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

# List all sessions
function list_sessions() {
    echo ""
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "  AI Stack Deployer Claude Code Sessions"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""

    local has_custom=false
    local has_builtin=false

    # List custom sessions
    if [ "$(ls -A $SESSION_DIR 2>/dev/null)" ]; then
        has_custom=true
        echo -e "${MAGENTA}📁 Custom Persistent Sessions${NC}"
        echo ""

        for session_file in "$SESSION_DIR"/*.session; do
            if [ -f "$session_file" ]; then
                source "$session_file"
                local name=$(basename "$session_file" .session)
                echo -e "${BLUE}Session:${NC} $name"
                echo "  ID: $CLAUDE_SESSION_ID"
                echo "  Started: $CLAUDE_SESSION_START"
                echo "  Last used: ${CLAUDE_SESSION_LAST_USED:-Never}"
                echo ""
            fi
        done
    fi

    # List Claude Code built-in sessions
    if [ -d "$CLAUDE_BUILTIN_DIR" ] && [ "$(ls -A $CLAUDE_BUILTIN_DIR/*.jsonl 2>/dev/null)" ]; then
        has_builtin=true

        if [ "$has_custom" = true ]; then
            echo ""
        fi

        echo -e "${MAGENTA}🤖 Claude Code Built-in Sessions${NC}"
        echo ""

        for jsonl_file in "$CLAUDE_BUILTIN_DIR"/*.jsonl; do
            if [ -f "$jsonl_file" ]; then
                local session_id=$(basename "$jsonl_file" .jsonl)
                local file_size=$(du -h "$jsonl_file" | cut -f1)
                local created=$(stat -c %y "$jsonl_file" 2>/dev/null | cut -d'.' -f1 || stat -f "%Sm" -t "%Y-%m-%d %H:%M:%S" "$jsonl_file" 2>/dev/null)
                local modified=$(stat -c %y "$jsonl_file" 2>/dev/null | cut -d'.' -f1 || stat -f "%Sm" -t "%Y-%m-%d %H:%M:%S" "$jsonl_file" 2>/dev/null)

                echo -e "${BLUE}Session ID:${NC} $session_id"
                echo "  Size: $file_size"
                echo "  Created: $created"
                echo "  Last modified: $modified"
                echo ""
            fi
        done
    fi

    if [ "$has_custom" = false ] && [ "$has_builtin" = false ]; then
        warning "No sessions found"
        echo ""
        info "Custom sessions: $SESSION_DIR"
        info "Built-in sessions: $CLAUDE_BUILTIN_DIR"
    fi
}

# Delete a session
function delete_session() {
    local SESSION_NAME="$1"
    local SESSION_FILE="$SESSION_DIR/$SESSION_NAME.session"

    if [ ! -f "$SESSION_FILE" ]; then
        error "Session not found: $SESSION_NAME"
        return 1
    fi

    source "$SESSION_FILE"

    echo ""
    warning "Delete session: $SESSION_NAME"
    echo "  ID: $CLAUDE_SESSION_ID"
    echo "  Started: $CLAUDE_SESSION_START"
    echo ""
    read -p "Are you sure? (yes/no): " -r REPLY

    if [ "$REPLY" == "yes" ]; then
        rm "$SESSION_FILE"
        success "Session deleted: $SESSION_NAME"
    else
        info "Deletion cancelled"
    fi
}

# Show help
function show_help() {
    echo "Usage: bash scripts/claude-session.sh [command]"
    echo ""
    echo "Commands:"
    echo "  list              - List all sessions"
    echo "  delete <name>     - Delete a session"
    echo "  help              - Show this help"
    echo ""
    echo "Environment variables set:"
    echo "  CLAUDE_SESSION_ID         - Persistent session UUID"
    echo "  CLAUDE_SESSION_NAME       - Session name"
    echo "  CLAUDE_SESSION_START      - When session was created"
    echo "  CLAUDE_SESSION_LAST_USED  - Last usage timestamp"
    echo "  CLAUDE_SESSION_PROJECT    - Project name (ai-stack-deployer)"
    echo "  CLAUDE_SESSION_MCP_GROUP  - MCP group ID (project_ai_stack_deployer)"
    echo ""
    echo "Examples:"
    echo "  bash scripts/claude-session.sh list"
    echo "  bash scripts/claude-session.sh delete feature-mcp-tools"
    echo ""
    echo "To start a session:"
    echo "  ./scripts/claude-start.sh feature-name"
}

# Main logic
case "${1:-}" in
    list)
        list_sessions
        ;;
    delete)
        if [ -z "${2:-}" ]; then
            error "Usage: $0 delete <session-name>"
            exit 1
        fi
        delete_session "$2"
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        show_help
        ;;
esac
