#!/bin/bash
#
# GigLez Web Interface Startup Script
#

echo "=========================================="
echo "GigLez - IoT RF Device Mapping Platform"
echo "=========================================="
echo ""

# Check Python
if ! command -v python3 &> /dev/null; then
    echo "❌ Python 3 not found"
    exit 1
fi

echo "✅ Python 3 found"

# More robust project directory detection
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_ROOT="$SCRIPT_DIR"

# Check for multiple project markers
if [ ! -f "$PROJECT_ROOT/src/api/main_simple.py" ] || \
   [ ! -f "$PROJECT_ROOT/CLAUDE.md" ] || \
   [ ! -d "$PROJECT_ROOT/src/database" ]; then
    echo "❌ Not in project directory"
    echo "Please run from: $PROJECT_ROOT"
    echo "Or use: cd /path/to/giglez && ./start_web.sh"
    exit 1
fi

# Change to project root if needed
cd "$PROJECT_ROOT"

echo "✅ Project directory confirmed ($PROJECT_ROOT)"

# Check database
if [ -f "giglez.db" ]; then
    echo "✅ SQLite database found (85 signatures)"
else
    echo "⚠️  Database not found (run scripts/import_flipper_sqlite.py first)"
fi

echo ""

# Find available port (try 8000-8010)
PORT=8000
MAX_PORT=8010

echo "Checking for available port..."
while [ $PORT -le $MAX_PORT ]; do
    # Check if port is in use
    if lsof -Pi :$PORT -sTCP:LISTEN -t >/dev/null 2>&1 ; then
        # Get PID using the port
        PID=$(lsof -Pi :$PORT -sTCP:LISTEN -t)
        PROCESS=$(ps -p $PID -o comm= 2>/dev/null)
        echo "⚠️  Port $PORT in use (PID: $PID, Process: $PROCESS)"
        PORT=$((PORT + 1))
    else
        echo "✅ Port $PORT is available"
        break
    fi
done

if [ $PORT -gt $MAX_PORT ]; then
    echo ""
    echo "❌ No available ports in range 8000-$MAX_PORT"
    echo ""
    echo "Running processes:"
    lsof -i :8000-8010 -sTCP:LISTEN
    echo ""
    echo "To kill a process: kill -9 <PID>"
    exit 1
fi

# Start server
echo ""
echo "=========================================="
echo "Starting GigLez Web Server..."
echo "=========================================="
echo ""
echo "Web Interface: http://localhost:$PORT"
echo "API Docs:      http://localhost:$PORT/docs"
echo "Health Check:  http://localhost:$PORT/health"
echo ""
echo "Press Ctrl+C to stop"
echo ""

# Run with uvicorn
python3 -m uvicorn src.api.main_simple:app --host 0.0.0.0 --port $PORT --reload
