#!/bin/bash
set -euo pipefail

REPO_DIR="$(cd "$(dirname "$0")" && pwd)"
SKILL_SRC="$REPO_DIR/skills/o11y-data"
CLAUDE_SKILL_DIR="$HOME/.claude/skills/o11y-data"
CURSOR_SKILL_DIR="$HOME/.cursor/skills/o11y-data"
VENV_DIR="$REPO_DIR/.venv"

info()  { echo "[INFO]  $*"; }
warn()  { echo "[WARN]  $*" >&2; }
error() { echo "[ERROR] $*" >&2; exit 1; }

# ─── Python venv (requires Python 3.10) ────────────────────────
setup_venv() {
    if ! command -v python3.10 &>/dev/null; then
        error "Python 3.10 is required but not found. Please install it:
  brew install python@3.10    # macOS
  apt install python3.10 python3.10-venv  # Ubuntu/Debian"
    fi

    local need_create=1
    if [ -d "$VENV_DIR" ]; then
        local v
        v=$("$VENV_DIR/bin/python" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null) || v=""
        if [ "$v" = "3.10" ]; then
            info "Virtual environment already exists at $VENV_DIR (Python 3.10)"
            need_create=0
        else
            warn "Existing venv uses Python $v, recreating with Python 3.10"
            rm -rf "$VENV_DIR"
        fi
    fi

    if [ "$need_create" -eq 1 ]; then
        info "Creating Python 3.10 virtual environment..."
        python3.10 -m venv "$VENV_DIR"
    fi

    info "Installing Python dependencies..."
    "$VENV_DIR/bin/pip" install -q --upgrade pip
    "$VENV_DIR/bin/pip" install -q -r "$REPO_DIR/requirements.txt"
    info "Python dependencies installed"
}

# ─── System tools check ──────────────────────────────────────
check_tools() {
    local missing=()
    for cmd in curl jq aws; do
        if ! command -v "$cmd" &>/dev/null; then
            missing+=("$cmd")
        fi
    done
    if [ ${#missing[@]} -gt 0 ]; then
        warn "Missing tools: ${missing[*]}"
        warn "Please install them for full O11Y skill functionality:"
        warn "  brew install ${missing[*]}    # macOS"
        warn "  apt install ${missing[*]}     # Ubuntu/Debian"
    else
        info "Required tools (curl, jq, aws) are available"
    fi

    if command -v duckdb &>/dev/null; then
        info "DuckDB is available (needed for slowlog queries)"
    else
        warn "DuckDB not found. Install for slowlog Delta Lake queries:"
        warn "  brew install duckdb    # macOS"
    fi
}

# ─── Install skill symlinks ──────────────────────────────────
install_skill() {
    local target_dir="$1"
    local name="$2"

    if [ -L "$target_dir" ]; then
        local existing
        existing=$(readlink "$target_dir")
        if [ "$existing" = "$SKILL_SRC" ]; then
            info "$name skill already linked"
            return
        fi
        rm "$target_dir"
    elif [ -d "$target_dir" ]; then
        warn "$name skill directory exists (not a symlink), backing up to ${target_dir}.bak"
        mv "$target_dir" "${target_dir}.bak"
    fi

    mkdir -p "$(dirname "$target_dir")"
    ln -s "$SKILL_SRC" "$target_dir"
    info "$name skill installed -> $target_dir"
}

# ─── GitHub PAT setup ────────────────────────────────────────
setup_github_pat() {
    local env_file="$REPO_DIR/.env"
    local obs_token_file="$HOME/.observability/.github"

    # Check .env for GITHUB_PAT or GITHUB_TOKEN
    if [ -f "$env_file" ]; then
        if grep -q "^GITHUB_PAT=" "$env_file" 2>/dev/null || \
           grep -q "^GITHUB_TOKEN=" "$env_file" 2>/dev/null; then
            info "GitHub token already configured in .env"
            return
        fi
    fi

    # Check environment variables
    if [ -n "${GITHUB_PAT:-}" ] || [ -n "${GITHUB_TOKEN:-}" ]; then
        info "GitHub token found in environment"
        return
    fi

    # Check ~/.observability/.github (used by logcli's client_auth.py)
    if [ -f "$obs_token_file" ] && [ -s "$obs_token_file" ]; then
        info "GitHub token found at $obs_token_file (used by logcli)"
        local existing_token
        existing_token=$(tr -d '[:space:]' < "$obs_token_file")
        [ ! -f "$env_file" ] && touch "$env_file"
        echo "GITHUB_PAT=${existing_token}" >> "$env_file"
        info "Synced token to .env for skill scripts"
        return
    fi

    # No token found anywhere — ask user
    echo ""
    echo "═══════════════════════════════════════════════════════════"
    echo "  GitHub Personal Access Token Setup"
    echo "═══════════════════════════════════════════════════════════"
    echo ""
    echo "A GitHub PAT with read:user and read:org scopes is required."
    echo "Create one at: https://github.com/settings/tokens/new"
    echo ""
    echo -n "Enter your GitHub PAT (or press Enter to skip): "
    read -r pat

    if [ -n "$pat" ]; then
        [ ! -f "$env_file" ] && touch "$env_file"
        echo "GITHUB_PAT=${pat}" >> "$env_file"
        mkdir -p "$HOME/.observability"
        echo -n "$pat" > "$obs_token_file"
        chmod 600 "$obs_token_file"
        info "GitHub PAT saved to .env and $obs_token_file"
    else
        warn "Skipped. You can set GITHUB_PAT later in .env or interactively"
    fi
}

# ─── Shell integration hint ──────────────────────────────────
print_usage() {
    echo ""
    echo "═══════════════════════════════════════════════════════════"
    echo "  Installation Complete"
    echo "═══════════════════════════════════════════════════════════"
    echo ""
    echo "Quick start:"
    echo ""
    echo "  # Activate Python environment"
    echo "  source $VENV_DIR/bin/activate"
    echo ""
    echo "  # Use O11Y shell helpers"
    echo "  source $REPO_DIR/skills/o11y-data/o11y-data.sh"
    echo "  o11y_auth"
    echo "  o11y_cluster_info aws us-west-2"
    echo ""
    echo "  # Inspect a cluster"
    echo "  python $REPO_DIR/skills/o11y-data/o11y-inspect.py <CLUSTER_ID>"
    echo ""
    echo "  # Use logcli"
    echo "  PYTHONPATH=$REPO_DIR python app/logcli/main.py logs download \\"
    echo "    --cluster <CLUSTER_ID> --vendor aws --region us-west-2 \\"
    echo "    --start 2026030500 --end 2026030506"
    echo ""
    echo "For AI coding assistants (Claude Code / Cursor):"
    echo "  The O11Y skill has been linked to ~/.claude/skills/ and ~/.cursor/skills/"
    echo "  It will be automatically available in your AI assistant sessions."
    echo ""
}

# ─── Main ─────────────────────────────────────────────────────
main() {
    info "Installing observability-client..."
    echo ""
    install_skill "$CLAUDE_SKILL_DIR" "Claude Code"
    install_skill "$CURSOR_SKILL_DIR" "Cursor"
    check_tools
    setup_venv
    setup_github_pat
    print_usage
}

main "$@"
