#!/bin/bash
# start-studio.sh — Launch local @mostajs/media studio (dev mode)
# Author: Dr Hamid MADANI <drmdh@msn.com>
# Date: 2026-04-29
# Usage: ./start-studio.sh [port]
#
# Prerequisites :
#   - Node.js 20+ (next 16 / react 19)
#   - ffmpeg installed system-wide (apt: ffmpeg, brew: ffmpeg)
#   - npm dependencies installed (run install-deploy.sh first if missing)
#
# This launches the studio in dev mode on http://localhost:<port> (default 4499).
# Studio = capture (image / webcam / screen+overlay+audio) → edit (split, speed,
# stickers, subtitles) → export (mp4 / gif / webm) → persist projects.

set -euo pipefail

CYAN='\033[0;36m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; NC='\033[0m'
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PORT="${1:-4499}"

cd "${SCRIPT_DIR}"

# ── 1. Pre-flight checks ──
echo -e "${CYAN}══════════════════════════════════════════════════${NC}"
echo -e "${CYAN}  @mostajs/media studio — local dev mode           ${NC}"
echo -e "${CYAN}══════════════════════════════════════════════════${NC}"

# Node.js
if ! command -v node >/dev/null 2>&1; then
  echo -e "${RED}  ✗ Node.js not found. Install Node 20+ first.${NC}"
  exit 1
fi
NODE_VER=$(node -v)
echo -e "${GREEN}  ✓ Node ${NODE_VER}${NC}"

# ffmpeg
if ! command -v ffmpeg >/dev/null 2>&1; then
  echo -e "${YELLOW}  ⚠ ffmpeg not found on PATH — server-side export will fail${NC}"
  echo -e "${YELLOW}    Install: sudo apt install ffmpeg   (or  brew install ffmpeg)${NC}"
else
  FFMPEG_VER=$(ffmpeg -version 2>&1 | head -1 | awk '{print $3}')
  echo -e "${GREEN}  ✓ ffmpeg ${FFMPEG_VER}${NC}"
fi

# Dependencies
if [ ! -d "node_modules" ]; then
  echo -e "${YELLOW}  ⚠ node_modules missing. Running install...${NC}"
  npm install --legacy-peer-deps
fi

# ── 2. Launch ──
echo ""
echo -e "${CYAN}  Starting Next.js dev server on port ${PORT}...${NC}"
echo -e "${GREEN}  ▶ http://localhost:${PORT}${NC}"
echo -e "${YELLOW}  Press Ctrl+C to stop${NC}"
echo ""

# Run with port override (package.json has -p 4499 by default; we honor PORT here)
exec npx next dev -p "${PORT}"
