#!/usr/bin/env bash
# Identify the "last green" and "first red" commits for a workflow.
#
# Usage:
#   script/ci-find-regression-range [owner/repo] [workflow_file] [branch]
#
# Examples:
#   script/ci-find-regression-range hi-godot/godot-ai ci.yml main
#
# Requirements:
#   - python3
#   - GitHub API access (optionally authenticated via GH_TOKEN)
set -euo pipefail
source "$(dirname "$0")/_ci_env.sh"

REPO="${1:-}"
WORKFLOW="${2:-ci.yml}"
BRANCH="${3:-main}"

if [[ -z "$REPO" ]]; then
  ORIGIN_URL="$(git config --get remote.origin.url || true)"
  if [[ "$ORIGIN_URL" =~ github.com[:/]([^/]+/[^/.]+)(\.git)?$ ]]; then
    REPO="${BASH_REMATCH[1]}"
  else
    echo "ERROR: Could not infer owner/repo from git remote."
    echo "Usage: $0 owner/repo [workflow_file] [branch]"
    exit 1
  fi
fi

python3 - "$REPO" "$WORKFLOW" "$BRANCH" <<'PY'
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request

repo, workflow, branch = sys.argv[1:4]
base = f"https://api.github.com/repos/{repo}/actions/workflows/{workflow}/runs"
query = urllib.parse.urlencode({
    "branch": branch,
    "event": "push",
    "status": "completed",
    "per_page": 100,
})
url = f"{base}?{query}"

headers = {
    "Accept": "application/vnd.github+json",
    "X-GitHub-Api-Version": "2022-11-28",
}
token = os.getenv("GH_TOKEN")
if token:
    headers["Authorization"] = f"Bearer {token}"

req = urllib.request.Request(url, headers=headers)
try:
    with urllib.request.urlopen(req, timeout=30) as resp:
        payload = json.load(resp)
except urllib.error.HTTPError as exc:
    body = exc.read().decode("utf-8", errors="replace")
    print(f"ERROR: GitHub API request failed ({exc.code}): {body[:300]}")
    sys.exit(1)
except Exception as exc:
    print(f"ERROR: GitHub API request failed: {exc}")
    sys.exit(1)

runs = payload.get("workflow_runs", [])
if not runs:
    print("No completed push runs found for this workflow/branch.")
    sys.exit(1)

recent_failures = []
last_green = None
for run in runs:
    concl = run.get("conclusion")
    if concl == "success":
        last_green = run
        break
    if concl == "failure":
        recent_failures.append(run)

if last_green is None:
    print("No successful run found in the fetched window (last 100 runs).")
    sys.exit(1)

if not recent_failures:
    print("Latest run is green (no current failure streak found).")
    print(f"Last green SHA: {last_green.get('head_sha')} ({last_green.get('html_url')})")
    sys.exit(0)

first_red = recent_failures[-1]

base_sha = last_green.get("head_sha")
head_sha = first_red.get("head_sha")
compare_url = f"https://github.com/{repo}/compare/{base_sha}...{head_sha}"

print(f"Repository:     {repo}")
print(f"Workflow:       {workflow}")
print(f"Branch:         {branch}")
print()
print("Last green run:")
print(f"  id:           {last_green.get('id')}")
print(f"  date:         {last_green.get('created_at')}")
print(f"  sha:          {base_sha}")
print(f"  url:          {last_green.get('html_url')}")
print()
print("First red run after that green:")
print(f"  id:           {first_red.get('id')}")
print(f"  date:         {first_red.get('created_at')}")
print(f"  sha:          {head_sha}")
print(f"  url:          {first_red.get('html_url')}")
print()
print(f"Compare commits: {compare_url}")
PY
