#!/usr/bin/env bash
# close-issue.sh — Closes a GitHub issue with a "shipped" comment and updates
# state.json to mark it as resolved. Called by the agent AFTER pushing the fix
# commit and verifying the build is green.
#
# Required env: GITHUB_TOKEN
# Args:
#   $1: issue_id  (e.g. "doctor-cmd")
#   $2: commit_sha  (the 7+ char SHA of the fix commit)
#   $3: pr_or_branch_url  (URL to the commit/branch)
#
# Example:
#   ./close-issue.sh doctor-cmd abc1234 "https://github.com/ignaciolagosruiz/releasekit/commit/abc1234"

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)"
STATE="$SCRIPT_DIR/state.json"
LOG="$SCRIPT_DIR/close-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 [ $# -lt 3 ]; then
  log "Usage: $0 <issue_id> <commit_sha> <url>"
  exit 1
fi

ISSUE_ID="$1"
COMMIT_SHA="$2"
URL="$3"

# Find the issue number from state.json
issue_number=$(python3 -c "
import json
state = json.load(open('$STATE'))
for f in state['filed_issues']:
    if f['id'] == '$ISSUE_ID' and not f.get('resolved_at'):
        print(f['issue_number'])
        break
")
if [ -z "$issue_number" ]; then
  log "ERROR: no unresolved filed issue with id='$ISSUE_ID' in state.json"
  exit 1
fi

log "Closing issue #$issue_number (id=$ISSUE_ID, sha=$COMMIT_SHA)"

# Post the closing comment
comment_body="Shipped in commit [\`${COMMIT_SHA}\`](${URL}).

- All acceptance criteria met
- Full test suite green
- Ready for review"

curl -sS -o /tmp/close-comment.json -w "" \
  -H "Authorization: token ${GITHUB_TOKEN}" \
  -H "Accept: application/vnd.github+json" \
  -X POST "https://api.github.com/repos/${REPO}/${REPO_NAME}/issues/${issue_number}/comments" \
  -d "$(python3 -c "import json;print(json.dumps({'body': '''$comment_body'''}))")"

# Close the issue
curl -sS -o /tmp/close-issue.json -w "" \
  -H "Authorization: token ${GITHUB_TOKEN}" \
  -H "Accept: application/vnd.github+json" \
  -X PATCH "https://api.github.com/repos/${REPO}/${REPO_NAME}/issues/${issue_number}" \
  -d '{"state": "closed", "state_reason": "completed"}'

# Update state
python3 -c "
import json
from datetime import datetime, timezone
state = json.load(open('$STATE'))
for f in state['filed_issues']:
    if f['id'] == '$ISSUE_ID':
        f['resolved_at'] = datetime.now(timezone.utc).isoformat()
        f['resolution_sha'] = '$COMMIT_SHA'
        f['resolution_url'] = '$URL'
        break
state['last_resolved_at'] = datetime.now(timezone.utc).isoformat()
state['resolved_issues'].append({
    'id': '$ISSUE_ID',
    'issue_number': $issue_number,
    'resolution_sha': '$COMMIT_SHA',
    'resolution_url': '$URL',
})
json.dump(state, open('$STATE', 'w'), indent=2)
"

log "Issue #$issue_number closed and state updated."
