#!/bin/bash
set -euo pipefail

# HCFS Workspace Management Script
# Handles workspace synchronization and artifact collection

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WORKSPACE_DIR="/home/agent/work"
HCFS_CONFIG="/home/agent/work/.hcfs-workspace"

# Load workspace configuration
if [ -f "$HCFS_CONFIG" ]; then
    source "$HCFS_CONFIG"
else
    echo "⚠️ No HCFS workspace configuration found"
    exit 1
fi

# Logging function
log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1" | tee -a /var/log/hcfs/workspace.log
}

# Function to store artifact in HCFS
store_artifact() {
    local artifact_path="$1"
    local artifact_name="$2"
    local content="$3"
    
    local hcfs_artifact_path="${HCFS_WORKSPACE_PATH}/artifacts/${artifact_name}"
    
    local artifact_data=$(cat <<EOF
{
    "path": "$hcfs_artifact_path",
    "content": "$content",
    "summary": "Artifact: $artifact_name",
    "metadata": {
        "agent_id": "$AGENT_ID",
        "task_id": "$TASK_ID",
        "artifact_name": "$artifact_name",
        "artifact_type": "workspace_output",
        "file_path": "$artifact_path",
        "created_at": "$(date -Iseconds)"
    }
}
EOF
    )
    
    local response=$(curl -s -X POST \
        -H "Content-Type: application/json" \
        -d "$artifact_data" \
        "$HCFS_API_URL/contexts" || echo "")
    
    if [ -n "$response" ]; then
        log "✅ Stored artifact: $artifact_name -> $hcfs_artifact_path"
        return 0
    else
        log "❌ Failed to store artifact: $artifact_name"
        return 1
    fi
}

# Function to collect and store workspace artifacts
collect_artifacts() {
    log "📦 Collecting workspace artifacts..."
    
    local artifact_count=0
    
    # Common artifact patterns
    local artifact_patterns=(
        "*.log"
        "*.md"
        "*.txt"
        "*.json"
        "*.yaml"
        "*.yml"
        "output/*"
        "build/*.json"
        "build/*.xml"
        "results/*"
        "./**/README*"
        "./**/CHANGELOG*"
        "./**/requirements*.txt"
        "./**/package*.json"
        "./**/Cargo.toml"
        "./**/go.mod"
        "./**/pom.xml"
    )
    
    for pattern in "${artifact_patterns[@]}"; do
        while IFS= read -r -d '' file; do
            if [ -f "$file" ] && [ -s "$file" ]; then
                local relative_path="${file#$WORKSPACE_DIR/}"
                local content=$(base64 -w 0 "$file" 2>/dev/null || echo "")
                
                if [ -n "$content" ] && [ ${#content} -lt 1000000 ]; then  # Limit to 1MB
                    if store_artifact "$relative_path" "$relative_path" "$content"; then
                        artifact_count=$((artifact_count + 1))
                    fi
                fi
            fi
        done < <(find "$WORKSPACE_DIR" -name "$pattern" -type f -print0 2>/dev/null || true)
    done
    
    log "✅ Collected $artifact_count artifacts"
}

# Function to update workspace status in HCFS
update_workspace_status() {
    local status="$1"
    local message="$2"
    
    local status_data=$(cat <<EOF
{
    "path": "${HCFS_WORKSPACE_PATH}/status",
    "content": "$message",
    "summary": "Workspace status: $status",
    "metadata": {
        "agent_id": "$AGENT_ID",
        "task_id": "$TASK_ID",
        "status": "$status",
        "timestamp": "$(date -Iseconds)",
        "hostname": "$(hostname)",
        "workspace_dir": "$WORKSPACE_DIR"
    }
}
EOF
    )
    
    curl -s -X POST \
        -H "Content-Type: application/json" \
        -d "$status_data" \
        "$HCFS_API_URL/contexts" > /dev/null || true
    
    log "📊 Updated workspace status: $status"
}

# Function to sync workspace changes
sync_workspace() {
    log "🔄 Syncing workspace changes..."
    
    # Create workspace summary
    local file_count=$(find "$WORKSPACE_DIR" -type f 2>/dev/null | wc -l)
    local dir_count=$(find "$WORKSPACE_DIR" -type d 2>/dev/null | wc -l)
    local total_size=$(du -sb "$WORKSPACE_DIR" 2>/dev/null | cut -f1 || echo "0")
    
    local summary=$(cat <<EOF
Workspace Summary ($(date -Iseconds)):
- Files: $file_count
- Directories: $dir_count  
- Total Size: $total_size bytes
- Agent: $AGENT_ID
- Task: $TASK_ID
- Container: $(hostname)

Recent Activity:
$(ls -la "$WORKSPACE_DIR" 2>/dev/null | head -10 || echo "No files")
EOF
    )
    
    update_workspace_status "active" "$summary"
}

# Function to finalize workspace
finalize_workspace() {
    log "🏁 Finalizing workspace..."
    
    # Collect all artifacts
    collect_artifacts
    
    # Create final summary
    local completion_summary=$(cat <<EOF
Workspace Completion Summary:
- Agent ID: $AGENT_ID
- Task ID: $TASK_ID
- Container: $(hostname)
- Started: $CREATED_AT
- Completed: $(date -Iseconds)
- Duration: $(($(date +%s) - $(date -d "$CREATED_AT" +%s 2>/dev/null || echo "0"))) seconds

Final Workspace Contents:
$(find "$WORKSPACE_DIR" -type f 2>/dev/null | head -20 || echo "No files")

Artifacts Collected:
$(ls "$WORKSPACE_DIR"/{output,build,logs,results}/* 2>/dev/null | head -10 || echo "No artifacts")
EOF
    )
    
    update_workspace_status "completed" "$completion_summary"
    log "✅ Workspace finalized"
}

# Daemon mode for continuous sync
daemon_mode() {
    log "🔄 Starting HCFS workspace sync daemon..."
    
    local sync_interval=30  # seconds
    local last_sync=0
    
    while true; do
        local current_time=$(date +%s)
        
        if [ $((current_time - last_sync)) -ge $sync_interval ]; then
            sync_workspace
            last_sync=$current_time
        fi
        
        sleep 5
    done
}

# Main command dispatcher
case "${1:-help}" in
    "sync")
        sync_workspace
        ;;
    "collect")
        collect_artifacts
        ;;
    "finalize")
        finalize_workspace
        ;;
    "daemon")
        daemon_mode
        ;;
    "status")
        update_workspace_status "active" "Status check at $(date -Iseconds)"
        ;;
    "help"|*)
        echo "HCFS Workspace Management Script"
        echo ""
        echo "Usage: $0 {sync|collect|finalize|daemon|status|help}"
        echo ""
        echo "Commands:"
        echo "  sync     - Sync current workspace state to HCFS"
        echo "  collect  - Collect and store artifacts in HCFS"
        echo "  finalize - Finalize workspace and store all artifacts"
        echo "  daemon   - Run continuous sync daemon"
        echo "  status   - Update workspace status in HCFS"
        echo "  help     - Show this help message"
        ;;
esac