#!/usr/bin/env bash
# Resolve a single team from config/teams.json without loading the full file.
# Usage:
#   bash scripts/get-team-config.sh --team raccoon [--format env|json]
set -euo pipefail

team=""
format="json"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --team)    team="$2";   shift 2 ;;
    --format)  format="$2"; shift 2 ;;
    *) echo "ERROR: unknown arg: $1" >&2; exit 2 ;;
  esac
done

if [ -z "$team" ]; then
  echo "ERROR: provide --team" >&2
  exit 2
fi

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
teams_file="$script_dir/../config/teams.json"

result="$(jq -c --arg t "$team" '
  to_entries
  | map(select(.key | startswith("_") | not))
  | map(select(
      (.key | ascii_downcase) == ($t | ascii_downcase) or
      (.value.name // "" | ascii_downcase) == ($t | ascii_downcase) or
      (.value.aliases // [] | map(ascii_downcase) | contains([$t | ascii_downcase]))
    ))
  | first
  // null
' "$teams_file")"

if [ "$result" = "null" ]; then
  echo "ERROR: team not found for input '$team'" >&2
  exit 1
fi

team_key="$(jq -r '.key' <<<"$result")"
cfg="$(jq -c '.value' <<<"$result")"
project_key="$(jq -r '.project_key // .name // "'"$team_key"'"' <<<"$cfg")"
name="$(jq -r '.name // "'"$team_key"'"' <<<"$cfg")"
members="$(jq -r '[.members // [] | .[] | if type == "object" then (.github // "") else . end] | map(select(length > 0)) | unique | join(",")' <<<"$cfg")"

if [ "$format" = "env" ]; then
  echo "TEAM_KEY=$team_key"
  echo "PROJECT_KEY=$project_key"
  printf 'TEAM_NAME=%q\n' "$name"
  echo "MATCHED_BY=matched"
  echo "TEAM_GITHUB_MEMBERS=$members"
  exit 0
fi

jq -n \
  --arg input "$team" \
  --arg team_key "$team_key" \
  --arg project_key "$project_key" \
  --arg name "$name" \
  --arg members "$members" \
  '{input: $input, team_key: $team_key, project_key: $project_key, name: $name, member_logins: ($members | split(",") | map(select(length > 0)))}'
