#!/bin/bash
# cherrypipe — WeChat → AI agent bridge
# https://github.com/cherry/cherrypipe

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VENV_DIR="$SCRIPT_DIR/.venv"
PYTHON="$VENV_DIR/bin/python"
LOG_FILE="$HOME/Library/Logs/cherrypipe.log"
ERR_FILE="$HOME/Library/Logs/cherrypipe.err"
PLIST_NAME="com.cherrypipe.bridge"
PLIST_DST="$HOME/Library/LaunchAgents/$PLIST_NAME.plist"
DATA_DIR="$SCRIPT_DIR/data"

# ── Colours ───────────────────────────────────────────────────────────────────

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
RESET='\033[0m'

info()    { echo -e "${CYAN}$1${RESET}"; }
success() { echo -e "${GREEN}✅ $1${RESET}"; }
warn()    { echo -e "${YELLOW}⚠️  $1${RESET}"; }
error()   { echo -e "${RED}❌ $1${RESET}"; exit 1; }

# ── Setup — runs automatically on first use ───────────────────────────────────

setup() {
    if ! command -v python3 &>/dev/null; then
        error "Python 3 not found. Install from https://python.org"
    fi

    PYTHON_VERSION=$(python3 -c "import sys; print(sys.version_info.minor)")
    if [ "$PYTHON_VERSION" -lt 11 ]; then
        error "Python 3.11+ required. Current: $(python3 --version)"
    fi

    if [ ! -d "$VENV_DIR" ]; then
        info "Setting up cherrypipe (first run)..."
        python3 -m venv "$VENV_DIR"
    fi

    "$VENV_DIR/bin/pip" install -q -e "$SCRIPT_DIR"
}

# ── Plist install ─────────────────────────────────────────────────────────────

install_service() {
    local MOCK_FLAG="${1:-}"
    local TEMPLATE="$SCRIPT_DIR/deployment/com.cherrypipe.bridge.plist.template"
    if [ ! -f "$TEMPLATE" ]; then
        error "Plist template not found: $TEMPLATE"
    fi

    local ARGS_ENTRY=""
    if [ -n "$MOCK_FLAG" ]; then
        ARGS_ENTRY="<string>--mock</string>"
    fi

    mkdir -p "$HOME/Library/LaunchAgents"
    sed \
        -e "s|PLACEHOLDER_PYTHON|$PYTHON|g" \
        -e "s|PLACEHOLDER_MAIN|$SCRIPT_DIR/main.py|g" \
        -e "s|PLACEHOLDER_HOME|$HOME|g" \
        -e "s|PLACEHOLDER_DIR|$SCRIPT_DIR|g" \
        -e "s|PLACEHOLDER_ARGS|$ARGS_ENTRY|g" \
        "$TEMPLATE" > "$PLIST_DST"
}

# ── Data clearing ─────────────────────────────────────────────────────────────

clear_data() {
    rm -f "$DATA_DIR/credentials.json"
    rm -f "$DATA_DIR/pairs.json"
    rm -f "$DATA_DIR/sessions.json"
}

# ── Commands ──────────────────────────────────────────────────────────────────

cmd_start() {
    setup

    local MOCK_FLAG=""
    if [[ "$*" == *"--mock"* ]]; then
        MOCK_FLAG="--mock"
    fi

    # Start mock server if needed
    if [ -n "$MOCK_FLAG" ]; then
        if ! lsof -i :8765 &>/dev/null; then
            info "Starting mock server..."
            "$PYTHON" "$SCRIPT_DIR/mock/server.py" &>/tmp/cherrypipe-mock.log &
            MOCK_PID=$!
            echo $MOCK_PID > /tmp/cherrypipe-mock.pid
            sleep 1
            info "Mock server running (PID $MOCK_PID)"
        else
            info "Mock server already running."
        fi
    fi

    # Login if not already logged in
    if [ ! -f "$DATA_DIR/credentials.json" ]; then
        info "🍒 cherrypipe — first time setup"
        echo ""
        "$PYTHON" "$SCRIPT_DIR/login.py" $MOCK_FLAG
        echo ""
    fi

    # Install service if needed
    if [ ! -f "$PLIST_DST" ]; then
        install_service
    fi

    # Install service if needed (pass mock flag)
    install_service $MOCK_FLAG

    # Start if not already running
    if launchctl list 2>/dev/null | grep -q "$PLIST_NAME"; then
        success "cherrypipe is already running."
        info "Send a message from WeChat to start chatting."
        return
    fi

    launchctl load "$PLIST_DST" 2>/dev/null
    sleep 1

    if launchctl list 2>/dev/null | grep -q "$PLIST_NAME"; then
        success "cherrypipe started."
        echo ""
        info "Send a message from WeChat to begin pairing."
        info "Logs: ./cherrypipe logs"
    else
        error "Failed to start. Check: $ERR_FILE"
    fi
}

