#!/bin/bash

# === SOMA-CORE GitHub Project Automation Setup ===
# This script sets up automated card creation for the SOMA++ project board

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}🚀 SOMA-CORE GitHub Project Automation Setup${NC}"
echo "=============================================="

# Configuration file path
CONFIG_FILE="$(dirname "$0")/config.env"

# === FUNCTION: Create config template ===
create_config_template() {
    cat > "$CONFIG_FILE" << 'EOF'
# === SOMA-CORE GitHub Project Configuration ===
# Copy this to config.env and fill in your values

# GitHub Personal Access Token (requires 'repo' and 'project' scopes)
# Get one at: https://github.com/settings/tokens
GITHUB_TOKEN="ghp_your_token_here"

# GitHub username
GITHUB_USERNAME="diegorhoger"

# Repository name
GITHUB_REPO="soma-core"

# Project ID (v2) - will be auto-detected if not provided
GITHUB_PROJECT_ID=""

# Default labels for created issues
DEFAULT_LABELS="soma++,operator,enhancement"

# Issue template directory
ISSUE_TEMPLATE_DIR="./issue-templates"
EOF
}

# === FUNCTION: Validate GitHub Token ===
validate_token() {
    local token="$1"
    echo -e "${YELLOW}🔍 Validating GitHub token...${NC}"
    
    response=$(curl -s -H "Authorization: token $token" \
        https://api.github.com/user)
    
    if echo "$response" | jq -e '.login' > /dev/null 2>&1; then
        username=$(echo "$response" | jq -r '.login')
        echo -e "${GREEN}✅ Token valid for user: $username${NC}"
        return 0
    else
        echo -e "${RED}❌ Invalid GitHub token${NC}"
        return 1
    fi
}

# === FUNCTION: Get Project ID ===
get_project_id() {
    local token="$1"
    local username="$2"
    
    echo -e "${YELLOW}🔍 Fetching GitHub projects...${NC}"
    
    query='query { viewer { projectsV2(first: 20) { nodes { id title url } } } }'
    
    response=$(curl -s -H "Authorization: bearer $token" \
        -X POST -d "{\"query\": \"$query\"}" \
        https://api.github.com/graphql)
    
    echo -e "${BLUE}📋 Available Projects:${NC}"
    echo "$response" | jq -r '.data.viewer.projectsV2.nodes[] | "  - \(.title) (\(.id))"'
    
    # Look for SOMA++ project
    soma_project=$(echo "$response" | jq -r '.data.viewer.projectsV2.nodes[] | select(.title | test("SOMA"; "i")) | .id')
    
    if [[ -n "$soma_project" && "$soma_project" != "null" ]]; then
        echo -e "${GREEN}✅ Found SOMA project: $soma_project${NC}"
        echo "$soma_project"
    else
        echo -e "${YELLOW}⚠️  SOMA project not found automatically${NC}"
        echo ""
    fi
}

# === MAIN SETUP ===
main() {
    echo -e "${BLUE}Setting up GitHub automation for SOMA-CORE...${NC}"
    
    # Create scripts directory if it doesn't exist
    mkdir -p "$(dirname "$0")"
    
    # Check if config exists
    if [[ ! -f "$CONFIG_FILE" ]]; then
        echo -e "${YELLOW}📝 Creating config template...${NC}"
        create_config_template
        echo -e "${GREEN}✅ Config template created at: $CONFIG_FILE${NC}"
        echo -e "${YELLOW}Please edit $CONFIG_FILE with your GitHub token and run this script again.${NC}"
        exit 0
    fi
    
    # Load configuration
    source "$CONFIG_FILE"
    
    # Validate required variables
    if [[ -z "$GITHUB_TOKEN" || "$GITHUB_TOKEN" == "ghp_your_token_here" ]]; then
        echo -e "${RED}❌ Please set GITHUB_TOKEN in $CONFIG_FILE${NC}"
        exit 1
    fi
    
    # Validate token
    if ! validate_token "$GITHUB_TOKEN"; then
        exit 1
    fi
    
    # Get or validate project ID
    if [[ -z "$GITHUB_PROJECT_ID" ]]; then
        echo -e "${YELLOW}🔍 Project ID not set, attempting to find it...${NC}"
        project_id=$(get_project_id "$GITHUB_TOKEN" "$GITHUB_USERNAME")
        
        if [[ -n "$project_id" ]]; then
            # Update config file with found project ID
            sed -i.bak "s/GITHUB_PROJECT_ID=\"\"/GITHUB_PROJECT_ID=\"$project_id\"/" "$CONFIG_FILE"
            echo -e "${GREEN}✅ Updated config with project ID: $project_id${NC}"
        else
            echo -e "${YELLOW}⚠️  Please manually set GITHUB_PROJECT_ID in $CONFIG_FILE${NC}"
        fi
    fi
    
    echo -e "${GREEN}🎉 Setup complete! You can now run the automation scripts.${NC}"
}

# Run if executed directly
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi 