#!/usr/bin/env bash
# run-frontend.sh - Idempotent script to run the Channel Frontend.
# This script configures env vars, installs packages, and boots the frontend.

set -e

# Visual formatting helper
info() {
  echo -e "\033[1;34m[INFO]\033[0m $1"
}

# 1. Generate Environment Config
if [ ! -f Channel-Frontend/.env ]; then
  info "Generating Channel-Frontend/.env config file..."
  cat <<EOT > Channel-Frontend/.env
VITE_API_URL=http://localhost:5000/api/v1
EOT
else
  info "Channel-Frontend/.env file already exists."
fi

# 2. Install Node dependencies
info "Installing frontend node packages..."
cd Channel-Frontend
npm install

# Check if port 5173 is occupied and free it
if lsof -i :5173 &> /dev/null; then
  PORT_PID=$(lsof -t -i :5173)
  info "Port 5173 is occupied by process $PORT_PID. Freeing port..."
  kill -9 $PORT_PID || true
  sleep 1
fi

# 3. Start Vite Dev Server
info "Starting Vite frontend dev server..."
npm run dev -- --host
