#!/bin/bash

if [ -z "$1" ]; then
  echo "Usage: $0 <path_to_accounts.json>"
  exit 1
fi

ACCOUNTS_FILE="$1"

# Check if accounts.json exists
if [ ! -f "$ACCOUNTS_FILE" ]; then
  echo "Error: $ACCOUNTS_FILE not found." >&2
  exit 1
fi

# Use a temporary directory to store repo lists for each contributor
TMP_DIR=$(mktemp -d)
trap 'rm -rf "$TMP_DIR"' EXIT

# Loop through each account in accounts.json
jq -c '.[]' "$ACCOUNTS_FILE" | while read -r account; do
  USER=$(echo "$account" | jq -r '.user')
  TOKEN=$(echo "$account" | jq -r '.token')

  # Get all repos for the user
  REPOS=$(curl -s -H "Authorization: token $TOKEN" "https://api.github.com/user/repos?type=all&per_page=100" | jq -r '.[].full_name')

  for REPO in $REPOS; do
    # Get contributors for each repo
    CONTRIBUTORS=$(curl -s -H "Authorization: token $TOKEN" "https://api.github.com/repos/$REPO/contributors" | jq -r '.[].login')

    for CONTRIBUTOR in $CONTRIBUTORS; do
      # Append the repo to the contributor's list
      echo "$REPO" >> "$TMP_DIR/$CONTRIBUTOR"
    done
  done
done

# Process the temporary files and print JSON to stdout
for contributor_file in "$TMP_DIR"/*; do
  CONTRIBUTOR_LOGIN=$(basename "$contributor_file")

  # Check if the temporary file is empty
  if [ ! -s "$contributor_file" ]; then
    continue
  fi

  # Sort and unique the repo list, then format as a JSON array
  JSON_CONTENT=$(sort -u "$contributor_file" | jq -R . | jq -s .)

  # Print the JSON content with a header for redirection
  echo "START_JSON:${CONTRIBUTOR_LOGIN}"
  echo "$JSON_CONTENT"
  echo "END_JSON:${CONTRIBUTOR_LOGIN}"
done