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

export LC_ALL=C

script_dir=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
root_dir=$(CDPATH= cd -- "$script_dir/.." && pwd)
env_file=$root_dir/deploy/ledger-api.env
spec_file=$root_dir/deploy/ledger-api.conf
image_file=$root_dir/fixtures/image-inspect.json

usage() {
  printf '%s\n' 'usage: containerctl image inspect IMAGE | inspect NAME | logs NAME | diagnose NAME | recreate NAME | health NAME' >&2
  exit 64
}

read_setting() {
  local file=$1
  local key=$2
  awk -F= -v wanted="$key" '
    $1 == wanted {
      sub(/^[^=]*=/, "")
      print
      found = 1
      exit
    }
    END { if (!found) exit 1 }
  ' "$file"
}

spec() {
  read_setting "$spec_file" "$1"
}

environment() {
  read_setting "$env_file" "$1"
}

require_name() {
  local wanted
  wanted=$(spec CONTAINER_NAME)
  if [[ ${1-} != "$wanted" ]]; then
    printf 'containerctl: no such container: %s\n' "${1-}" >&2
    exit 66
  fi
}

require_image() {
  local wanted
  wanted=$(spec IMAGE)
  if [[ ${1-} != "$wanted" ]]; then
    printf 'containerctl: no such image: %s\n' "${1-}" >&2
    exit 66
  fi
}

health_status() {
  local app_port health_port
  app_port=$(environment APP_PORT)
  health_port=$(spec HEALTH_PORT)
  if [[ $app_port == "$health_port" ]]; then
    printf '%s' healthy
  else
    printf '%s' unhealthy
  fi
}

show_inspect() {
  local app_mode app_port log_level image image_id command mount memory cpus pids health_port status
  app_mode=$(environment APP_MODE)
  app_port=$(environment APP_PORT)
  log_level=$(environment LOG_LEVEL)
  image=$(spec IMAGE)
  image_id=$(spec IMAGE_ID)
  command=$(spec COMMAND)
  mount=$(spec MOUNT)
  memory=$(spec MEMORY_BYTES)
  cpus=$(spec NANO_CPUS)
  pids=$(spec PIDS_LIMIT)
  health_port=$(spec HEALTH_PORT)
  status=$(health_status)

  printf '{\n'
  printf '  "Name": "/ledger-api",\n'
  printf '  "Image": "%s",\n' "$image_id"
  printf '  "Config": {\n'
  printf '    "Image": "%s",\n' "$image"
  printf '    "Cmd": ["/usr/local/bin/ledger-api", "serve"],\n'
  printf '    "CommandLine": "%s",\n' "$command"
  printf '    "Env": ["APP_MODE=%s", "APP_PORT=%s", "LOG_LEVEL=%s"]\n' "$app_mode" "$app_port" "$log_level"
  printf '  },\n'
  printf '  "HostConfig": {\n'
  printf '    "Binds": ["%s"],\n' "$mount"
  printf '    "Memory": %s,\n' "$memory"
  printf '    "NanoCpus": %s,\n' "$cpus"
  printf '    "PidsLimit": %s\n' "$pids"
  printf '  },\n'
  printf '  "State": {\n'
  printf '    "Status": "running",\n'
  printf '    "ExitCode": 0,\n'
  printf '    "Health": {"Status": "%s", "ProbePort": %s}\n' "$status" "$health_port"
  printf '  }\n'
  printf '}\n'
}

show_logs() {
  local app_port health_port
  app_port=$(environment APP_PORT)
  health_port=$(spec HEALTH_PORT)
  printf '%s\n' '2026-04-14T09:30:00Z level=info msg="starting ledger-api" mode=production'
  printf '2026-04-14T09:30:00Z level=info msg="listening" address=0.0.0.0:%s\n' "$app_port"
  if [[ $app_port == "$health_port" ]]; then
    printf '2026-04-14T09:30:10Z level=info msg="health probe passed" target=127.0.0.1:%s\n' "$health_port"
  else
    printf '2026-04-14T09:30:10Z level=warn msg="health probe failed" target=127.0.0.1:%s error="connection refused"\n' "$health_port"
  fi
}

