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

if [[ $# -lt 4 ]]; then
  echo "usage: $0 /absolute/runtime/root repo_url branch /absolute/task-pack-dir [ruflo-version]" >&2
  exit 2
fi

runtime_root="$1"
repo_url="$2"
branch="$3"
task_pack_dir="$4"
ruflo_version="${5:-3.38.20}"

if [[ "$runtime_root" != /* || "$task_pack_dir" != /* ]]; then
  echo "runtime root and task pack must be absolute paths" >&2
  exit 2
fi
if [[ ! -d "$task_pack_dir" ]]; then
  echo "task pack directory not found: $task_pack_dir" >&2
  exit 1
fi
if [[ ! -f "$task_pack_dir/task-metrics.csv" ]]; then
  echo "missing mandatory task metrics: $task_pack_dir/task-metrics.csv" >&2
  echo "copy assets/task-metrics-template.csv into the task pack and fill the baseline first" >&2
  exit 2
fi

source_repo="$(git -C "$task_pack_dir" rev-parse --show-toplevel 2>/dev/null || true)"
if [[ -n "$source_repo" ]]; then
  case "$runtime_root/" in
    "$source_repo/"*)
      echo "runtime root must not be inside the control repository: $runtime_root" >&2
      exit 2
      ;;
  esac
fi

mkdir -p "$runtime_root"
harness_dir="$runtime_root/harness"
repo_dir="$runtime_root/repo"
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; refusing 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"
find "$task_pack_dir" -maxdepth 1 -type f \( -name '*.md' -o -name '*.csv' \) -exec cp {} "$harness_dir/task-pack/" \;

python3 "$(dirname "$0")/validate_ruflo_task_metrics.py" "$task_pack_dir/task-metrics.csv" --phase start

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