#!/usr/bin/env bash

# MCP Browser Project Management Script
# Project-level management tool with integrated venv handling

set -euo pipefail

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
BOLD='\033[1m'

# Project configuration
PROJECT_NAME="mcp-browser"
PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VENV_DIR="${PROJECT_DIR}/.venv"
TMP_DIR="${PROJECT_DIR}/tmp"
DATA_DIR="${PROJECT_DIR}/data"
LOGS_DIR="${PROJECT_DIR}/logs"
PID_FILE="${TMP_DIR}/mcp-server.pid"
VERSION_FILE="${PROJECT_DIR}/pyproject.toml"

# Platform detection
OS_TYPE="$(uname -s)"
IS_MACOS=false
IS_LINUX=false

case "${OS_TYPE}" in
    Darwin*)
        IS_MACOS=true
        ;;
    Linux*)
        IS_LINUX=true
        ;;
    *)
        echo -e "${YELLOW}⚠️  Warning: Unsupported OS '${OS_TYPE}'. Some features may not work.${NC}"
        ;;
esac

# Utility functions
print_header() {
    echo -e "\n${BOLD}${CYAN}═══════════════════════════════════════${NC}"
    echo -e "${BOLD}${CYAN}  ${PROJECT_NAME} Manager${NC}"
    echo -e "${BOLD}${CYAN}═══════════════════════════════════════${NC}\n"
}

print_success() {
    echo -e "${GREEN}✓${NC} $1"
}

print_error() {
    echo -e "${RED}✗${NC} $1" >&2
}

print_info() {
    echo -e "${BLUE}ℹ${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}⚠${NC} $1"
}

print_step() {
    echo -e "${MAGENTA}▶${NC} $1"
}

