#!/bin/bash

# AI-Core gRPC Server Startup Script

echo "Starting AI-Core Document Parser gRPC Server..."

# 配置
PORT=${1:-50051}

# 使用虚拟环境
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"

# Windows 下使用 PowerShell 的 py 命令或者直接用 venv
if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "win32" || -f "venv/Scripts/python.exe" ]]; then
    if [ -f "venv/Scripts/python.exe" ]; then
        echo "Using virtual environment Python..."
        PYTHON_CMD="$SCRIPT_DIR/venv/Scripts/python.exe"
    elif command -v py &> /dev/null; then
        echo "Using py launcher..."
        PYTHON_CMD="py"
    else
        echo "Error: Python not found"
        exit 1
    fi
else
    # Linux/Mac
    if [ -d "venv" ]; then
        echo "Activating virtual environment..."
        source venv/bin/activate
        PYTHON_CMD="python"
    else
        PYTHON_CMD="python3"
    fi
fi

echo "Using Python: $PYTHON_CMD"
$PYTHON_CMD --version

# Check if requirements are installed
$PYTHON_CMD -c "import grpcio" 2>/dev/null
if [ $? -ne 0 ]; then
    echo "Installing Python dependencies..."
    $PYTHON_CMD -m pip install -r requirements.txt
    if [ $? -ne 0 ]; then
        echo "Error: Failed to install dependencies"
        exit 1
    fi
fi

# Generate gRPC code if needed
if [ ! -f "proto/document_parser_pb2.py" ]; then
    echo "Generating gRPC code..."
    $PYTHON_CMD generate_grpc.py
    if [ $? -ne 0 ]; then
        echo "Error: Failed to generate gRPC code"
        exit 1
    fi
fi

# 用 Python 来检测和杀死占用端口的进程（跨平台更可靠）
echo "Checking and cleaning up port $PORT..."

# 先尝试直接用 Windows 命令杀死（更可靠）
if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "win32" || "$(uname)" == "MINGW"* ]]; then
    # 直接用 cmd /c 执行
    cmd //c "for /f \"tokens=5\" %a in ('netstat -ano ^| findstr :$PORT ^| findstr LISTENING') do taskkill /F /PID %a"
    sleep 1
fi

# 再用 Python 检测
$PYTHON_CMD -c "
import socket
import subprocess
import sys
import time
import os

port = $PORT
print(f'Checking port {port}...')

# 检查端口是否被占用
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(1)
    result = s.connect_ex(('127.0.0.1', port))
    s.close()
    if result != 0:
        print(f'Port {port} is free (not listening)')
    else:
        print(f'Port {port} is still in use!')
        # 尝试杀死
        try:
            result = subprocess.run(['netstat', '-ano'], capture_output=True, text=True, shell=True)
            for line in result.stdout.split('\n'):
                if f':{port}' in line and 'LISTENING' in line:
                    parts = line.split()
                    pid = parts[-1]
                    print(f'Found process {pid}, killing...')
                    os.system(f'taskkill /F /PID {pid}')
            time.sleep(2)
        except Exception as e:
            print(f'Error: {e}')
except Exception as e:
    print(f'Check error: {e}')
"

# Start the server
echo "Starting server on port $PORT..."
$PYTHON_CMD main.py --port $PORT --max-workers 10 --log-level INFO
