#!/usr/bin/env bash
# Credential loader for the Azure DevOps skills. Source it; do not execute it.
#
#   source "<skill>/scripts/load_env.sh"
#   require_azure
#
# Sets (and never prints): PAT, ORG, PROJECT
#
# Lookup order, first non-empty value wins:
#   1. variables already exported in the shell
#   2. $ROOT/.env
#   3. $ROOT/azure.env
#
# ROOT is the git toplevel of the current directory (or the current directory
# outside a repo). Set ROOT before sourcing to point somewhere else.
#
# Expected keys (placeholders, never commit real values):
#   AZURE_PAT=<your-pat>
#   AZURE_ORG=<org>          (AZURE_ORGANIZATION is accepted too)
#   AZURE_PROJECT=<project>
#
# Both .env and azure.env must be in .gitignore.

if [[ -z "${ROOT:-}" ]]; then
  ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
fi

_read_kv() {   # $1 = file, $2 = key ; prints the value or nothing
  local file="$1" key="$2" line=""
  [[ -f "$file" ]] || return 0
  line="$(grep -E "^[[:space:]]*(export[[:space:]]+)?${key}[[:space:]]*=" "$file" 2>/dev/null | head -n1 || true)"
  [[ -n "$line" ]] || return 0
  printf '%s' "${line#*=}" | tr -d '\r' \
    | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' \
          -e 's/^"//' -e 's/"$//' -e "s/^'//" -e "s/'$//"
}

_first_nonempty() {
  local v
  for v in "$@"; do
    if [[ -n "${v:-}" ]]; then printf '%s' "$v"; return 0; fi
  done
  return 0
}

_env_lookup() {   # $1.. = candidate keys ; env first, then .env, then azure.env
  local key file
  for key in "$@"; do
    if [[ -n "${!key:-}" ]]; then printf '%s' "${!key}"; return 0; fi
  done
  for file in "$ROOT/.env" "$ROOT/azure.env"; do
    for key in "$@"; do
      local v
      v="$(_read_kv "$file" "$key")"
      if [[ -n "$v" ]]; then printf '%s' "$v"; return 0; fi
    done
  done
  return 0
}

PAT="$(_env_lookup AZURE_PAT)"
ORG="$(_env_lookup AZURE_ORG AZURE_ORGANIZATION)"
PROJECT="$(_env_lookup AZURE_PROJECT)"

require_azure() {
  local missing=()
  [[ -n "${PAT:-}" ]]     || missing+=(AZURE_PAT)
  [[ -n "${ORG:-}" ]]     || missing+=(AZURE_ORG)
  [[ -n "${PROJECT:-}" ]] || missing+=(AZURE_PROJECT)
  if [[ ${#missing[@]} -gt 0 ]]; then
    echo "ERROR: missing Azure DevOps settings: ${missing[*]}" >&2
    echo "Export them or add them to $ROOT/.env (placeholders: <org>, <project>, <your-pat>)." >&2
    echo "Scopes: Work Items (Read) to read; Work Items (Read & Write) to attach or update." >&2
    return 1
  fi
  # URL-encode spaces in the project name: the REST paths take it raw.
  PROJECT_URL="${PROJECT// /%20}"
  BASE_URL="https://dev.azure.com/$ORG/$PROJECT_URL"
}

# Guard against the classic expired-PAT trap: Azure DevOps answers 200 with an
# HTML sign-in page instead of 401. Call it on every response body.
assert_json() {   # $1 = body, $2 = context
  case "${1#"${1%%[![:space:]]*}"}" in
    '{'*|'['*) return 0 ;;
  esac
  echo "ERROR: $2 did not return JSON (expired PAT or wrong org/project?)." >&2
  return 1
}
