#!/usr/bin/env bash
set -euo pipefail

REPO="${REPO:-holon-run/holon-test}"
WORKFLOW="${WORKFLOW:-holon-solve-smoke.yml}"
MODEL="${MODEL:-anthropic/claude-sonnet-4-6}"
RUN_ID="${RUN_ID:-$(date +%Y%m%d-%H%M%S)}"
ISSUE_TITLE="${ISSUE_TITLE:-E2E issue resolve $RUN_ID}"
ISSUE_BODY_FILE="$(mktemp)"

cat >"$ISSUE_BODY_FILE" <<EOT
Please solve this issue by adding a small markdown file under docs/ with:

- title "E2E Issue Resolve Test"
- one short section saying this was generated by the Holon issue resolve e2e case

Open a pull request when complete.
EOT

issue_url="$(gh issue create --repo "$REPO" --title "$ISSUE_TITLE" --body-file "$ISSUE_BODY_FILE")"
rm -f "$ISSUE_BODY_FILE"

goal='Solve the target issue end to end. Make the requested docs-only change, commit it on a branch, push it, and open a pull request. Include the PR URL in summary.md and manifest.json when possible.'

gh workflow run "$WORKFLOW" \
  --repo "$REPO" \
  -f ref="$issue_url" \
  -f goal="$goal" \
  -f model="$MODEL"

sleep 5
run_json="$(gh run list --repo "$REPO" --workflow "$WORKFLOW" --limit 1 --json databaseId,url,status,conclusion,createdAt)"
run_url="$(printf '%s' "$run_json" | jq -r '.[0].url')"

cat <<EOT
Triggered issue resolve e2e.
- issue: $issue_url
- run: $run_url

Watch:
  gh run watch --repo "$REPO" "$(printf '%s' "$run_json" | jq -r '.[0].databaseId')" --interval 10
EOT