cmd_stop() {
    echo ""

    # Stop service
    if launchctl list 2>/dev/null | grep -q "$PLIST_NAME"; then
        launchctl unload "$PLIST_DST" 2>/dev/null || true
        success "Service stopped."
    else
        warn "Service was not running."
    fi

    # Stop mock server if running
    if [ -f /tmp/cherrypipe-mock.pid ]; then
        MOCK_PID=$(cat /tmp/cherrypipe-mock.pid)
        kill "$MOCK_PID" 2>/dev/null && info "Mock server stopped."
        rm -f /tmp/cherrypipe-mock.pid
    fi

    # Remove plist
    rm -f "$PLIST_DST"

    # Clear all data
    clear_data
    success "All data cleared."

    echo ""
    info "Run ./cherrypipe start to set up again."
    echo ""
}

cmd_clear() {
    echo ""
    warn "This will wipe all credentials, pairs, and sessions."
    read -r -p "Are you sure? (y/N) " confirm
    if [[ "$confirm" =~ ^[Yy]$ ]]; then
        cmd_stop 2>/dev/null || true
        clear_data
        success "Everything cleared. Run ./cherrypipe start to begin fresh."
    else
        info "Cancelled."
    fi
    echo ""
}

cmd_status() {
    echo ""
    echo -e "${BOLD}🍒 cherrypipe status${RESET}"
    echo "────────────────────────────────────────"

    # Service
    if launchctl list 2>/dev/null | grep -q "$PLIST_NAME"; then
        echo -e "Service:  ${GREEN}running${RESET}"
    else
        echo -e "Service:  ${RED}stopped${RESET}"
    fi

    # Login
    if [ -f "$DATA_DIR/credentials.json" ]; then
        ACCOUNT=$("$PYTHON" -c "import json; d=json.load(open('$DATA_DIR/credentials.json')); print(d.get('account_id','?'))" 2>/dev/null)
        echo -e "Account:  ${GREEN}$ACCOUNT${RESET}"
    else
        echo -e "Account:  ${RED}not logged in${RESET}"
    fi

    # Paired users
    if [ -f "$DATA_DIR/pairs.json" ]; then
        COUNT=$("$PYTHON" -c "import json; d=json.load(open('$DATA_DIR/pairs.json')); print(len(d.get('paired',[])))" 2>/dev/null)
        echo "Paired:   $COUNT user(s)"
    else
        echo "Paired:   0 user(s)"
    fi

    echo ""

    # Recent logs
    if [ -f "$LOG_FILE" ]; then
        echo -e "${BOLD}Recent logs:${RESET}"
        tail -5 "$LOG_FILE"
        echo ""
    fi
}

cmd_logs() {
    if [ ! -f "$LOG_FILE" ]; then
        warn "No log file yet. Start cherrypipe first."
        exit 1
    fi
    info "Following logs (Ctrl+C to stop)..."
    tail -f "$LOG_FILE"
}

cmd_help() {
    echo ""
    echo -e "${BOLD}🍒 cherrypipe${RESET} — WeChat → AI agent bridge"
    echo ""
    echo -e "${BOLD}Usage:${RESET}"
    echo "  ./cherrypipe <command>"
    echo ""
    echo -e "${BOLD}Commands:${RESET}"
    echo "  start    setup, login, and start the service"
    echo "  stop     stop the service and clear all data"
    echo "  status   show service and account status"
    echo "  logs     follow live logs"
    echo "  clear    wipe everything and start fresh"
    echo ""
    echo -e "${BOLD}WeChat commands:${RESET}"
    echo "  /status  show bridge status"
    echo "  /stop    stop the service from WeChat"
    echo "  /help    show all commands"
    echo ""
}

# ── Entry point ───────────────────────────────────────────────────────────────

COMMAND="${1:-help}"
shift 2>/dev/null || true

case "$COMMAND" in
    start)          cmd_start "$@" ;;
    stop)           cmd_stop ;;
    clear)          cmd_clear ;;
    status)         cmd_status ;;
    logs)           cmd_logs ;;
    help|--help|-h) cmd_help ;;
    *)              warn "Unknown command: $COMMAND"; cmd_help; exit 1 ;;
esac
