#!/usr/bin/env bash
# install.sh — Set up plan-tools on this machine
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
BIN_DIR="$SCRIPT_DIR/bin"

echo "plan-tools setup"
echo "════════════════"
echo ""

# Make scripts executable
chmod +x "$BIN_DIR/plan-refine"
chmod +x "$BIN_DIR/plan-status"
echo "Made scripts executable."

# Check for Oracle
if command -v oracle &>/dev/null; then
    echo "Oracle: $(oracle --version 2>/dev/null || echo 'installed')"
else
    echo "Oracle not found. Installing via npm..."
    npm install -g @steipete/oracle
fi

# Set up Oracle browser profile (first-time login)
ORACLE_PROFILE="$HOME/.oracle/browser-profile"
if [[ ! -d "$ORACLE_PROFILE" ]]; then
    echo ""
    echo "Oracle needs a one-time browser login to ChatGPT."
    echo "This will open Chrome — log into ChatGPT, then close the browser."
    read -rp "Run browser login now? (y/N) " confirm
    if [[ "$confirm" == "y" || "$confirm" == "Y" ]]; then
        oracle --engine browser \
            --browser-manual-login \
            --browser-keep-browser \
            -p "Hello, this is a test. Reply with: Oracle setup complete." \
            --write-output /dev/null || true
        echo "Browser profile saved."
    else
        echo "Skipped. Run this later:"
        echo "  oracle --engine browser --browser-manual-login --browser-keep-browser -p 'test'"
    fi
fi

# Symlink to PATH
echo ""
TARGET_BIN="$HOME/.local/bin"
mkdir -p "$TARGET_BIN"

for script in plan-refine plan-status; do
    target="$TARGET_BIN/$script"
    if [[ -L "$target" ]]; then
        rm "$target"
    fi
    ln -s "$BIN_DIR/$script" "$target"
    echo "Linked: $script -> $target"
done

# Check PATH
if ! echo "$PATH" | tr ':' '\n' | grep -q "^${TARGET_BIN}$"; then
    echo ""
    echo "NOTE: $TARGET_BIN is not in your PATH."
    echo "Add this to your shell profile:"
    echo "  export PATH=\"\$HOME/.local/bin:\$PATH\""
fi

echo ""
echo "Setup complete. Available commands:"
echo "  plan-refine <plan.md>         Run one ChatGPT evaluation iteration"
echo "  plan-refine <plan.md> --init  Add plan frontmatter to a file"
echo "  plan-status                   Show all plans and their pipeline stage"
echo ""
