#!/bin/bash

# Check for required tools
for tool in jq curl; do
    if ! command -v $tool &>/dev/null; then
        echo "Error: Required tool '$tool' is not installed." >&2
        exit 1
    fi
done

if [[ -z "$GITHUB_TOKEN" ]]; then
    echo "Error: GITHUB_TOKEN is not set in your environment." >&2
    exit 1
fi

# Get authenticated user
AUTH_USER=$(curl -s -H "Authorization: token $GITHUB_TOKEN" https://api.github.com/user | jq -r '.login')
if [[ -z "$AUTH_USER" || "$AUTH_USER" == "null" ]]; then
    echo "Error: Could not determine authenticated user. Check your GITHUB_TOKEN." >&2
    exit 1
fi

echo "User: $AUTH_USER"
echo "|"
echo "|-- [User Repos]"

USER_REPOS=$(curl -s -H "Authorization: token $GITHUB_TOKEN" "https://api.github.com/user/repos?per_page=100&type=owner" | jq -r '.[] | "    |-- \(.name) (https://github.com/\(.full_name))"')
if [[ -n "$USER_REPOS" ]]; then
    echo "$USER_REPOS"
else
    echo "    |-- (No user-owned repos found)"
fi

echo "|"
echo "|-- [Organizations]"

ORGS=$(curl -s -H "Authorization: token $GITHUB_TOKEN" "https://api.github.com/user/orgs" | jq -r '.[].login')
if [[ -z "$ORGS" ]]; then
    echo "    |-- (No organizations found)"
    exit 0
fi

for ORG in $ORGS; do
    echo "    |-- $ORG"
    ORG_REPOS=$(curl -s -H "Authorization: token $GITHUB_TOKEN" "https://api.github.com/orgs/$ORG/repos?per_page=100" | jq -r '.[] | "        |-- \(.name) (https://github.com/\(.full_name))"')
    if [[ -n "$ORG_REPOS" ]]; then
        echo "$ORG_REPOS"
    else
        echo "        |-- (No repos found)"
    fi
done