#!/bin/bash

# Script to check if i-ayushh18 is a collaborator on repositories
# Uses accounts.json for authentication tokens

set -euo pipefail

# Color definitions
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[0;34m'
readonly CYAN='\033[0;36m'
readonly BOLD='\033[1m'
readonly NC='\033[0m' # No Color

USER_TO_CHECK="i-ayushh18"
REPOS_FILE="repos.txt"
ACCOUNTS_FILE="accounts.json"

# Function to log messages
log_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

log_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

log_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

log_error() {
    echo -e "${RED}❌ $1${NC}"
}

log_header() {
    echo -e "\n${BOLD}${CYAN}$1${NC}"
    echo -e "${CYAN}$(printf '=%.0s' {1..60})${NC}"
}

# Check required files
if [[ ! -f "$REPOS_FILE" ]]; then
    log_error "Repository list file '$REPOS_FILE' not found"
    exit 1
fi

if [[ ! -f "$ACCOUNTS_FILE" ]]; then
    log_error "Accounts file '$ACCOUNTS_FILE' not found"
    exit 1
fi

# Get GitHub token from accounts.json
GITHUB_TOKEN=$(jq -r '.[0].token' "$ACCOUNTS_FILE")
GITHUB_USER=$(jq -r '.[0].user' "$ACCOUNTS_FILE")

if [[ -z "$GITHUB_TOKEN" || "$GITHUB_TOKEN" == "null" ]]; then
    log_error "Could not extract GitHub token from accounts.json"
    exit 1
fi

log_info "Using GitHub account: $GITHUB_USER"

# Function to check if user is a collaborator on a repository
check_collaboration() {
    local repo="$1"
    
    # Validate repository name format
    if [[ ! "$repo" =~ ^[a-zA-Z0-9._-]+/[a-zA-Z0-9._-]+$ ]]; then
        log_warning "Invalid repository name format: $repo"
        return 1
    fi
    
    local response
    response=$(curl -s -w "%{http_code}" -H "Authorization: token $GITHUB_TOKEN" \
        "https://api.github.com/repos/$repo/collaborators/$USER_TO_CHECK")
    
    local http_code="${response: -3}"
    
    case "$http_code" in
        204)
            return 0  # User is a collaborator
            ;;
        404)
            return 1  # User is not a collaborator
            ;;
        403)
            log_warning "Access forbidden for $repo - may not have admin permissions"
            return 1
            ;;
        401)
            log_error "Authentication failed - token may be invalid or expired"
            return 1
            ;;
        *)
            log_warning "Failed to check collaboration status for $USER_TO_CHECK on $repo (HTTP: $http_code)"
            return 1
            ;;
    esac
}

# Main execution
log_header "Checking collaborator status for $USER_TO_CHECK"

# Read repositories from file
if [[ ! -s "$REPOS_FILE" ]]; then
    log_error "Repository file '$REPOS_FILE' is empty"
    exit 1
fi

collaborator_repos=()
total_repos=0
checked_repos=0

# Count total repositories
total_repos=$(wc -l < "$REPOS_FILE")
log_info "Found $total_repos repositories to check"

log_header "Checking Repositories"

# Check each repository
while IFS= read -r repo; do
    # Skip empty lines
    [[ -z "$repo" ]] && continue
    
    ((checked_repos++))
    printf "\r${CYAN}Progress: [%3d%%] %d/%d repositories checked${NC}" \
        $((checked_repos * 100 / total_repos)) "$checked_repos" "$total_repos"
    
    if check_collaboration "$repo"; then
        collaborator_repos+=("$repo")
        echo # New line after progress
        log_success "$USER_TO_CHECK is a collaborator on: $repo"
    fi
done < "$REPOS_FILE"

echo # New line after progress

# Show results
log_header "Results Summary"

if [[ ${#collaborator_repos[@]} -eq 0 ]]; then
    log_info "✨ $USER_TO_CHECK is not a collaborator on any of the $total_repos repositories checked"
    echo -e "${GREEN}No repositories found where $USER_TO_CHECK has collaborator access.${NC}"
else
    log_success "$USER_TO_CHECK is a collaborator on ${#collaborator_repos[@]} out of $total_repos repositories:"
    echo
    for repo in "${collaborator_repos[@]}"; do
        echo -e "${YELLOW}• $repo${NC}"
    done
    
    # Save results to file
    results_file="collaborator_repos_${USER_TO_CHECK}.txt"
    printf '%s\n' "${collaborator_repos[@]}" > "$results_file"
    log_info "Results saved to: $results_file"
fi

log_header "Operation Complete"
echo -e "${GREEN}Finished checking $total_repos repositories for $USER_TO_CHECK collaborator status${NC}"