#!/usr/bin/env bash
# PhenikaaX RBS — CLI gom script theo nhóm.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")" && pwd)"

usage() {
  cat <<EOF
Usage: ./scripts/lm.sh <nhóm> <lệnh> [args...]

Test (local build + server tạm):
  test run              GTest + smoke + pytest (port \$LM_TEST_PORT, mặc định 18080)
  test smoke [url]      Chỉ API smoke (mặc định http://127.0.0.1:18080)

Docker (container :8080):
  docker up             compose up --build -d
  docker down           compose down
  docker stats [name]   CPU/RAM/cgroup
  docker htop           htop trong container
  docker shell          bash trong container
  docker bench [url]    Stats + đo latency HTTP
  docker test           up + smoke + pytest trên container

Benchmark:
  bench http [url]      Đo latency (mặc định \$LM_URL)

Biến môi trường: LM_URL, LM_TEST_PORT, LM_CONTAINER, TEST_BASE_URL, BENCH_REQUESTS
EOF
}

cmd="${1:-help}"
shift || true

case "$cmd" in
  help|-h|--help)
    usage
    ;;
  test)
    sub="${1:-run}"
    shift || true
    case "$sub" in
      run) exec "$ROOT/test/run.sh" "$@" ;;
      smoke) exec "$ROOT/test/smoke.sh" "$@" ;;
      *) echo "Unknown: test $sub" >&2; usage >&2; exit 1 ;;
    esac
    ;;
  docker)
    sub="${1:-}"
    shift || true
    case "$sub" in
      up) exec "$ROOT/docker/up.sh" "$@" ;;
      down) exec "$ROOT/docker/down.sh" "$@" ;;
      stats) exec "$ROOT/docker/stats.sh" "$@" ;;
      htop) exec "$ROOT/docker/htop.sh" "$@" ;;
      shell) exec "$ROOT/docker/shell.sh" "$@" ;;
      bench) exec "$ROOT/docker/bench.sh" "$@" ;;
      test) exec "$ROOT/docker/test.sh" "$@" ;;
      *) echo "Unknown: docker $sub" >&2; usage >&2; exit 1 ;;
    esac
    ;;
  bench)
    sub="${1:-http}"
    shift || true
    case "$sub" in
      http) exec "$ROOT/bench/http.sh" "$@" ;;
      *) echo "Unknown: bench $sub" >&2; usage >&2; exit 1 ;;
    esac
    ;;
  *)
    echo "Unknown group: $cmd" >&2
    usage >&2
    exit 1
    ;;
esac
