#!/usr/bin/env bash
# fix-plan-tiers.sh — normalize task.tier in harness-native plan JSONL files to the
# closed enum the engine actually enforces: low/medium/high (spec/presets.schema.json,
# lib/resolve-seat.sh). Legacy risk-vocabulary values ("regular"/"critical") come from
# an earlier draft of the harness-native schema and are never consumed by the engine —
# see docs/specs/2026-07-01-harness-migration-design.md field rules.
#
# Usage:
#   bin/fix-plan-tiers.sh [--dry-run] [file.jsonl ...]
#   (no files given) -> scans docs/plans/*.jsonl
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

if ! command -v jq >/dev/null 2>&1; then
  echo "fix-plan-tiers: jq required" >&2
  exit 1
fi

DRY_RUN=0
FILES=()
for arg in "$@"; do
  case "$arg" in
    --dry-run) DRY_RUN=1 ;;
    *) FILES+=("$arg") ;;
  esac
done

if [[ ${#FILES[@]} -eq 0 ]]; then
  while IFS= read -r -d '' f; do FILES+=("$f"); done \
    < <(find "$REPO_ROOT/docs/plans" -maxdepth 1 -name '*.jsonl' -print0)
fi

CHANGED=0
for f in "${FILES[@]}"; do
  [[ -f "$f" ]] || { echo "fix-plan-tiers: no such file: $f" >&2; exit 2; }

  hits="$(jq -rc 'select(.type=="task" and (.tier=="regular" or .tier=="critical")) | .id' "$f" 2>/dev/null || true)"
  [[ -z "$hits" ]] && continue

  echo "$f:"
  while IFS= read -r id; do
    echo "  $id: tier -> medium/high (was regular/critical)"
  done <<<"$hits"

  if [[ "$DRY_RUN" -eq 1 ]]; then
    continue
  fi

  tmp="$(mktemp)"
  jq -c 'if .type=="task" and .tier=="regular" then .tier="medium"
         elif .type=="task" and .tier=="critical" then .tier="high"
         else . end' "$f" > "$tmp"
  mv "$tmp" "$f"
  CHANGED=$((CHANGED+1))
done

if [[ "$DRY_RUN" -eq 1 ]]; then
  echo "dry-run: no files written"
else
  echo "fixed $CHANGED file(s)"
fi
