#!/usr/bin/env bash
# Usage: bash pr.sh "PR title" "PR body"
# Loads GITEA_TOKEN from .env automatically

set -euo pipefail

# Load .env if GITEA_TOKEN not already exported
if [ -z "${GITEA_TOKEN:-}" ] && [ -f .env ]; then
  set -a
  source .env
  set +a
fi

GITEA_URL="${GITEA_URL:-http://10.0.0.194:3012}"
REPO="${GITEA_OWNER:-michal}/mcpctl"

TITLE="${1:?Usage: pr.sh <title> [body]}"
BODY="${2:-}"
BASE="${3:-main}"
HEAD=$(git rev-parse --abbrev-ref HEAD)

if [ "$HEAD" = "$BASE" ]; then
  echo "Error: already on $BASE, switch to a feature branch first" >&2
  exit 1
fi

if [ -z "${GITEA_TOKEN:-}" ]; then
  echo "Error: GITEA_TOKEN not set and .env not found" >&2
  exit 1
fi

# Push if needed
if ! git rev-parse --verify "origin/$HEAD" &>/dev/null; then
  git push -u origin "$HEAD"
else
  git push
fi

# Create PR
RESPONSE=$(curl -s -X POST "$GITEA_URL/api/v1/repos/$REPO/pulls" \
  -H "Authorization: token $GITEA_TOKEN" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --arg t "$TITLE" --arg b "$BODY" --arg h "$HEAD" --arg base "$BASE" \
    '{title: $t, body: $b, head: $h, base: $base}')")

PR_NUM=$(echo "$RESPONSE" | jq -r '.number // empty')
PR_URL=$(echo "$RESPONSE" | jq -r '.html_url // empty')

if [ -z "$PR_NUM" ]; then
  echo "Error creating PR:" >&2
  echo "$RESPONSE" | jq . 2>/dev/null || echo "$RESPONSE" >&2
  exit 1
fi

echo "PR #$PR_NUM: https://mysources.co.uk/$REPO/pulls/$PR_NUM"
