#!/bin/bash

# === SOMA-CORE GitHub Project Card Creator (Bash 3.2 Compatible) ===
# 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 (Array Format) ===
# Format: "title|description"

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

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

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

    # Escape the body for JSON
    local escaped_body=$(echo "$issue_body" | sed 's/"/\\"/g' | sed ':a;N;$!ba;s/\n/\\n/g')
    
    # 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\": \"$escaped_body\",
            \"labels\": [\"$(echo "$labels" | sed 's/,/", "/g')\"]
        }")
    
    # Extract node_id for project addition
    local node_id=$(echo "$response" | grep -o '"node_id":"[^"]*"' | cut -d'"' -f4)
    local issue_number=$(echo "$response" | grep -o '"number":[0-9]*' | cut -d':' -f2)
    
    if [[ -n "$node_id" && "$node_id" != "null" ]]; then
        log_success "Created issue #$issue_number"
        echo "$node_id"
    else
        log_error "Failed to create issue: $title"
        echo "$response" >&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\": \"$query\"}")
    
    if echo "$response" | grep -q '"item":{"id"'; then
        log_success "Added to project: $title"
    else
        log_error "Failed to add to project: $title"
        echo "$response" >&2
    fi
}

# === FUNCTION: Process Task Group ===
process_task_group() {
    local -a tasks_ref=("$@")
    local group_name="$1"
    local group_labels="$2"
    shift 2
    local tasks=("$@")
    
    echo -e "\n${BLUE}📂 Processing $group_name${NC}"
    echo "=================================="
    
    for item in "${tasks[@]}"; do
        title=$(echo "$item" | cut -d'|' -f1)
        description=$(echo "$item" | cut -d'|' -f2)
        
        # 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 1
        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 SOMA Operators" "$DEFAULT_LABELS,core-operator" "${CORE_OPERATORS[@]}"
    process_task_group "Edit Control Enhancement" "$DEFAULT_LABELS,edit-control" "${EDIT_CONTROL_TASKS[@]}"
    process_task_group "Workflow Integration" "$DEFAULT_LABELS,workflow,integration" "${WORKFLOW_INTEGRATION[@]}"
    
    show_summary
}

# === CLI OPTIONS ===
case "${1:-}" in
    --operators-only)
        echo -e "${BLUE}🔧 Creating Core Operators only${NC}"
        process_task_group "Core SOMA Operators" "$DEFAULT_LABELS,core-operator" "${CORE_OPERATORS[@]}"
        show_summary
        ;;
    --edit-control-only)
        echo -e "${BLUE}📝 Creating Edit Control tasks only${NC}"
        process_task_group "Edit Control Enhancement" "$DEFAULT_LABELS,edit-control" "${EDIT_CONTROL_TASKS[@]}"
        show_summary
        ;;
    --workflow-only)
        echo -e "${BLUE}🔄 Creating Workflow Integration tasks only${NC}"
        process_task_group "Workflow Integration" "$DEFAULT_LABELS,workflow,integration" "${WORKFLOW_INTEGRATION[@]}"
        show_summary
        ;;
    --help|-h)
        echo "SOMA-CORE GitHub Project Card Creator (Bash 3.2 Compatible)"
        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 