#!/usr/bin/env bash
set -euo pipefail

script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd -- "${script_dir}/.." && pwd)"
cd "${repo_root}"

usage() {
  cat <<'USAGE'
Usage: bin/dev <command> [args...]

Commands:
  init              First-time, non-destructive setup
  up                Start local containers
  down              Stop local containers
  logs [service]    Follow docker compose logs (optional service)
  console <args...> Run php bin/console inside php container
  qa                Alias for qa-required
  qa-required       Run required quality gates (QG-001/002/003/006/008/009)
  qa-extended       Run qa-required plus non-blocking checks (QG-004/005/007)
USAGE
}

require_docker_compose() {
  if ! command -v docker >/dev/null 2>&1; then
    echo "[ERROR] docker is required." >&2
    exit 2
  fi
  docker compose version >/dev/null 2>&1 || {
    echo "[ERROR] docker compose is required." >&2
    exit 2
  }
}

wait_for_php_container() {
  local max_attempts=60
  local attempt=1
  while (( attempt <= max_attempts )); do
    if docker compose exec -T php php -v >/dev/null 2>&1; then
      return 0
    fi
    sleep 1
    attempt=$((attempt + 1))
  done

  echo "[ERROR] php container did not become ready in time." >&2
  return 1
}

run_console() {
  if [[ $# -eq 0 ]]; then
    echo "[ERROR] console requires arguments, e.g. bin/dev console list" >&2
    exit 2
  fi
  docker compose exec -T php php bin/console "$@"
}

cmd_init() {
  require_docker_compose

  if [[ ! -f .env ]]; then
    if [[ ! -f .env.example ]]; then
      echo "[ERROR] .env missing and .env.example not found." >&2
      exit 2
    fi
    cp .env.example .env
    echo "[INFO] created .env from .env.example"
  fi

  docker compose up --build -d
  wait_for_php_container

  run_console module:sync
  run_console doctor
}

cmd_up() {
  require_docker_compose
  docker compose up -d
}

cmd_down() {
  require_docker_compose
  docker compose down
}

cmd_logs() {
  require_docker_compose
  if [[ $# -gt 1 ]]; then
    echo "[ERROR] logs accepts at most one optional service name." >&2
    exit 2
  fi
  if [[ $# -eq 1 ]]; then
    docker compose logs -f "$1"
  else
    docker compose logs -f
  fi
}

cmd_qa_required() {
  require_docker_compose
  "${repo_root}/bin/qa-required.sh"
}

cmd_qa_extended() {
  require_docker_compose
  "${repo_root}/bin/qa-extended.sh"
}

if [[ $# -eq 0 ]]; then
  usage
  exit 0
fi

command="$1"
shift || true

case "${command}" in
  init)
    cmd_init "$@"
    ;;
  up)
    cmd_up "$@"
    ;;
  down)
    cmd_down "$@"
    ;;
  logs)
    cmd_logs "$@"
    ;;
  console)
    run_console "$@"
    ;;
  qa)
    cmd_qa_required "$@"
    ;;
  qa-required)
    cmd_qa_required "$@"
    ;;
  qa-extended)
    cmd_qa_extended "$@"
    ;;
  -h|--help|help)
    usage
    ;;
  *)
    echo "[ERROR] unknown command: ${command}" >&2
    usage
    exit 2
    ;;
esac
