#!/bin/bash
# Browser automation script for mcpz browser MCP server
# Usage: ./browser.sh <command> [args]
#
# Commands:
#   demo <url>               - Run full demo: open URL, get content, screenshot

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
MCPZ="${SCRIPT_DIR}/target/release/mcpz"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

# Ensure mcpz is built
ensure_built() {
    if [[ ! -f "$MCPZ" ]]; then
        echo -e "${YELLOW}Building mcpz...${NC}"
        (cd "$SCRIPT_DIR" && cargo build --release)
    fi
}

# Run a full demo
run_demo() {
    local url="${1:-https://example.com}"

    ensure_built

    echo -e "${GREEN}=== Browser Demo ===${NC}"
    echo -e "${CYAN}URL: $url${NC}"
    echo ""

    mkdir -p /tmp/mcpz
    rm -f /tmp/mcpz/demo-fifo
    mkfifo /tmp/mcpz/demo-fifo

    # Start server in background, capture output
    "$MCPZ" server browser < /tmp/mcpz/demo-fifo 2>/dev/null > /tmp/mcpz/demo-output &
    SERVER_PID=$!

    # Open fifo for writing
    exec 3>/tmp/mcpz/demo-fifo

    # Cleanup on exit
    cleanup() {
        exec 3>&- 2>/dev/null || true
        kill $SERVER_PID 2>/dev/null || true
        rm -f /tmp/mcpz/demo-fifo /tmp/mcpz/demo-output
    }
    trap cleanup EXIT

    sleep 1

    echo -e "${YELLOW}Starting browser...${NC}"
    echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' >&3
    sleep 0.5
    echo '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"start_browser","arguments":{}}}' >&3
    sleep 3

    echo -e "${YELLOW}Navigating to $url...${NC}"
    echo "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"open_url\",\"arguments\":{\"url\":\"${url}\",\"wait_time\":5}}}" >&3
    sleep 7

    echo -e "${YELLOW}Getting page content...${NC}"
    echo '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"get_page_as_markdown","arguments":{}}}' >&3
    sleep 2

    echo -e "${YELLOW}Taking screenshot...${NC}"
    echo '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"get_screenshot","arguments":{}}}' >&3
    sleep 2

    echo -e "${YELLOW}Stopping browser...${NC}"
    echo '{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"stop_browser","arguments":{}}}' >&3
    sleep 1

    # Close fifo
    exec 3>&-

    # Wait for server to finish
    wait $SERVER_PID 2>/dev/null || true

    echo ""
    echo -e "${GREEN}=== Results ===${NC}"
    echo ""

    # Parse output
    local output=$(cat /tmp/mcpz/demo-output 2>/dev/null)

    # Extract markdown content (response id=4)
    local markdown=$(echo "$output" | grep '"id":4' | python3 -c "
import sys, json
try:
    data = json.loads(sys.stdin.read())
    if 'result' in data and 'content' in data['result']:
        for c in data['result']['content']:
            if c.get('type') == 'text':
                inner = json.loads(c['text'])
                if 'data' in inner and 'markdown' in inner['data']:
                    md = inner['data']['markdown']
                    print(md[:3000])
                    if len(md) > 3000:
                        print('... (truncated)')
except Exception as e:
    pass
" 2>/dev/null)

    if [[ -n "$markdown" ]]; then
        echo -e "${CYAN}Page Content (Markdown):${NC}"
        echo "----------------------------------------"
        echo "$markdown"
        echo "----------------------------------------"
        echo ""
    fi

    # Extract screenshot path (response id=5)
    local screenshot=$(echo "$output" | grep '"id":5' | python3 -c "
import sys, json
try:
    data = json.loads(sys.stdin.read())
    if 'result' in data and 'content' in data['result']:
        for c in data['result']['content']:
            if c.get('type') == 'text':
                inner = json.loads(c['text'])
                if 'path' in inner:
                    print(inner['path'])
except:
    pass
" 2>/dev/null)

    if [[ -n "$screenshot" ]] && [[ -f "$screenshot" ]]; then
        echo -e "${GREEN}Screenshot saved to: $screenshot${NC}"

        # Try to open it on macOS
        if [[ "$(uname)" == "Darwin" ]]; then
            echo -e "${CYAN}Opening screenshot...${NC}"
            open "$screenshot" 2>/dev/null || true
        fi
    fi

    echo ""
    echo -e "${GREEN}Demo complete!${NC}"

    # Remove trap and do cleanup manually
    trap - EXIT
    rm -f /tmp/mcpz/demo-fifo /tmp/mcpz/demo-output
}

# Show usage
show_usage() {
    echo "Browser automation script for mcpz"
    echo ""
    echo "Usage: $0 demo <url>"
    echo ""
    echo "Examples:"
    echo "  $0 demo https://xeb.ai"
    echo "  $0 demo https://google.com"
    echo "  $0 demo https://news.ycombinator.com"
    echo ""
    echo "This will:"
    echo "  1. Start Chrome with remote debugging"
    echo "  2. Navigate to the URL"
    echo "  3. Get the page content as markdown"
    echo "  4. Take a screenshot"
    echo "  5. Stop Chrome"
    echo "  6. Display results and open the screenshot"
}

# Main
case "${1:-}" in
    demo)
        run_demo "${2:-https://example.com}"
        ;;
    help|--help|-h|"")
        show_usage
        ;;
    *)
        echo -e "${RED}Unknown command: $1${NC}"
        show_usage
        exit 1
        ;;
esac
