#!/usr/bin/env bash
# Seed 27 scenario-gap GitHub issues from scenario-gaps.json.
#
# Run from repo root. Requires `gh` (authenticated) and `jq`.
# Idempotent-ish: skips a gap if a same-titled open issue already exists.
#
# Usage:
#   scripts/seed-scenario-gap-issues.sh                # dry run, prints titles
#   scripts/seed-scenario-gap-issues.sh --apply        # actually create issues
#   scripts/seed-scenario-gap-issues.sh --apply --only SEC-01,DB-01

set -euo pipefail

GAPS_JSON="$(dirname "$0")/scenario-gaps.json"
APPLY=0
ONLY=""

while [[ $# -gt 0 ]]; do
  case $1 in
    --apply) APPLY=1; shift ;;
    --only)  ONLY="$2"; shift 2 ;;
    *)       echo "unknown arg: $1" >&2; exit 1 ;;
  esac
done

count_total=$(jq 'length' "$GAPS_JSON")
echo "Loaded $count_total gaps from $GAPS_JSON"
[[ $APPLY -eq 0 ]] && echo "(dry run — pass --apply to actually create)"

created=0
skipped=0

# shellcheck disable=SC2034
for i in $(jq -r 'to_entries | .[] | .key' "$GAPS_JSON"); do
  id=$(jq -r ".[$i].id" "$GAPS_JSON")

  # --only filter
  if [[ -n "$ONLY" && ",$ONLY," != *",$id,"* ]]; then
    continue
  fi

  title_raw=$(jq -r ".[$i].title" "$GAPS_JSON")
  severity=$(jq -r ".[$i].severity" "$GAPS_JSON")
  area=$(jq -r ".[$i].area" "$GAPS_JSON")
  agent=$(jq -r ".[$i].agent" "$GAPS_JSON")
  current=$(jq -r ".[$i].current" "$GAPS_JSON")
  risk=$(jq -r ".[$i].risk" "$GAPS_JSON")
  location=$(jq -r ".[$i].location" "$GAPS_JSON")
  proposal=$(jq -r ".[$i].proposal" "$GAPS_JSON")

  title="[$id] $title_raw"

  # Skip if already exists (open or closed)
  existing=$(gh issue list --state all --search "$title in:title" --json number,title --limit 5 \
             | jq -r --arg t "$title" '.[] | select(.title == $t) | .number' | head -1)
  if [[ -n "$existing" ]]; then
    echo "SKIP $id (already exists as #$existing)"
    skipped=$((skipped+1))
    continue
  fi

  body=$(cat <<EOF
## 갭 ID
$id

## 발견 경로
- 검토 대시보드: \`b2b-scenario-gaps.html\`
- 발견 에이전트: $agent

## 현재 동작
$current

## 예상 동작 / 위험
$risk

## 위치
$location

## 해결 제안
$proposal
EOF
)

  labels="severity: $severity,area: $area,b2b"

  if [[ $APPLY -eq 1 ]]; then
    url=$(gh issue create --title "$title" --body "$body" --label "$labels")
    echo "CREATE $id → $url"
    created=$((created+1))
  else
    echo "DRY    $id → $title  [$labels]"
  fi
done

echo "---"
echo "Summary: $created created, $skipped skipped (existed)"
