#!/usr/bin/env bash

# Fast-forward the complete project before a substantive Q&A session.
# Use QA_SYNC_REMOTE=github only when an explicit GitHub mirror is configured.

set -euo pipefail

for required_command in git dirname; do
  if ! command -v "$required_command" >/dev/null 2>&1; then
    printf 'ERROR: required command not found: %s. Install it and ensure it is available in PATH.\n' "$required_command" >&2
    exit 127
  fi
done

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
branch="${QA_SYNC_BRANCH:-master}"

if [[ -n "${QA_SYNC_REMOTE:-}" ]]; then
  sync_remote="$QA_SYNC_REMOTE"
elif git -C "$repo_root" remote get-url github >/dev/null 2>&1; then
  sync_remote="github"
else
  sync_remote="origin"
fi

if ! git -C "$repo_root" remote get-url "$sync_remote" >/dev/null 2>&1; then
  printf 'ERROR: configured sync remote does not exist: %s\n' "$sync_remote" >&2
  exit 1
fi

if [[ -n "$(git -C "$repo_root" status --porcelain)" ]]; then
  printf 'ERROR: working tree is not clean; archive, commit, or resolve changes before Q&A sync.\n' >&2
  exit 1
fi

current_branch="$(git -C "$repo_root" branch --show-current)"
if [[ "$current_branch" != "$branch" ]]; then
  printf 'ERROR: expected branch %s but current branch is %s\n' "$branch" "${current_branch:-detached}" >&2
  exit 1
fi

git -C "$repo_root" fetch "$sync_remote" "$branch"
git -C "$repo_root" pull --ff-only "$sync_remote" "$branch"
printf 'SYNC_OK remote=%s branch=%s head=%s\n' "$sync_remote" "$branch" "$(git -C "$repo_root" rev-parse --short HEAD)"
bash "$repo_root/scripts/install_skills_to_codex.sh"
printf 'PROJECT_DEFAULTS_REFRESH_OK repository=%s\n' "$repo_root"
