#!/bin/bash
# kugetsu-chat setup script
# Configures Hermes as Chat Agent for Phase 3a

set -euo pipefail

KUGETSU_CHAT_DIR="$(dirname "$(dirname "$(readlink -f "$0")")")"
HERMES_DIR="${HERMES_DIR:-$HOME/.hermes}"

usage() {
    cat << 'EOF'
kugetsu-chat setup - Configure Hermes as Chat Agent

Usage:
    kugetsu-chat-setup.sh [--apply] [--check]

Options:
    --apply    Apply the Chat Agent configuration to Hermes
    --check    Verify configuration without applying

Examples:
    ./kugetsu-chat-setup.sh --check   # Check configuration
    ./kugetsu-chat-setup.sh --apply   # Apply configuration

EOF
}

check_prerequisites() {
    echo "=== Checking Prerequisites ==="
    
    if ! command -v hermes &> /dev/null; then
        echo "Error: Hermes is not installed or not in PATH"
        exit 1
    fi
    echo "✓ Hermes is installed"
    
    if ! command -v kugetsu &> /dev/null; then
        echo "Error: kugetsu is not installed or not in PATH"
        exit 1
    fi
    echo "✓ kugetsu is installed"
    
    if [ ! -f "$HERMES_DIR/config.yaml" ]; then
        echo "Error: Hermes config not found at $HERMES_DIR/config.yaml"
        exit 1
    fi
    echo "✓ Hermes config exists"
    
    echo ""
}

verify_kugetsu_init() {
    echo "=== Verifying kugetsu Initialization ==="
    
    if [ ! -f "$HOME/.kugetsu/index.json" ]; then
        echo "Error: kugetsu not initialized. Run 'kugetsu init' first."
        exit 1
    fi
    
    if ! grep -q '"pm_agent"' "$HOME/.kugetsu/index.json"; then
        echo "Error: kugetsu index.json missing pm_agent field"
        exit 1
    fi
    
    PM_AGENT=$(python3 -c "import json; print(json.load(open('$HOME/.kugetsu/index.json')).get('pm_agent', ''))" 2>/dev/null || echo "")
    if [ -z "$PM_AGENT" ] || [ "$PM_AGENT" = "null" ]; then
        echo "Error: PM agent session not initialized. Run 'kugetsu init' first."
        exit 1
    fi
    
    echo "✓ kugetsu is initialized with PM agent: $PM_AGENT"
    echo ""
}

verify_telegram_config() {
    echo "=== Verifying Telegram Configuration ==="
    
    if ! grep -q "TELEGRAM_HOME_CHANNEL" "$HERMES_DIR/config.yaml"; then
        echo "Warning: TELEGRAM_HOME_CHANNEL not found in Hermes config"
        echo "  Telegram may not be configured. Run 'hermes gateway setup' to configure."
    else
        echo "✓ Telegram is configured in Hermes"
    fi
    
    echo ""
}

install_soul() {
    echo "=== Installing Chat Agent SOUL ==="
    
    SOUL_SOURCE="$KUGETSU_CHAT_DIR/SOUL.md"
    SOUL_TARGET="$HERMES_DIR/SOUL-chat.md"
    
    if [ ! -f "$SOUL_SOURCE" ]; then
        echo "Error: SOUL.md not found at $SOUL_SOURCE"
        exit 1
    fi
    
    cp "$SOUL_SOURCE" "$SOUL_TARGET"
    echo "✓ Copied SOUL.md to $SOUL_TARGET"
    
    echo ""
}

install_skill() {
    echo "=== Installing kugetsu-chat Skill ==="
    
    SKILL_SOURCE="$KUGETSU_CHAT_DIR"
    SKILL_TARGET="$HERMES_DIR/skills/kugetsu-chat"
    
    if [ -L "$SKILL_TARGET" ]; then
        rm "$SKILL_TARGET"
    elif [ -d "$SKILL_TARGET" ]; then
        echo "Warning: $SKILL_TARGET already exists (not a symlink)"
    fi
    
    ln -sf "$SKILL_SOURCE" "$SKILL_TARGET"
    echo "✓ Linked skill to $SKILL_TARGET"
    
    echo ""
}

apply_config() {
    echo "=== Applying Chat Agent Configuration ==="
    
    check_prerequisites
    verify_kugetsu_init
    verify_telegram_config
    install_soul
    install_skill
    
    echo "=== Configuration Complete ==="
    echo ""
    echo "Next steps:"
    echo "1. Run 'hermes gateway' to start the Telegram gateway"
    echo "2. Or run 'hermes' to use Chat Agent in CLI mode"
    echo ""
    echo "The Chat Agent will:"
    echo "- Receive Telegram messages"
    echo "- Handle small talk directly"
    echo "- Route task requests to PM Agent"
    echo "- Relay PM Agent responses back"
}

check_config() {
    echo "=== Checking Chat Agent Configuration ==="
    echo ""
    
    check_prerequisites
    verify_kugetsu_init
    verify_telegram_config
    
    SOUL_TARGET="$HERMES_DIR/SOUL-chat.md"
    if [ -f "$SOUL_TARGET" ]; then
        echo "✓ Chat Agent SOUL is installed"
    else
        echo "○ Chat Agent SOUL not installed (run with --apply)"
    fi
    
    SKILL_TARGET="$HERMES_DIR/skills/kugetsu-chat"
    if [ -L "$SKILL_TARGET" ]; then
        echo "✓ kugetsu-chat skill is linked"
    else
        echo "○ kugetsu-chat skill not linked (run with --apply)"
    fi
    
    echo ""
}

main() {
    if [ $# -eq 0 ]; then
        usage
        exit 1
    fi
    
    case "$1" in
        --apply)
            apply_config
            ;;
        --check)
            check_config
            ;;
        -h|--help)
            usage
            ;;
        *)
            echo "Error: Unknown option '$1'"
            usage
            exit 1
            ;;
    esac
}

main "$@"