#!/bin/bash

# === SOMA-CORE GitHub Automation Quick Start ===
# One-command setup for GitHub project automation

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m'

clear

echo -e "${PURPLE}"
cat << 'EOF'
 ███████╗ ██████╗ ███╗   ███╗ █████╗       ██████╗ ██████╗ ██████╗ ███████╗
 ██╔════╝██╔═══██╗████╗ ████║██╔══██╗     ██╔════╝██╔═══██╗██╔══██╗██╔════╝
 ███████╗██║   ██║██╔████╔██║███████║     ██║     ██║   ██║██████╔╝█████╗  
 ╚════██║██║   ██║██║╚██╔╝██║██╔══██║     ██║     ██║   ██║██╔══██╗██╔══╝  
 ███████║╚██████╔╝██║ ╚═╝ ██║██║  ██║     ╚██████╗╚██████╔╝██║  ██║███████╗
 ╚══════╝ ╚═════╝ ╚═╝     ╚═╝╚═╝  ╚═╝      ╚═════╝ ╚═════╝ ╚═╝  ╚═╝╚══════╝
                                                                              
EOF
echo -e "${NC}"

echo -e "${BLUE}🚀 GitHub Project Automation Quick Start${NC}"
echo -e "${CYAN}=========================================${NC}"
echo ""
echo -e "${GREEN}Welcome to SOMA-CORE GitHub automation setup!${NC}"
echo -e "${YELLOW}This script will help you set up automated project card creation.${NC}"
echo ""

# Check prerequisites
echo -e "${BLUE}🔍 Checking prerequisites...${NC}"

# Check for required tools
missing_tools=()

if ! command -v curl &> /dev/null; then
    missing_tools+=("curl")
fi

if ! command -v jq &> /dev/null; then
    missing_tools+=("jq")
fi

if ! command -v git &> /dev/null; then
    missing_tools+=("git")
fi

