#!/usr/bin/env bash

set -u

resolve_cwd() {
  local payload cwd
  payload="$(cat 2>/dev/null || true)"
  if [[ -n "$payload" ]]; then
    cwd="$(printf '%s' "$payload" | node -e '
let input = "";
process.stdin.on("data", (chunk) => { input += chunk; });
process.stdin.on("end", () => {
  try {
    const parsed = JSON.parse(input);
    if (parsed && typeof parsed.cwd === "string" && parsed.cwd.length > 0) {
      process.stdout.write(parsed.cwd);
    }
  } catch {}
});
')" || cwd=""
    if [[ -n "$cwd" ]]; then
      printf '%s\n' "$cwd"
      return
    fi
  fi

  pwd
}

main() {
  local cwd repo_root okf_bin project_name rc
  cwd="$(resolve_cwd)"
  repo_root="$(git -C "$cwd" rev-parse --show-toplevel 2>/dev/null || printf '%s\n' "$cwd")"
  okf_bin="$repo_root/bin/okf"
  project_name="$(basename "$repo_root")"

  if [[ ! -x "$okf_bin" ]]; then
    printf 'okf-sync: missing executable %s\n' "$okf_bin" >&2
    exit 0
  fi

  "$okf_bin" sync --repo "$repo_root" --project-name "$project_name" >/dev/null 2>&1
  rc=$?
  if [[ "$rc" -ne 0 ]]; then
    printf 'okf-sync: okf sync failed with exit %s\n' "$rc" >&2
  fi
  exit 0
}

main "$@"
