#!/usr/bin/env bash
# PA Agent Mode - Launch/attach to persistent PA tmux session
set -euo pipefail

SESSION_NAME="pa"
CLAUDE="/home/linuxbrew/.linuxbrew/bin/claude"
HISTORY_DIR="$HOME/.claude/state/personal-assistant/history"
INDEX_FILE="$HISTORY_DIR/index.json"

usage() {
    echo "Usage: pa-mode [command]"
    echo ""
    echo "Commands:"
    echo "  (none)    Attach to existing session or create new one"
    echo "  new       Force new session (kills existing if any)"
    echo "  kill      Terminate the PA session"
    echo "  status    Show session status"
    echo ""
}

get_session_id() {
    date +"%Y-%m-%d_%H-%M-%S"
}

record_session_start() {
    local session_id="$1"
    local tmp_file
    tmp_file=$(mktemp)
    jq --arg id "$session_id" --arg started "$(date -Iseconds)" \
        '.sessions += [{"id": $id, "started": $started, "ended": null, "summarized": false, "topics": []}]' \
        "$INDEX_FILE" > "$tmp_file" && mv "$tmp_file" "$INDEX_FILE"
}

create_or_attach_session() {
    local session_id
    session_id=$(get_session_id)
    local history_file="$HISTORY_DIR/${session_id}.jsonl"

    # If session doesn't exist, record it in index before creating
    if ! tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
        record_session_start "$session_id"
    fi

    # Export env vars for the tmux session
    export CLAUDE_AGENT=personal-assistant
    export PA_SESSION_ID="$session_id"
    export PA_HISTORY_FILE="$history_file"

    # Using -A: attach if session exists, create if not
    # exec replaces this shell with tmux
    # Uses PA-specific config for distinct "power mode" visual theme
    exec tmux -f ~/.tmux-pa.conf new-session -A -s "$SESSION_NAME" -c "$HOME" \
        "$CLAUDE" --dangerously-skip-permissions --agent personal-assistant
}

case "${1:-}" in
    "")
        create_or_attach_session
        ;;
    new)
        if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
            tmux kill-session -t "$SESSION_NAME"
        fi
        create_or_attach_session
        ;;
    kill)
        if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
            tmux kill-session -t "$SESSION_NAME"
            echo "PA session terminated"
        else
            echo "No PA session running"
        fi
        ;;
    status)
        if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
            echo "PA session is running"
            tmux list-sessions -F "#{session_name}: #{session_created} (#{session_attached} attached)" | grep "^$SESSION_NAME:"
        else
            echo "PA session is not running"
        fi
        ;;
    -h|--help|help)
        usage
        ;;
    *)
        echo "Unknown command: $1"
        usage
        exit 1
        ;;
esac