if [ ${#missing_tools[@]} -ne 0 ]; then
    echo -e "${RED}❌ Missing required tools: ${missing_tools[*]}${NC}"
    echo -e "${YELLOW}Please install the missing tools and run this script again.${NC}"
    echo ""
    echo -e "${BLUE}Installation commands:${NC}"
    echo -e "${CYAN}# macOS (using Homebrew):${NC}"
    echo "brew install curl jq git"
    echo ""
    echo -e "${CYAN}# Ubuntu/Debian:${NC}"  
    echo "sudo apt-get install curl jq git"
    echo ""
    echo -e "${CYAN}# CentOS/RHEL:${NC}"
    echo "sudo yum install curl jq git"
    exit 1
fi

echo -e "${GREEN}✅ All prerequisites installed${NC}"

# Check if we're in the right directory
if [[ ! -f "../../Cargo.toml" ]] || [[ ! -d "../../src" ]]; then
    echo -e "${RED}❌ This script should be run from the scripts/github-automation directory${NC}"
    echo -e "${YELLOW}Current directory: $(pwd)${NC}"
    echo -e "${YELLOW}Please navigate to the correct directory and try again.${NC}"
    exit 1
fi

echo -e "${GREEN}✅ Running from correct directory${NC}"

# Interactive setup
echo ""
echo -e "${BLUE}📝 Interactive Setup${NC}"
echo -e "${CYAN}===================${NC}"

# Get GitHub token
echo ""
echo -e "${YELLOW}🔑 GitHub Personal Access Token${NC}"
echo -e "${CYAN}We need a GitHub token with 'repo' and 'project' scopes.${NC}"
echo ""
echo -e "${BLUE}To create a token:${NC}"
echo "1. Go to: https://github.com/settings/tokens"
echo "2. Click 'Generate new token (classic)'"
echo "3. Select scopes: repo, project"
echo "4. Copy the generated token"
echo ""

read -p "$(echo -e ${YELLOW}Enter your GitHub token: ${NC})" GITHUB_TOKEN

if [[ -z "$GITHUB_TOKEN" || "$GITHUB_TOKEN" == "ghp_"* && ${#GITHUB_TOKEN} -lt 10 ]]; then
    echo -e "${RED}❌ Invalid token format${NC}"
    exit 1
fi

# Validate token
echo ""
echo -e "${BLUE}🔍 Validating token...${NC}"

response=$(curl -s -H "Authorization: token $GITHUB_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}"
else
    echo -e "${RED}❌ Token validation failed${NC}"
    echo -e "${YELLOW}Response: $response${NC}"
    exit 1
fi

# Get project information
echo ""
echo -e "${BLUE}🔍 Finding GitHub projects...${NC}"

query='query { viewer { projectsV2(first: 20) { nodes { id title url } } } }'
project_response=$(curl -s -H "Authorization: bearer $GITHUB_TOKEN" \
    -X POST -d "{\"query\": \"$query\"}" \
    https://api.github.com/graphql)

if echo "$project_response" | jq -e '.data.viewer.projectsV2.nodes' > /dev/null 2>&1; then
    echo -e "${GREEN}✅ Successfully fetched projects${NC}"
    
    # Show available projects
    echo -e "${CYAN}Available projects:${NC}"
    echo "$project_response" | jq -r '.data.viewer.projectsV2.nodes[] | "  - \(.title) (\(.id))"'
    
    # Look for SOMA project
    soma_project=$(echo "$project_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}"
        PROJECT_ID="$soma_project"
    else
        echo -e "${YELLOW}⚠️  No SOMA project found automatically${NC}"
        echo ""
        read -p "$(echo -e ${YELLOW}Enter your project ID manually (optional): ${NC})" PROJECT_ID
    fi
else
    echo -e "${YELLOW}⚠️  Could not fetch projects (will create issues without project assignment)${NC}"
    PROJECT_ID=""
fi

# Create configuration
echo ""
echo -e "${BLUE}📝 Creating configuration...${NC}"

cat > config.env << EOF
# === SOMA-CORE GitHub Project Configuration ===
# Generated by quick-start.sh on $(date)

# GitHub Personal Access Token
GITHUB_TOKEN="$GITHUB_TOKEN"

# GitHub username
GITHUB_USERNAME="$username"

# Repository name
GITHUB_REPO="soma-core"

# Project ID (auto-detected)
GITHUB_PROJECT_ID="$PROJECT_ID"

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

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

echo -e "${GREEN}✅ Configuration saved to config.env${NC}"

# Ask about immediate creation
echo ""
echo -e "${BLUE}🚀 Ready to create project cards!${NC}"
echo -e "${CYAN}===============================${NC}"
echo ""
echo -e "${YELLOW}The system will create GitHub issues for:${NC}"
echo "• 6 Core SOMA Operators"
echo "• 6 Edit Control Enhancement tasks"  
echo "• 4 Workflow Integration tasks"
echo ""
echo -e "${GREEN}Total: 16 issues${NC}"
echo ""

read -p "$(echo -e ${YELLOW}Create all project cards now? [y/N]: ${NC})" -n 1 -r
echo

if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo ""
    echo -e "${BLUE}🔄 Creating project cards...${NC}"
    
    # Run the card creation script
    if ./create-cards.sh; then
        echo ""
        echo -e "${GREEN}🎉 Success! All project cards created.${NC}"
        
        # Show next steps
        echo ""
        echo -e "${BLUE}📋 Next Steps:${NC}"
        echo -e "${CYAN}=============${NC}"
        echo "1. Check your GitHub repository issues tab"
        if [[ -n "$PROJECT_ID" ]]; then
            echo "2. View your project board for the new cards"
        fi
        echo "3. Organize cards in your project columns as needed"
        echo "4. Start working on your SOMA-CORE development!"
        echo ""
        echo -e "${BLUE}🔄 Future Updates:${NC}"
        echo "• Run ./create-cards.sh anytime to add new tasks"
        echo "• GitHub Actions will auto-sync when you update plan.md"
        echo "• Use ./create-cards.sh --help for more options"
        
    else
        echo -e "${RED}❌ Error creating cards. Check the output above.${NC}"
        exit 1
    fi
else
    echo ""
    echo -e "${GREEN}✅ Setup complete!${NC}"
    echo ""
    echo -e "${BLUE}📋 Manual Creation:${NC}"
    echo -e "${CYAN}=================${NC}"
    echo "Run these commands when ready:"
    echo ""
    echo -e "${CYAN}# Create all cards${NC}"
    echo "./create-cards.sh"
    echo ""
    echo -e "${CYAN}# Create specific groups${NC}"
    echo "./create-cards.sh --operators-only"
    echo "./create-cards.sh --edit-control-only" 
    echo "./create-cards.sh --workflow-only"
    echo ""
    echo -e "${CYAN}# Get help${NC}"
    echo "./create-cards.sh --help"
fi

echo ""
echo -e "${PURPLE}═══════════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}🎉 SOMA-CORE GitHub Automation Setup Complete!${NC}"
echo -e "${PURPLE}═══════════════════════════════════════════════════════════════${NC}"
echo ""
echo -e "${BLUE}📚 Documentation:${NC} See README.md for detailed usage"
echo -e "${BLUE}🐛 Issues:${NC} Check troubleshooting section in README.md"
echo -e "${BLUE}🔧 Configuration:${NC} Edit config.env to modify settings"
echo ""
echo -e "${CYAN}Happy coding with SOMA-CORE! 🚀${NC}" 