# Check for required tools
check_requirements() {
    local missing_tools=()

    command -v python3 >/dev/null 2>&1 || missing_tools+=("python3")
    command -v pip3 >/dev/null 2>&1 || missing_tools+=("pip3")

    if [ ${#missing_tools[@]} -gt 0 ]; then
        print_error "Missing required tools: ${missing_tools[*]}"
        print_info "Please install the missing tools and try again."
        exit 1
    fi

    # Check Python version
    local python_version=$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')
    if [[ $(echo "$python_version < 3.8" | bc -l) == 1 ]]; then
        print_error "Python 3.8 or higher is required (found: $python_version)"
        exit 1
    fi
}

# Virtual environment management
ensure_venv() {
    if [ ! -d "${VENV_DIR}" ]; then
        print_step "Creating virtual environment..."
        python3 -m venv "${VENV_DIR}"
        print_success "Virtual environment created at ${VENV_DIR}"

        # Upgrade pip
        "${VENV_DIR}/bin/pip" install --upgrade pip setuptools wheel >/dev/null 2>&1
        print_success "Updated pip, setuptools, and wheel"
    fi
}

activate_venv() {
    if [ -d "${VENV_DIR}" ]; then
        export PATH="${VENV_DIR}/bin:${PATH}"
        export VIRTUAL_ENV="${VENV_DIR}"
        unset PYTHONHOME 2>/dev/null || true
    else
        print_error "Virtual environment not found. Run '${0} install' first."
        exit 1
    fi
}

# Command functions
cmd_install() {
    print_header
    print_step "Installing ${PROJECT_NAME}..."

    check_requirements
    ensure_venv
    activate_venv

    # Install dependencies
    print_step "Installing dependencies..."
    pip install -e . >/dev/null 2>&1

    # Install dev dependencies if requirements-dev.txt exists
    if [ -f "${PROJECT_DIR}/requirements-dev.txt" ]; then
        pip install -r "${PROJECT_DIR}/requirements-dev.txt" >/dev/null 2>&1
        print_success "Development dependencies installed"
    fi

    print_success "${PROJECT_NAME} installed successfully!"
    print_info "Run '${0} init' to complete setup"
}

cmd_init() {
    print_header
    print_step "Initializing ${PROJECT_NAME}..."

    activate_venv

    # Create necessary directories
    mkdir -p "${TMP_DIR}" "${DATA_DIR}" "${LOGS_DIR}"
    print_success "Created project directories"

    # Create MCP configuration
    if [ ! -f "${PROJECT_DIR}/.mcp.json" ]; then
        cat > "${PROJECT_DIR}/.mcp.json" <<EOF
{
  "mcpServers": {
    "mcp-browser": {
      "command": "${VENV_DIR}/bin/python",
      "args": ["${PROJECT_DIR}/src/cli/main.py"],
      "env": {
        "PYTHONPATH": "${PROJECT_DIR}/src"
      }
    }
  }
}
EOF
        print_success "Created MCP configuration"
    else
        print_info "MCP configuration already exists"
    fi

    # Install Chrome extension
    if [ -d "${PROJECT_DIR}/extension" ]; then
        print_step "Chrome Extension Setup:"
        print_info "1. Open Chrome and navigate to: chrome://extensions"
        print_info "2. Enable 'Developer mode' (top right)"
        print_info "3. Click 'Load unpacked' and select: ${PROJECT_DIR}/extension"

        # Open Chrome extensions page on macOS
        if $IS_MACOS; then
            print_info "Opening Chrome extensions page..."
            open -a "Google Chrome" "chrome://extensions"
        fi
    fi

    print_success "Initialization complete!"
}

cmd_start() {
    print_header
    print_step "Starting MCP server..."

    activate_venv

    # Check if already running
    if [ -f "${PID_FILE}" ] && kill -0 $(cat "${PID_FILE}") 2>/dev/null; then
        print_warning "MCP server is already running (PID: $(cat ${PID_FILE}))"
        return 0
    fi

    # Start server in background
    cd "${PROJECT_DIR}"
    nohup python -m src.cli.main > "${LOGS_DIR}/mcp-server.log" 2>&1 &
    local pid=$!
    echo $pid > "${PID_FILE}"

    # Wait for server to start
    sleep 2

    if kill -0 $pid 2>/dev/null; then
        print_success "MCP server started (PID: $pid)"
        print_info "Logs: ${LOGS_DIR}/mcp-server.log"
    else
        print_error "Failed to start MCP server"
        rm -f "${PID_FILE}"
        exit 1
    fi
}

cmd_stop() {
    print_header
    print_step "Stopping MCP server..."

    if [ ! -f "${PID_FILE}" ]; then
        print_info "MCP server is not running"
        return 0
    fi

    local pid=$(cat "${PID_FILE}")
    if kill -0 $pid 2>/dev/null; then
        kill $pid
        rm -f "${PID_FILE}"
        print_success "MCP server stopped"
    else
        rm -f "${PID_FILE}"
        print_info "MCP server was not running"
    fi
}

cmd_status() {
    print_header

    # Check venv
    if [ -d "${VENV_DIR}" ]; then
        print_success "Virtual environment: Active"
    else
        print_error "Virtual environment: Not found"
    fi

    # Check server
    if [ -f "${PID_FILE}" ] && kill -0 $(cat "${PID_FILE}") 2>/dev/null; then
        print_success "MCP server: Running (PID: $(cat ${PID_FILE}))"

        # Check for active connections
        if command -v lsof >/dev/null 2>&1; then
            local ports=$(lsof -i :8875-8895 -P -n 2>/dev/null | grep LISTEN | awk '{print $9}' | cut -d: -f2 | sort -u)
            if [ ! -z "$ports" ]; then
                print_info "Active ports: $(echo $ports | tr '\n' ' ')"
            fi
        fi
    else
        print_warning "MCP server: Not running"
    fi

    # Check Chrome extension
    if $IS_MACOS; then
        local ext_loaded=$(ps aux | grep -i chrome | grep -c "extension" || true)
        if [ $ext_loaded -gt 0 ]; then
            print_info "Chrome extension: Potentially loaded"
        else
            print_warning "Chrome extension: Not detected (may need manual check)"
        fi
    fi

    # Show disk usage
    if [ -d "${DATA_DIR}" ]; then
        local data_size=$(du -sh "${DATA_DIR}" 2>/dev/null | cut -f1)
        print_info "Data directory size: ${data_size}"
    fi
}

cmd_test() {
    print_header
    print_step "Running tests..."

    activate_venv

    # Install test dependencies if needed
    if ! python -c "import pytest" 2>/dev/null; then
        print_step "Installing test dependencies..."
        pip install pytest pytest-asyncio pytest-cov >/dev/null 2>&1
    fi

    # Run tests
    cd "${PROJECT_DIR}"
    if python -m pytest tests/ -v --color=yes; then
        print_success "All tests passed!"
    else
        print_error "Some tests failed"
        exit 1
    fi
}

cmd_logs() {
    print_header

    local log_file="${LOGS_DIR}/mcp-server.log"

    if [ ! -f "${log_file}" ]; then
        print_warning "No log file found"
        return 0
    fi

    # Show last 50 lines by default
    local lines=${1:-50}
    print_info "Showing last ${lines} lines of logs:"
    echo -e "${CYAN}───────────────────────────────────────${NC}"
    tail -n "${lines}" "${log_file}"
    echo -e "${CYAN}───────────────────────────────────────${NC}"

    print_info "Full logs: ${log_file}"
}

cmd_clean() {
    print_header
    print_step "Cleaning up..."

    # Clean temporary files
    if [ -d "${TMP_DIR}" ]; then
        rm -rf "${TMP_DIR}"/*
        print_success "Cleaned temporary files"
    fi

    # Clean Python cache
    find "${PROJECT_DIR}" -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
    find "${PROJECT_DIR}" -type f -name "*.pyc" -delete 2>/dev/null || true
    print_success "Cleaned Python cache"

    # Clean old logs (keep last 7 days)
    if [ -d "${LOGS_DIR}" ]; then
        find "${LOGS_DIR}" -type f -mtime +7 -delete 2>/dev/null || true
        print_success "Cleaned old logs"
    fi

    # Clean old data files (keep last 7 days as per spec)
    if [ -d "${DATA_DIR}" ]; then
        find "${DATA_DIR}" -name "console_*.jsonl" -mtime +7 -delete 2>/dev/null || true
        print_success "Cleaned old data files"
    fi

    print_success "Cleanup complete!"
}

cmd_update() {
    print_header
    print_step "Updating ${PROJECT_NAME}..."

    activate_venv

    # Update pip first
    pip install --upgrade pip setuptools wheel >/dev/null 2>&1
    print_success "Updated pip and build tools"

    # Reinstall with latest dependencies
    pip install -e . --upgrade >/dev/null 2>&1
    print_success "Updated ${PROJECT_NAME} and dependencies"

    # Update dev dependencies if file exists
    if [ -f "${PROJECT_DIR}/requirements-dev.txt" ]; then
        pip install -r "${PROJECT_DIR}/requirements-dev.txt" --upgrade >/dev/null 2>&1
        print_success "Updated development dependencies"
    fi

    print_success "Update complete!"
}

cmd_version() {
    print_header

    if [ -f "${VERSION_FILE}" ]; then
        local version=$(grep '^version' "${VERSION_FILE}" | cut -d'"' -f2)
        echo -e "${BOLD}${PROJECT_NAME} version: ${GREEN}${version}${NC}"
    else
        print_warning "Version information not found"
    fi

    activate_venv 2>/dev/null || true
    if command -v python >/dev/null 2>&1; then
        local py_version=$(python --version 2>&1 | cut -d' ' -f2)
        echo -e "${BOLD}Python version: ${BLUE}${py_version}${NC}"
    fi

    echo -e "${BOLD}Project directory: ${MAGENTA}${PROJECT_DIR}${NC}"
}

cmd_extension() {
    print_header
    print_step "Opening Chrome extension setup..."

    if $IS_MACOS; then
        open -a "Google Chrome" "chrome://extensions"
        print_success "Opened Chrome extensions page"
    elif $IS_LINUX; then
        if command -v google-chrome >/dev/null 2>&1; then
            google-chrome "chrome://extensions" &
            print_success "Opened Chrome extensions page"
        else
            print_warning "Chrome not found. Please open chrome://extensions manually"
        fi
    else
        print_info "Please open chrome://extensions in your browser"
    fi

    print_info "Extension directory: ${PROJECT_DIR}/extension"
    print_info "1. Enable 'Developer mode'"
    print_info "2. Click 'Load unpacked'"
    print_info "3. Select the extension directory shown above"
}

cmd_dev() {
    print_header
    print_step "Starting development mode..."

    activate_venv

    # Install development dependencies
    if [ -f "${PROJECT_DIR}/requirements-dev.txt" ]; then
        if ! python -c "import watchdog" 2>/dev/null; then
            print_step "Installing development dependencies..."
            pip install -r "${PROJECT_DIR}/requirements-dev.txt" >/dev/null 2>&1
        fi
    fi

    print_info "Starting MCP server with hot reload..."
    print_info "Press Ctrl+C to stop"

    cd "${PROJECT_DIR}"

    # Check if dev_runner exists
    if [ -f "${PROJECT_DIR}/src/dev_runner.py" ]; then
        python -m src.dev_runner
    else
        # Fallback to regular server
        python -m src.cli.main
    fi
}

cmd_help() {
    print_header
    echo -e "${BOLD}Usage:${NC} ${0} <command> [options]"
    echo ""
    echo -e "${BOLD}Commands:${NC}"
    echo -e "  ${GREEN}install${NC}    Install ${PROJECT_NAME} with dependencies"
    echo -e "  ${GREEN}init${NC}       Initialize MCP configuration and directories"
    echo -e "  ${GREEN}start${NC}      Start the MCP server"
    echo -e "  ${GREEN}stop${NC}       Stop the MCP server"
    echo -e "  ${GREEN}status${NC}     Check server and extension status"
    echo -e "  ${GREEN}test${NC}       Run the test suite"
    echo -e "  ${GREEN}logs${NC}       Display server logs (optional: number of lines)"
    echo -e "  ${GREEN}clean${NC}      Clean temporary files and cache"
    echo -e "  ${GREEN}update${NC}     Update dependencies and reinstall"
    echo -e "  ${GREEN}version${NC}    Display version information"
    echo -e "  ${GREEN}extension${NC}  Open Chrome extension installation page"
    echo -e "  ${GREEN}dev${NC}        Start in development mode with hot reload"
    echo -e "  ${GREEN}help${NC}       Show this help message"
    echo ""
    echo -e "${BOLD}Examples:${NC}"
    echo -e "  ${0} install      # First-time setup"
    echo -e "  ${0} init         # Initialize configuration"
    echo -e "  ${0} start        # Start the server"
    echo -e "  ${0} logs 100     # Show last 100 lines of logs"
    echo -e "  ${0} dev          # Start development mode"
    echo ""
    echo -e "${BOLD}Project:${NC} ${PROJECT_DIR}"
    echo -e "${BOLD}Virtual Environment:${NC} ${VENV_DIR}"
}

# Main execution
main() {
    # Ensure we're in the project directory
    cd "${PROJECT_DIR}"

    # Create tmp directory if it doesn't exist
    mkdir -p "${TMP_DIR}"

    # Parse command
    local command="${1:-help}"
    shift || true

    case "${command}" in
        install)
            cmd_install "$@"
            ;;
        init)
            cmd_init "$@"
            ;;
        start)
            cmd_start "$@"
            ;;
        stop)
            cmd_stop "$@"
            ;;
        status)
            cmd_status "$@"
            ;;
        test)
            cmd_test "$@"
            ;;
        logs)
            cmd_logs "$@"
            ;;
        clean)
            cmd_clean "$@"
            ;;
        update)
            cmd_update "$@"
            ;;
        version)
            cmd_version "$@"
            ;;
        extension|ext)
            cmd_extension "$@"
            ;;
        dev|develop)
            cmd_dev "$@"
            ;;
        help|--help|-h)
            cmd_help
            ;;
        *)
            print_error "Unknown command: ${command}"
            echo "Run '${0} help' for usage information"
            exit 1
            ;;
    esac
}

# Handle both sourcing and direct execution
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi