#!/bin/bash

# --- CONFIGURATION (Default values, will be overridden by network_config.env) ---
BACKEND_PORT=8000
FRONTEND_PORT=3001
BACKEND_SSL_PORT=3002
FRONTEND_SSL_PORT=3003
SERVER_IP="localhost"

# Load Configuration from file if it exists
CONFIG_PATH="$(cd "$(dirname "$0")" && pwd)/config/network_config.env"
if [ -f "$CONFIG_PATH" ]; then
    echo "⚙️  Loading network configuration from $CONFIG_PATH..."
    # Export variables from .env file (ignoring comments and empty lines)
    export $(grep -v '^#' "$CONFIG_PATH" | xargs)
fi

# Add common Mac paths for npm/node
export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"

echo "🚀 Starting TFM aInventory Stack with Dual Proxy..."

# 1. Kill potentially hanging processes
echo "Sweep: Cleaning up old processes..."
pkill -f "uvicorn" || true
pkill -f "next-server" || true
pkill -f "local-ssl-proxy" || true

# 2. Setup/Activate Virtual Environment
if [ ! -d ".venv" ]; then
    echo "🌑 Creating virtual environment (.venv)..."
    python3 -m venv .venv
fi
source .venv/bin/activate

# 3. Check and Install Backend Dependencies
echo "📦 Updating Python dependencies..."
pip install -q -r backend/requirements.txt

# 4. Get Local IP and set environment variables
LOCAL_IP=$(ipconfig getifaddr en0 || ipconfig getifaddr en1 || echo "localhost")
export ALLOWED_ORIGINS="http://localhost:$FRONTEND_PORT,http://localhost:$BACKEND_PORT,https://localhost:$FRONTEND_SSL_PORT,https://localhost:$BACKEND_SSL_PORT,https://$LOCAL_IP:$FRONTEND_SSL_PORT,https://$LOCAL_IP:$BACKEND_SSL_PORT"
export JWT_SECRET_KEY="${JWT_SECRET_KEY:-ephemeral-dev-key-$(date +%s)}"
export DATA_DIR="$(cd "$(dirname "$0")" && pwd)/data"
export LOGS_DIR="$(cd "$(dirname "$0")" && pwd)/logs"

# First-run: initialize data directories and config templates
echo "🔧 Initializing runtime data directories..."
bash "$(cd "$(dirname "$0")" && pwd)/scripts/init_data.sh"

# 4.1 Sync Network Config to Frontend for runtime discovery
echo "🔌 Syncing network configuration to frontend..."
cat <<EOF > frontend/public/network.json
{
  "SERVER_IP": "$SERVER_IP",
  "BACKEND_PORT": $BACKEND_PORT,
  "BACKEND_SSL_PORT": $BACKEND_SSL_PORT,
  "FRONTEND_PORT": $FRONTEND_PORT,
  "FRONTEND_SSL_PORT": $FRONTEND_SSL_PORT
}
EOF

echo "🔥 Starting Backend on port $BACKEND_PORT..."
echo "   CORS origins: $ALLOWED_ORIGINS"
python3 -m uvicorn backend.main:app --host 0.0.0.0 --port $BACKEND_PORT --reload &

# 5. Start Frontend (Next.js)
echo "💻 Starting Frontend on port $FRONTEND_PORT..."
cd frontend
npm run dev -- -p $FRONTEND_PORT &
cd ..

# 6. Start Proxies (Crucial for Mobile/Tablet Camera & Sync)
npx local-ssl-proxy --source $BACKEND_SSL_PORT --target $BACKEND_PORT --hostname 0.0.0.0 > /dev/null 2>&1 &
npx local-ssl-proxy --source $FRONTEND_SSL_PORT --target $FRONTEND_PORT --hostname 0.0.0.0 > /dev/null 2>&1 &

# 7. Print Unified Access Banner

# Colors
GREEN='\033[0;32m'
BOLD='\033[1m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo ""
echo -e "${GREEN}=======================================================${NC}"
echo -e "${GREEN}${BOLD}        🚀 TFM aInventory UNIFIED ACCESS${NC}"
echo -e "${GREEN}=======================================================${NC}"
echo ""
echo -e "   USE THIS URL ON BOTH DESKTOP & MOBILE:"
echo -e "   👉 ${GREEN}${BOLD}https://$LOCAL_IP:$FRONTEND_SSL_PORT${NC}"
echo -e "   (Or ${GREEN}https://localhost:$FRONTEND_SSL_PORT${NC} on this Mac)"
echo ""
echo -e "   ${YELLOW}${BOLD}NOTE:${NC} If you see a 'Not Private' warning,"
echo -e "   Click 'Advanced' -> 'Proceed' to continue."
echo -e "${GREEN}=======================================================${NC}"
echo "Keep this window open while working."
echo -e "${GREEN}=======================================================${NC}"

# Wait for background processes
wait