show_health() {
  local name app_port health_port image_id
  name=$(spec CONTAINER_NAME)
  app_port=$(environment APP_PORT)
  health_port=$(spec HEALTH_PORT)
  image_id=$(spec IMAGE_ID)
  if [[ $app_port == "$health_port" ]]; then
    printf '%s: healthy\n' "$name"
    printf 'probe: tcp://127.0.0.1:%s\n' "$health_port"
    printf 'listener: tcp://127.0.0.1:%s\n' "$app_port"
    printf 'image_id: %s\n' "$image_id"
    return 0
  fi
  printf '%s: unhealthy\n' "$name"
  printf 'probe: tcp://127.0.0.1:%s\n' "$health_port"
  printf 'listener: tcp://127.0.0.1:%s\n' "$app_port"
  printf '%s\n' 'reason: connection refused'
  return 1
}

show_diagnosis() {
  local app_port health_port status
  app_port=$(environment APP_PORT)
  health_port=$(spec HEALTH_PORT)
  status=$(health_status)
  printf 'IMAGE: %s (%s)\n' "$(spec IMAGE)" "$(spec IMAGE_ID)"
  printf 'HEALTHCHECK: /usr/local/bin/healthcheck --port %s\n' "$health_port"
  printf 'COMMAND: %s\n' "$(spec COMMAND)"
  printf 'ENVIRONMENT: APP_MODE=%s APP_PORT=%s LOG_LEVEL=%s\n' "$(environment APP_MODE)" "$app_port" "$(environment LOG_LEVEL)"
  printf 'MOUNT: %s\n' "$(spec MOUNT)"
  printf 'LIMITS: memory=%s nano_cpus=%s pids=%s\n' "$(spec MEMORY_BYTES)" "$(spec NANO_CPUS)" "$(spec PIDS_LIMIT)"
  printf 'LOG: listener=0.0.0.0:%s probe=127.0.0.1:%s status=%s\n' "$app_port" "$health_port" "$status"
  if [[ $status == healthy ]]; then
    printf '%s\n' 'ASSESSMENT: deployment port matches the image healthcheck'
  else
    printf 'ASSESSMENT: APP_PORT=%s does not match image healthcheck port %s\n' "$app_port" "$health_port"
  fi
}

recreate() {
  local name
  name=$(spec CONTAINER_NAME)
  printf 'recreated %s\n' "$name"
  printf 'image: %s\n' "$(spec IMAGE)"
  printf 'image_id: %s (preserved)\n' "$(spec IMAGE_ID)"
  printf 'command: %s\n' "$(spec COMMAND)"
  printf 'environment: APP_MODE=%s APP_PORT=%s LOG_LEVEL=%s\n' "$(environment APP_MODE)" "$(environment APP_PORT)" "$(environment LOG_LEVEL)"
  printf 'mount: %s\n' "$(spec MOUNT)"
  printf 'limits: memory=%s nano_cpus=%s pids=%s\n' "$(spec MEMORY_BYTES)" "$(spec NANO_CPUS)" "$(spec PIDS_LIMIT)"
  printf 'health: %s\n' "$(health_status)"
}

case ${1-} in
  image)
    [[ $# -eq 3 && ${2-} == inspect ]] || usage
    require_image "$3"
    cat -- "$image_file"
    ;;
  inspect)
    [[ $# -eq 2 ]] || usage
    require_name "$2"
    show_inspect
    ;;
  logs)
    [[ $# -eq 2 ]] || usage
    require_name "$2"
    show_logs
    ;;
  diagnose)
    [[ $# -eq 2 ]] || usage
    require_name "$2"
    show_diagnosis
    ;;
  recreate)
    [[ $# -eq 2 ]] || usage
    require_name "$2"
    recreate
    ;;
  health)
    [[ $# -eq 2 ]] || usage
    require_name "$2"
    show_health
    ;;
  *)
    usage
    ;;
esac
