#!/bin/bash
set -euo pipefail

BODY_FILE="${1:-report.md}"

if [[ ! -f "$BODY_FILE" ]]; then
  echo "[WARN] Report file not found: $BODY_FILE. Skipping Gitea issue creation."
  exit 0
fi

# If report says no files or no findings, you may decide NOT to create an issue.
#HAS_FINDINGS=$(grep -E "Total findings: [1-9][0-9]*" -i "$BODY_FILE" || true)
HAS_FINDINGS=$(cat report.md | grep "Total findings\*\*" | grep -v ": 0" || true)
if [[ -z "$HAS_FINDINGS" ]]; then
  echo "[INFO] No findings detected. Not creating a Gitea issue."
  exit 0
fi

: "${GITEA_API_URL:?Missing GITEA_API_URL}"
: "${GITEA_API_KEY:?Missing GITEA_API_KEY}"
: "${GITEA_AGENT:?Missing GITEA_AGENT}"
# GITEA_REPO_OWNER=$(git remote show origin | grep "^  Fetch" | cut -f 4 -d '/')
# echo "Will report issue to: [$GITEA_REPO_OWNER]"

# Parse owner/repo from GIT_URL
: "${GIT_URL:?Missing GIT_URL in Jenkins env}"
# Handle formats: https://gitea.example.com/owner/repo.git or git@gitea.example.com:owner/repo.git
OWNER=""
REPO=""
if [[ "$GIT_URL" =~ [:\/]([^\/:]+)\/([^\/\.]+)(\.git)?$ ]]; then
  OWNER="${BASH_REMATCH[1]}"
  REPO="${BASH_REMATCH[2]}"
fi
if [[ -z "$OWNER" || -z "$REPO" ]]; then
  echo "[ERROR] Could not determine owner/repo from GIT_URL=$GIT_URL"
  exit 1
fi
echo "Will report issue to [$OWNER][$REPO]"

BRANCH="${BRANCH_NAME:-${GIT_BRANCH:-unknown}}"
SHA="${GIT_COMMIT:-unknown}"
SHORT_SHA="${SHA:0:7}"
JOB_URL="${BUILD_URL:-}"

TITLE="[security-scan] ${OWNER}/${REPO} @ ${BRANCH} (${SHORT_SHA})"
LABELS='["security-scan","ollama"]'

# Build JSON payload safely
BODY_JSON=$(jq -Rs . < "$BODY_FILE")
ASSIGNEES_JSON=$(jq -n --arg u "$GITEA_AGENT" 'if ($u|length) > 0 then [$u] else [] end')

PAYLOAD=$(jq -n --arg title "$TITLE" --argjson body "$BODY_JSON" --argjson labels "$LABELS" --argjson assignees "$ASSIGNEES_JSON" \
  '{title:$title, body:$body, labels:$labels, assignees:$assignees}')

PAYLOAD=$(jq -n --arg title "$TITLE" --argjson body "$BODY_JSON" --argjson labels "$LABELS" --argjson assignees "$ASSIGNEES_JSON" \
  '{title:$title, body:$body}')

#DEBUG
API_URL="${GITEA_API_URL%/}/repos/${OWNER}/${REPO}/issues"
echo "[INFO] Creating Gitea issue at ${API_URL} [$GITEA_API_KEY]"
echo "[DEBUG] PAYLOAD=[$PAYLOAD]"

# Gitea supports "token" auth header
RESP=$(curl -sS -X POST "$API_URL" \
  -H "Authorization: token $GITEA_API_KEY" \
  -H "Content-Type: application/json" \
  -d "$PAYLOAD")

ISSUE_NUM=$(echo "$RESP" | jq -r '.number // empty')

if [[ -n "$ISSUE_NUM" ]]; then
  echo "[OK] Created issue #$ISSUE_NUM"
else
  echo "[ERROR] Failed to create issue. Response:"
  echo "$RESP"
  exit 1
fi