package runtime

import (
	"context"
	"encoding/json"

	"github.com/RyanCopley/skybridge/faas/internal/domain"
	"github.com/google/uuid"
)

// LogStreamCallback is a function that can be called to stream logs during execution
type LogStreamCallback func(logs []string) error

// RuntimeBackend provides function execution capabilities
type RuntimeBackend interface {
	// Execute runs a function with given input
	Execute(ctx context.Context, function *domain.FunctionDefinition, input json.RawMessage) (*domain.ExecutionResult, error)

	// ExecuteWithLogStreaming runs a function with given input and streams logs during execution
	ExecuteWithLogStreaming(ctx context.Context, function *domain.FunctionDefinition, input json.RawMessage, logCallback LogStreamCallback) (*domain.ExecutionResult, error)

	// Deploy prepares function for execution
	Deploy(ctx context.Context, function *domain.FunctionDefinition) error

	// Remove cleans up function resources
	Remove(ctx context.Context, functionID uuid.UUID) error

	// GetLogs retrieves execution logs
	GetLogs(ctx context.Context, executionID uuid.UUID) ([]string, error)

	// HealthCheck verifies runtime availability
	HealthCheck(ctx context.Context) error

	// GetInfo returns runtime information
	GetInfo(ctx context.Context) (*RuntimeInfo, error)

	// ListContainers returns active containers for functions
	ListContainers(ctx context.Context) ([]ContainerInfo, error)

	// StopExecution stops a running execution
	StopExecution(ctx context.Context, executionID uuid.UUID) error
}

// RuntimeInfo contains runtime backend information
type RuntimeInfo struct {
	Type      string            `json:"type"`
	Version   string            `json:"version"`
	Available bool              `json:"available"`
	Endpoint  string            `json:"endpoint,omitempty"`
	Metadata  map[string]string `json:"metadata,omitempty"`
}

// ContainerInfo contains information about a running container
type ContainerInfo struct {
	ID         string            `json:"id"`
	FunctionID uuid.UUID         `json:"function_id"`
	Status     string            `json:"status"`
	Image      string            `json:"image"`
	CreatedAt  string            `json:"created_at"`
	Labels     map[string]string `json:"labels,omitempty"`
}

// RuntimeFactory creates runtime backends
type RuntimeFactory interface {
	CreateRuntime(ctx context.Context, runtimeType string, config map[string]interface{}) (RuntimeBackend, error)
	GetSupportedRuntimes() []string
	GetDefaultConfig(runtimeType string) map[string]interface{}
}
