#!/usr/bin/env bash
# resolve-oldest-issue.sh — Scans open issues in ignaciolagosruiz/releasekit.
# If any issue in our known pool is >3 days old, it picks the oldest and writes
# a "ready for implementation" marker file. The cronjob that calls this script
# will then dispatch a sub-agent (Pipo) to read the issue and ship the fix.
#
# This script DOES NOT itself write code. It only:
#   1. Queries the GitHub Issues API for open issues we filed
#   2. Finds the oldest one that is >72h old
#   3. Emits a JSON marker file with everything the agent needs to start
#   4. Updates state.json to mark the issue as "in_resolution"
#
# Required env: GITHUB_TOKEN
# Output: /tmp/releasekit-todo.json  (consumed by the agent prompt)

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/resolve-oldest-issue.log"
POOL="$SCRIPT_DIR/pool.json"
TODO="/tmp/releasekit-todo.json"

REPO="ignaciolagosruiz"
REPO_NAME="releasekit"
REPO_OWNER="ignaciolagosruiz"
export REPO_NAME REPO_OWNER
export STATE POOL

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

# List open issues with our pool labels
HTTP_CODE=$(curl -sS -o /tmp/open-issues.json -w "%{http_code}" \
  -H "Authorization: token ${GITHUB_TOKEN}" \
  -H "Accept: application/vnd.github+json" \
  -H "X-GitHub-Api-Version: 2022-11-28" \
  "https://api.github.com/repos/${REPO}/${REPO_NAME}/issues?state=open&per_page=50")

if [ "$HTTP_CODE" != "200" ]; then
  log "ERROR: GitHub returned HTTP $HTTP_CODE"
  cat /tmp/open-issues.json
  exit 1
fi

# Find the oldest issue in our pool that is >= 72 hours old and still unresolved
# Emit it as a todo file the agent can pick up
python3 <<'PYEOF'
import json
import os
from datetime import datetime, timezone, timedelta

state = json.load(open(os.environ['STATE']))
pool = json.load(open(os.environ['POOL']))
open_issues = json.load(open('/tmp/open-issues.json'))

# Issues are returned with PRs mixed in; filter to actual issues
open_issues = [i for i in open_issues if 'pull_request' not in i]

# Build a map: id -> pool spec
pool_by_id = {p['id']: p for p in pool['issues']}

# Build a map: issue_number -> github issue
gh_by_number = {i['number']: i for i in open_issues}

# Find the oldest filed-but-unresolved issue from our pool
now = datetime.now(timezone.utc)
cutoff = now - timedelta(hours=72)

candidates = []
for filed in state['filed_issues']:
    if filed.get('resolved_at'):
        continue
    issue_num = filed['issue_number']
    if issue_num not in gh_by_number:
        continue
    gh_issue = gh_by_number[issue_num]
    filed_at = datetime.fromisoformat(filed['filed_at'].replace('Z', '+00:00'))
    if filed_at > cutoff:
        continue
    age_hours = (now - filed_at).total_seconds() / 3600
    candidates.append({
        'filed': filed,
        'gh': gh_issue,
        'age_hours': age_hours,
        'pool_spec': pool_by_id.get(filed['id']),
    })

if not candidates:
    # No issue is ready. Emit an empty todo and exit 0.
    json.dump({'action': 'noop', 'reason': 'no_open_issue_over_72h_old'}, open('/tmp/releasekit-todo.json', 'w'))
    print('NOOP', flush=True)
else:
    # Pick the oldest
    candidates.sort(key=lambda c: c['filed']['filed_at'])
    chosen = candidates[0]
    payload = {
        'action': 'implement_and_close',
        'issue_number': chosen['filed']['issue_number'],
        'issue_url': chosen['filed']['github_url'],
        'issue_id': chosen['filed']['id'],
        'issue_title': chosen['gh']['title'],
        'issue_body': chosen['gh']['body'],
        'pool_spec': chosen['pool_spec'],
        'age_hours': chosen['age_hours'],
        'repo': os.environ['REPO_NAME'],
        'owner': os.environ['REPO_OWNER'],
        'local_path': '/home/ubuntu/nachlakes-oss/releasekit',
    }
    json.dump(payload, open('/tmp/releasekit-todo.json', 'w'), indent=2)
    print(f"TODO issue #{payload['issue_number']}", flush=True)
PYEOF

result=$(cat /tmp/releasekit-todo.json | python3 -c "import json,sys;print(json.load(sys.stdin)['action'])")

if [ "$result" = "noop" ]; then
  reason=$(python3 -c "import json;print(json.load(open('/tmp/releasekit-todo.json'))['reason'])")
  log "Nothing to do: $reason"
  exit 0
fi

issue_num=$(python3 -c "import json;print(json.load(open('/tmp/releasekit-todo.json'))['issue_number'])")
log "Selected issue #$issue_num for resolution. Todo written to /tmp/releasekit-todo.json"
