#!/usr/bin/env bash
# file-next-issue.sh — Files the next unrealized issue from pool.json to
# ignaciolagosruiz/releasekit via the GitHub Issues API. Idempotent: if the
# next issue in the pool is already filed, it skips. If the pool is exhausted,
# it exits 0 with a message.
#
# Required env: GITHUB_TOKEN (PAT with `repo` scope on ignaciolagosruiz)
# State files (read/write): state.json
# Pool file (read): pool.json

set -euo pipefail

# Source the persistent env file if it exists; otherwise expect GITHUB_TOKEN
# in the environment.
if [ -z "${GITHUB_TOKEN:-}" ] && [ -f "$HOME/.hermes/secrets/github.env" ]; then
  set -a; source "$HOME/.hermes/secrets/github.env"; set +a
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
POOL="$SCRIPT_DIR/pool.json"
STATE="$SCRIPT_DIR/state.json"
LOG="$SCRIPT_DIR/file-next-issue.log"

REPO="ignaciolagosruiz"
REPO_NAME="releasekit"

log() { echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] $*" | tee -a "$LOG"; }

if [ -z "${GITHUB_TOKEN:-}" ]; then
  log "ERROR: GITHUB_TOKEN not set"
  exit 1
fi

if [ ! -f "$POOL" ]; then
  log "ERROR: pool.json not found at $POOL"
  exit 1
fi

if [ ! -f "$STATE" ]; then
  log "ERROR: state.json not found at $STATE"
  exit 1
fi

# Read counters from JSON
next_idx=$(python3 -c "import json;print(json.load(open('$STATE'))['next_id_to_file_index'])")
total=$(python3 -c "import json;print(len(json.load(open('$POOL'))['issues']))")

log "pool size: $total  next index: $next_idx"

if [ "$next_idx" -ge "$total" ]; then
  log "Pool exhausted. No more issues to file. Exit 0."
  exit 0
fi

# Pull the next issue spec
python3 -c "
import json
pool = json.load(open('$POOL'))
state = json.load(open('$STATE'))
issue = pool['issues'][state['next_id_to_file_index']]
filed_ids = {f['id'] for f in state['filed_issues']}
if issue['id'] in filed_ids:
    print('SKIP', flush=True)
else:
    print(json.dumps(issue), flush=True)
" > /tmp/next-issue-spec.txt

if [ "$(cat /tmp/next-issue-spec.txt | head -1)" = "SKIP" ]; then
  log "Issue at index $next_idx already filed. Advancing pointer."
  python3 -c "
import json
state = json.load(open('$STATE'))
state['next_id_to_file_index'] += 1
json.dump(state, open('$STATE', 'w'), indent=2)
"
  exit 0
fi

issue_id=$(python3 -c "import json;print(json.load(open('/tmp/next-issue-spec.txt'))['id'])")
issue_title=$(python3 -c "import json;print(json.load(open('/tmp/next-issue-spec.txt'))['title'])")
issue_body=$(python3 -c "import json;print(json.load(open('/tmp/next-issue-spec.txt'))['body_markdown'])")
issue_labels=$(python3 -c "import json;print(json.dumps(json.load(open('/tmp/next-issue-spec.txt'))['labels']))")

log "Filing issue: [$issue_id] $issue_title"

# Build the JSON body for the GitHub API
python3 -c "
import json
issue = json.load(open('/tmp/next-issue-spec.txt'))
payload = {
    'title': issue['title'],
    'body': issue['body_markdown'],
    'labels': issue['labels'],
}
json.dump(payload, open('/tmp/issue-payload.json', 'w'))
"

# POST to GitHub Issues API
HTTP_CODE=$(curl -sS -o /tmp/issue-response.json -w "%{http_code}" \
  -H "Authorization: token ${GITHUB_TOKEN}" \
  -H "Accept: application/vnd.github+json" \
  -H "X-GitHub-Api-Version: 2022-11-28" \
  -X POST "https://api.github.com/repos/${REPO}/${REPO_NAME}/issues" \
  --data-binary @/tmp/issue-payload.json)

if [ "$HTTP_CODE" = "201" ]; then
  issue_number=$(python3 -c "import json;print(json.load(open('/tmp/issue-response.json'))['number'])")
  issue_url=$(python3 -c "import json;print(json.load(open('/tmp/issue-response.json'))['html_url'])")
  log "Created issue #$issue_number — $issue_url"

  # Update state
  python3 -c "
import json
from datetime import datetime, timezone
state = json.load(open('$STATE'))
state['filed_issues'].append({
    'id': '$issue_id',
    'issue_number': $issue_number,
    'github_url': '$issue_url',
    'filed_at': datetime.now(timezone.utc).isoformat(),
    'resolved_at': None,
})
state['next_id_to_file_index'] += 1
state['last_filed_at'] = datetime.now(timezone.utc).isoformat()
json.dump(state, open('$STATE', 'w'), indent=2)
"
  log "State updated."
else
  log "ERROR: GitHub returned HTTP $HTTP_CODE"
  cat /tmp/issue-response.json
  exit 1
fi
