#!/bin/bash

# === SOMA-CORE GitHub Project Card Creator (Manual) ===
# Compatible with macOS bash 3.2

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'

# === 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"

log_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

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

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

# === FUNCTION: Create Single Issue ===
create_issue() {
    local title="$1"
    local description="$2"
    local label_group="$3"
    
    log_info "Creating issue: $title"
    
    # Create a temporary JSON file for the issue
    cat > /tmp/issue_payload.json << EOF
{
    "title": "$title",
    "body": "## 🎯 SOMA-CORE Operator/Task\n\n**Description:**\n$description\n\n## 📋 Implementation Checklist\n- [ ] Research and design phase\n- [ ] Core implementation\n- [ ] Integration with existing system\n- [ ] Testing and validation\n- [ ] Documentation update\n- [ ] Performance benchmarks\n\n## 🔗 Related\n- Part of SOMA-CORE multi-agent editing system\n- Linked to enhanced edit control roadmap\n- Dependencies: Core edit control framework\n\n## 🏷️ Labels\n$DEFAULT_LABELS,$label_group\n\n---\n*Auto-generated by SOMA-CORE GitHub automation*",
    "labels": ["soma++", "operator", "enhancement", "$label_group"]
}
EOF

    # 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 @/tmp/issue_payload.json)
    
    # Check if successful
    if echo "$response" | grep -q '"number":'; then
        issue_number=$(echo "$response" | grep -o '"number":[0-9]*' | cut -d':' -f2)
        log_success "Created issue #$issue_number: $title"
    else
        log_error "Failed to create issue: $title"
        echo "$response"
    fi
    
    # Clean up
    rm -f /tmp/issue_payload.json
    
    # Rate limiting pause
    sleep 1
}

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

echo -e "\n${BLUE}📂 Creating Core SOMA Operators${NC}"
echo "=================================="

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

echo -e "\n${BLUE}📂 Creating Edit Control Enhancement Tasks${NC}"
echo "=================================="

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

echo -e "\n${BLUE}📂 Creating Workflow Integration Tasks${NC}"
echo "=================================="

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

echo -e "\n${GREEN}🎉 SOMA-CORE GitHub Automation Complete!${NC}"
echo "============================================="
echo -e "${BLUE}Repository:${NC} https://github.com/${GITHUB_USERNAME}/${GITHUB_REPO}"
echo -e "${YELLOW}📊 Total Issues Created:${NC} 16"
echo "• 6 Core SOMA Operators"
echo "• 6 Edit Control Enhancement Tasks"
echo "• 4 Workflow Integration Tasks"
echo ""
echo -e "${GREEN}✅ Check your GitHub repository issues tab to see all the new cards!${NC}" 