package action

import (
	"context"
	"fmt"

	"github.com/rockliang/poimen/workflows/internal/routing"
	"go.temporal.io/sdk/activity"
)

// LLMRouterActivity is the Temporal activity that routes user requests to workflows
func LLMRouterActivity(ctx context.Context, input routing.LLMRouterInput) (*routing.LLMRouterOutput, error) {
	logger := activity.GetLogger(ctx)
	logger.Info("LLMRouterActivity started", "message", input.Message)

	// Load knowledge base
	kb, err := routing.LoadKnowledgeBaseFromDefaultPath()
	if err != nil {
		return nil, fmt.Errorf("failed to load knowledge base: %w", err)
	}

	// Create router
	router, err := routing.NewLLMRouter(kb)
	if err != nil {
		return nil, fmt.Errorf("failed to create router: %w", err)
	}

	// Route the request
	output, err := router.Route(ctx, input)
	if err != nil {
		logger.Error("LLMRouterActivity failed", "error", err)
		return nil, err
	}

	if output.IsCron {
		logger.Info("LLMRouterActivity completed (cron)", 
			"workflowName", output.CronSpec.Name,
			"schedule", output.CronSpec.Schedule,
			"stateCount", len(output.CronSpec.States))
	} else {
		logger.Info("LLMRouterActivity completed", 
			"workflowName", output.Spec.Name,
			"stateCount", len(output.Spec.States))
	}

	return output, nil
}

// ValidateWorkflowSpecActivity validates a workflow spec before execution
func ValidateWorkflowSpecActivity(ctx context.Context, spec routing.WorkflowSpec) (*routing.ValidationResult, error) {
	logger := activity.GetLogger(ctx)
	logger.Info("ValidateWorkflowSpecActivity started", "workflowName", spec.Name)

	kb, err := routing.LoadKnowledgeBaseFromDefaultPath()
	if err != nil {
		return nil, fmt.Errorf("failed to load knowledge base: %w", err)
	}

	validator := routing.NewValidator(kb)
	result := validator.ValidateWorkflowSpec(&spec)

	logger.Info("ValidateWorkflowSpecActivity completed", 
		"valid", result.Valid,
		"errorCount", len(result.Errors))

	return result, nil
}

// ValidateCronWorkflowSpecActivity validates a cron workflow spec before scheduling
func ValidateCronWorkflowSpecActivity(ctx context.Context, spec routing.CronWorkflowSpec) (*routing.ValidationResult, error) {
	logger := activity.GetLogger(ctx)
	logger.Info("ValidateCronWorkflowSpecActivity started", 
		"workflowName", spec.Name,
		"schedule", spec.Schedule)

	kb, err := routing.LoadKnowledgeBaseFromDefaultPath()
	if err != nil {
		return nil, fmt.Errorf("failed to load knowledge base: %w", err)
	}

	validator := routing.NewValidator(kb)
	result := validator.ValidateCronWorkflowSpec(&spec)

	logger.Info("ValidateCronWorkflowSpecActivity completed", 
		"valid", result.Valid,
		"errorCount", len(result.Errors))

	return result, nil
}
