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

if [[ $# -lt 1 ]]; then
  echo "usage: $0 /absolute/runtime/root [ai_api_repo_url] [branch]" >&2
  exit 2
fi

runtime_root="$1"
repo_url="${2:-git@codeup.aliyun.com:60069db88deaa14d9e02b875/zhct/ai_api.git}"
branch="${3:-develop_haerbin}"
ruflo_version="3.38.20"
script_dir="$(cd "$(dirname "$0")" && pwd)"
control_dir="$(cd "$script_dir/.." && pwd)"
zhctprompt_root="$(cd "$control_dir/../.." && pwd)"

if [[ "$runtime_root" != /* ]]; then
  echo "runtime root must be an absolute path" >&2
  exit 2
fi
case "$runtime_root/" in
  "$zhctprompt_root/"*)
    echo "runtime root must not be inside zhctprompt: $runtime_root" >&2
    exit 2
    ;;
esac

mkdir -p "$runtime_root"
harness_dir="$runtime_root/harness"
repo_dir="$runtime_root/ai_api-shanghe-lab"
mkdir -p "$harness_dir"

if [[ -e "$repo_dir" ]]; then
  if ! git -C "$repo_dir" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
    echo "existing repo path is not a git worktree: $repo_dir" >&2
    exit 1
  fi
  if [[ -n "$(git -C "$repo_dir" status --porcelain)" ]]; then
    echo "existing experiment repo is dirty; stop before refresh: $repo_dir" >&2
    exit 1
  fi
  git -C "$repo_dir" pull --ff-only
else
  git clone --branch "$branch" --single-branch "$repo_url" "$repo_dir"
fi

if [[ ! -f "$harness_dir/.claude-flow/config.yaml" ]]; then
  (
    cd "$harness_dir"
    printf 'n\n' | CI=1 npx --yes "ruflo@$ruflo_version" init \
      --minimal --skip-claude --no-global --no-skills-sh --no-signup --no-codex-detect
  )
fi

(
  cd "$harness_dir"
  npx --yes "ruflo@$ruflo_version" daemon stop >/dev/null 2>&1 || true
)

mkdir -p "$harness_dir/task-pack" "$harness_dir/evidence"
cp "$zhctprompt_root/work/2026-08-25-shanghe-health-device-integration/q.md" "$harness_dir/task-pack/q.md"
cp "$zhctprompt_root/work/2026-08-25-shanghe-health-device-integration/plan.md" "$harness_dir/task-pack/plan.md"
cp "$zhctprompt_root/work/2026-08-25-shanghe-health-device-integration/shanghe-health-device-integration-solution.md" "$harness_dir/task-pack/solution.md"

git -C "$repo_dir" status --short --branch
echo "harness=$harness_dir"
echo "repo=$repo_dir"
