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

if (($# < 2)); then
  echo "usage: $0 <cp9-session> <kubectl-args...>" >&2
  exit 64
fi

session=$1
shift
repo_root="${CP9_REPO_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)}"
state_dir="${CP9_STATE_DIR:-$repo_root/.cp9/$session}"
host_json="$state_dir/host.json"

[[ -f "$host_json" ]] || {
  echo "cp9 host state is missing: $host_json" >&2
  exit 1
}

host_field() {
  python3 - "$host_json" "$1" <<'PY'
import json
import sys

value = json.load(open(sys.argv[1], encoding="utf-8"))
for key in sys.argv[2].split("."):
    value = value.get(key, "") if isinstance(value, dict) else ""
print(str(value or "").strip())
PY
}

mode=$(host_field mode)
context="${KUBE_CONTEXT:-$(host_field context)}"
if [[ "$mode" != "remote-ec2-k3d" ]]; then
  kubeconfig="${KUBECONFIG:-$(host_field kubeconfig_path)}"
  args=(--kubeconfig "$kubeconfig")
  [[ -n "$context" ]] && args+=(--context "$context")
  exec kubectl "${args[@]}" "$@"
fi

remote_kubeconfig=$(host_field remote.remote_kubeconfig_path)
[[ -n "$remote_kubeconfig" ]] || {
  echo "remote cp9 host state is incomplete: $host_json" >&2
  exit 1
}

remote_args=(kubectl --kubeconfig "$remote_kubeconfig")
[[ -n "$context" ]] && remote_args+=(--context "$context")
remote_args+=("$@")
exec "$repo_root/skills/get-started/scripts/session-ssh.sh" \
  "$session" "${remote_args[@]}"
