#!/bin/bash
set -euo pipefail

# HCFS Agent Container Entrypoint
echo "🚀 Starting HCFS-enabled agent container..."

# Environment validation
AGENT_ID="${AGENT_ID:-agent-$(hostname)}"
TASK_ID="${TASK_ID:-task-$(date +%s)}"
HCFS_API_URL="${HCFS_API_URL:-http://host.docker.internal:8000}"
HCFS_ENABLED="${HCFS_ENABLED:-true}"

echo "📋 Container Configuration:"
echo "  Agent ID: $AGENT_ID"
echo "  Task ID: $TASK_ID"
echo "  HCFS API: $HCFS_API_URL"
echo "  HCFS Enabled: $HCFS_ENABLED"

# Function to wait for HCFS API
wait_for_hcfs() {
    local max_attempts=30
    local attempt=0
    
    echo "⏳ Waiting for HCFS API to be available..."
    
    while [ $attempt -lt $max_attempts ]; do
        if curl -s "$HCFS_API_URL/health" > /dev/null 2>&1; then
            echo "✅ HCFS API is available"
            return 0
        fi
        
        echo "   Attempt $((attempt + 1))/$max_attempts - HCFS API not ready"
        sleep 2
        attempt=$((attempt + 1))
    done
    
    echo "❌ HCFS API failed to become available after $max_attempts attempts"
    return 1
}

# Function to initialize HCFS workspace
init_hcfs_workspace() {
    echo "🔧 Initializing HCFS workspace..."
    
    # Create workspace context in HCFS
    local workspace_path="/agents/$AGENT_ID/workspaces/$(date +%s)"
    local context_data=$(cat <<EOF
{
    "path": "$workspace_path",
    "content": "Agent workspace for container $(hostname)",
    "summary": "Agent $AGENT_ID workspace - Task $TASK_ID",
    "metadata": {
        "agent_id": "$AGENT_ID",
        "task_id": "$TASK_ID",
        "container_id": "$(hostname)",
        "created_at": "$(date -Iseconds)",
        "workspace_type": "agent_container"
    }
}
EOF
    )
    
    # Create context via HCFS API
    local response=$(curl -s -X POST \
        -H "Content-Type: application/json" \
        -d "$context_data" \
        "$HCFS_API_URL/contexts" || echo "")
    
    if [ -n "$response" ]; then
        echo "✅ HCFS workspace context created: $workspace_path"
        echo "$workspace_path" > /tmp/hcfs-workspace-path
        return 0
    else
        echo "⚠️ Failed to create HCFS workspace context, using local storage"
        return 1
    fi
}

# Function to mount HCFS
mount_hcfs() {
    local workspace_path="$1"
    
    echo "🔗 Mounting HCFS workspace: $workspace_path"
    
    # For now, create a symbolic structure since we don't have full FUSE implementation
    # In production, this would be: fusermount3 -o allow_other "$workspace_path" /mnt/hcfs
    
    mkdir -p /mnt/hcfs
    mkdir -p /home/agent/work/{src,build,output,logs}
    
    # Create workspace metadata
    cat > /home/agent/work/.hcfs-workspace << EOF
HCFS_WORKSPACE_PATH=$workspace_path
HCFS_API_URL=$HCFS_API_URL
AGENT_ID=$AGENT_ID
TASK_ID=$TASK_ID
CREATED_AT=$(date -Iseconds)
EOF
    
    # Set ownership
    chown -R agent:agent /home/agent/work /mnt/hcfs
    
    echo "✅ HCFS workspace mounted and configured"
}

# Function to setup development environment
setup_dev_environment() {
    echo "🛠️ Setting up development environment..."
    
    # Create standard development directories
    sudo -u agent mkdir -p /home/agent/{.local/bin,.config,.cache,work/{src,tests,docs,scripts}}
    
    # Set up git configuration if provided
    if [ -n "${GIT_USER_NAME:-}" ] && [ -n "${GIT_USER_EMAIL:-}" ]; then
        sudo -u agent git config --global user.name "$GIT_USER_NAME"
        sudo -u agent git config --global user.email "$GIT_USER_EMAIL"
        echo "✅ Git configuration set: $GIT_USER_NAME <$GIT_USER_EMAIL>"
    fi
    
    # Set up Python virtual environment
    if [ "${SETUP_PYTHON_VENV:-true}" = "true" ]; then
        sudo -u agent python3 -m venv /home/agent/.venv
        echo "✅ Python virtual environment created"
    fi
    
    echo "✅ Development environment ready"
}

# Function to start background services
start_background_services() {
    echo "🔄 Starting background services..."
    
    # Start HCFS workspace sync daemon (if needed)
    if [ "$HCFS_ENABLED" = "true" ] && [ -f /tmp/hcfs-workspace-path ]; then
        /opt/hcfs/hcfs-workspace.sh daemon &
        echo "✅ HCFS workspace sync daemon started"
    fi
}

# Function to cleanup on exit
cleanup() {
    echo "🧹 Container cleanup initiated..."
    
    if [ "$HCFS_ENABLED" = "true" ] && [ -f /tmp/hcfs-workspace-path ]; then
        echo "💾 Storing final workspace state to HCFS..."
        /opt/hcfs/hcfs-workspace.sh finalize
    fi
    
    echo "✅ Cleanup completed"
}

# Set up signal handlers for graceful shutdown
trap cleanup EXIT INT TERM

# Main initialization sequence
main() {
    echo "🏁 Starting HCFS Agent Container initialization..."
    
    # Wait for HCFS if enabled
    if [ "$HCFS_ENABLED" = "true" ]; then
        if wait_for_hcfs; then
            if init_hcfs_workspace; then
                local workspace_path=$(cat /tmp/hcfs-workspace-path)
                mount_hcfs "$workspace_path"
            else
                echo "⚠️ HCFS workspace initialization failed, continuing with local storage"
            fi
        else
            echo "⚠️ HCFS API unavailable, continuing with local storage"
        fi
    else
        echo "ℹ️ HCFS disabled, using local storage only"
    fi
    
    # Set up development environment
    setup_dev_environment
    
    # Start background services
    start_background_services
    
    echo "🎉 HCFS Agent Container initialization complete!"
    echo "📁 Workspace: /home/agent/work"
    echo "🔧 Agent: $AGENT_ID"
    echo "📋 Task: $TASK_ID"
    
    # Execute the provided command or start interactive shell
    if [ $# -eq 0 ]; then
        echo "🔧 Starting interactive shell..."
        exec sudo -u agent -i /bin/bash
    else
        echo "🚀 Executing command: $*"
        exec sudo -u agent "$@"
    fi
}

# Execute main function
main "$@"