#!/bin/bash

# === SOMA-CORE GitHub Project Card Creator ===
# Automatically creates issues and adds them to your GitHub project

set -e

# Get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_FILE="$SCRIPT_DIR/config.env"

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

# === LOAD CONFIGURATION ===
if [[ ! -f "$CONFIG_FILE" ]]; then
    echo -e "${RED}❌ Config file not found. Run setup.sh first.${NC}"
    exit 1
fi

source "$CONFIG_FILE"

# === SOMA OPERATORS & TASKS DATA ===
# Based on your plan.md and SOMA-CORE architecture

declare -A CORE_OPERATORS=(
    ["IntrospectOperator"]="Operator for recursive self-diagnosis and phase awareness in multi-agent editing workflows"
    ["ConsensusOperator"]="Multi-agent edit agreement resolver across operations with conflict resolution"
    ["CognitiveLoadOperator"]="Estimates computational complexity of reasoning paths and edit proposal generation"  
    ["AttentionFocusOperator"]="Prioritizes high-salience context elements during ops execution and code analysis"
    ["VisualReasoningOperator"]="Converts image inputs into symbolic graph concepts for visual code understanding"
    ["MetaReflectiveOperator"]="Claude's signature operator for recursive system introspection and self-improvement"
)

declare -A EDIT_CONTROL_TASKS=(
    ["EditModificationInterface"]="Allow users to modify proposed edits before applying with inline editor capabilities"
    ["AdvancedPreviewSystem"]="Side-by-side editor view with live editing, syntax highlighting and error checking"
    ["GranularApprovalLevels"]="Implement approve with modifications, conditional approval, and queued processing"
    ["EditClassificationSystem"]="Auto-categorize edits (critical, safe, cosmetic, experimental) with risk scoring"
    ["StagedApplicationSystem"]="Apply edits in groups/phases with rollback capabilities and stable state bookmarking"
    ["FileProtectionConstraints"]="Mark files as read-only or critical with custom validation rules per file type"
)

declare -A WORKFLOW_INTEGRATION=(
    ["GitIntegration"]="Create branches per edit session with automated backup strategies and CI/CD hooks"
    ["ConditionalLogicSystem"]="Apply edits only if tests pass with user-defined success criteria"
    ["EditHistoryTimeTravel"]="Complete edit history with metadata, rollback to any point, branch and merge timelines"
    ["CustomAgentConfiguration"]="User-defined agent personalities/focus with behavior modification based on project context"
)

# === FUNCTIONS ===

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}"
}

# === FUNCTION: Create GitHub Issue ===
create_github_issue() {
    local title="$1"
    local body="$2"
    local labels="$3"
    
    log_info "Creating issue: $title"
    
    # Create issue body with SOMA-specific template
    local issue_body="## 🎯 SOMA-CORE Operator/Task

**Description:**
$body

## 📋 Implementation Checklist
- [ ] Research and design phase
- [ ] Core implementation
- [ ] Integration with existing system
- [ ] Testing and validation  
- [ ] Documentation update
- [ ] Performance benchmarks

## 🔗 Related
- Part of SOMA-CORE multi-agent editing system
- Linked to enhanced edit control roadmap
- Dependencies: Core edit control framework

## 🏷️ Labels
$labels

---
*Auto-generated by SOMA-CORE GitHub automation*"

    # Create the issue
    response=$(curl -s -X POST "https://api.github.com/repos/${GITHUB_USERNAME}/${GITHUB_REPO}/issues" \
        -H "Authorization: token ${GITHUB_TOKEN}" \
        -H "Accept: application/vnd.github+json" \
        -H "Content-Type: application/json" \
        -d "{
            \"title\": \"$title\",
            \"body\": $(echo "$issue_body" | jq -Rs .),
            \"labels\": [$(echo "$labels" | sed 's/,/","/g' | sed 's/^/"/; s/$/"/')]
        }")
    
    # Extract node_id for project addition
    local node_id=$(echo "$response" | jq -r '.node_id')
    local issue_number=$(echo "$response" | jq -r '.number')
    
    if [[ "$node_id" != "null" && -n "$node_id" ]]; then
        log_success "Created issue #$issue_number"
        echo "$node_id"
    else
        log_error "Failed to create issue: $title"
        echo "$response" | jq -r '.message // .errors[0].message // "Unknown error"' >&2
        return 1
    fi
}

# === FUNCTION: Add Issue to Project ===
add_to_project() {
    local issue_node_id="$1"
    local title="$2"
    
    if [[ -z "$GITHUB_PROJECT_ID" ]]; then
        log_warning "No project ID configured, skipping project addition for: $title"
        return 0
    fi
    
    log_info "Adding to project: $title"
    
    local query="mutation { 
        addProjectV2ItemById(input: {
            projectId: \"$GITHUB_PROJECT_ID\", 
            contentId: \"$issue_node_id\"
        }) { 
            item { id } 
        } 
    }"
    
    response=$(curl -s -X POST https://api.github.com/graphql \
        -H "Authorization: bearer ${GITHUB_TOKEN}" \
        -H "Content-Type: application/json" \
        -d "{\"query\": $(echo "$query" | jq -Rs .)}")
    
    if echo "$response" | jq -e '.data.addProjectV2ItemById.item.id' > /dev/null 2>&1; then
        log_success "Added to project: $title"
    else
        log_error "Failed to add to project: $title"
        echo "$response" | jq -r '.errors[0].message // "Unknown error"' >&2
    fi
}

# === FUNCTION: Process Task Group ===
process_task_group() {
    local -n tasks_ref=$1
    local group_name="$2"
    local group_labels="$3"
    
    echo -e "\n${BLUE}📂 Processing $group_name${NC}"
    echo "=================================="
    
    for title in "${!tasks_ref[@]}"; do
        description="${tasks_ref[$title]}"
        
        # Create issue
        node_id=$(create_github_issue "$title" "$description" "$group_labels")
        
        if [[ $? -eq 0 && -n "$node_id" ]]; then
            # Add to project
            add_to_project "$node_id" "$title"
            
            # Brief pause to avoid rate limiting
            sleep 0.5
        fi
    done
}

# === FUNCTION: Show Summary ===
show_summary() {
    echo -e "\n${GREEN}🎉 SOMA-CORE GitHub Automation Complete!${NC}"
    echo "============================================="
    echo -e "${BLUE}Repository:${NC} https://github.com/${GITHUB_USERNAME}/${GITHUB_REPO}"
    
    if [[ -n "$GITHUB_PROJECT_ID" ]]; then
        echo -e "${BLUE}Project Board:${NC} Check your GitHub projects page"
    fi
    
    echo -e "\n${YELLOW}📊 Created Issues:${NC}"
    echo "• $(( ${#CORE_OPERATORS[@]} )) Core SOMA Operators"
    echo "• $(( ${#EDIT_CONTROL_TASKS[@]} )) Edit Control Tasks"
    echo "• $(( ${#WORKFLOW_INTEGRATION[@]} )) Workflow Integration Tasks"
    echo -e "\n${GREEN}Total: $(( ${#CORE_OPERATORS[@]} + ${#EDIT_CONTROL_TASKS[@]} + ${#WORKFLOW_INTEGRATION[@]} )) issues created${NC}"
}

# === MAIN EXECUTION ===
main() {
    echo -e "${BLUE}🚀 SOMA-CORE GitHub Project Card Creator${NC}"
    echo "=========================================="
    
    # Validate configuration
    if [[ -z "$GITHUB_TOKEN" || -z "$GITHUB_USERNAME" || -z "$GITHUB_REPO" ]]; then
        log_error "Missing required configuration. Check config.env"
        exit 1
    fi
    
    # Create task groups
    process_task_group CORE_OPERATORS "Core SOMA Operators" "$DEFAULT_LABELS,core-operator"
    process_task_group EDIT_CONTROL_TASKS "Edit Control Enhancement" "$DEFAULT_LABELS,edit-control"
    process_task_group WORKFLOW_INTEGRATION "Workflow Integration" "$DEFAULT_LABELS,workflow,integration"
    
    show_summary
}

# === CLI OPTIONS ===
case "${1:-}" in
    --operators-only)
        echo -e "${BLUE}🔧 Creating Core Operators only${NC}"
        process_task_group CORE_OPERATORS "Core SOMA Operators" "$DEFAULT_LABELS,core-operator"
        ;;
    --edit-control-only)
        echo -e "${BLUE}📝 Creating Edit Control tasks only${NC}"
        process_task_group EDIT_CONTROL_TASKS "Edit Control Enhancement" "$DEFAULT_LABELS,edit-control"
        ;;
    --workflow-only)
        echo -e "${BLUE}🔄 Creating Workflow Integration tasks only${NC}"
        process_task_group WORKFLOW_INTEGRATION "Workflow Integration" "$DEFAULT_LABELS,workflow,integration"
        ;;
    --help|-h)
        echo "SOMA-CORE GitHub Project Card Creator"
        echo ""
        echo "Usage: $0 [OPTIONS]"
        echo ""
        echo "Options:"
        echo "  --operators-only     Create only core SOMA operators"
        echo "  --edit-control-only  Create only edit control tasks"
        echo "  --workflow-only      Create only workflow integration tasks"
        echo "  --help, -h           Show this help message"
        echo ""
        echo "Default: Creates all task groups"
        ;;
    "")
        main
        ;;
    *)
        log_error "Unknown option: $1"
        echo "Use --help for usage information"
        exit 1
        ;;
esac 