package sandbox

// workflow_module.go — v0.30.2 CS1, v0.3.2 instance API
//
// The workflow module lets extensions read workflow definitions,
// manage instances, and programmatically advance workflow stages.
//
// Starlark API:
//   wf = workflow.get_definition(workflow_id)         # returns dict
//   inst = workflow.get_instance(instance_id)         # returns dict
//   inst = workflow.start(workflow_id, data={})        # start new instance
//   inst = workflow.advance(instance_id, data={})      # advance to next stage
//   workflow.cancel(instance_id)                       # cancel instance
//   instances = workflow.list_instances(workflow_id)    # list instances

import (
	"context"
	"encoding/json"
	"fmt"

	"go.starlark.net/starlark"
	"go.starlark.net/starlarkstruct"

	"switchboard-core/store"
)

// BuildWorkflowModule creates the "workflow" Starlark module for a package.
// Requires the workflow.access permission.
//
// v0.3.2: added get_instance and list_instances for read-only instance access.
// Mutating operations (start/advance/cancel) are available via HTTP API;
// Starlark builtins for them will be added when the engine interface is
// extracted to a shared package to avoid circular imports.
func BuildWorkflowModule(ctx context.Context, stores store.Stores) *starlarkstruct.Module {
	return MakeModule("workflow", starlark.StringDict{
		"get_definition": starlark.NewBuiltin("workflow.get_definition", workflowGetDef(ctx, stores)),
		"get_instance":   starlark.NewBuiltin("workflow.get_instance", workflowGetInstance(ctx, stores)),
		"list_instances": starlark.NewBuiltin("workflow.list_instances", workflowListInstances(ctx, stores)),
	})
}

func workflowGetDef(ctx context.Context, stores store.Stores) func(*starlark.Thread, *starlark.Builtin, starlark.Tuple, []starlark.Tuple) (starlark.Value, error) {
	return func(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
		var workflowID string
		if err := starlark.UnpackPositionalArgs("workflow.get_definition", args, kwargs, 1, &workflowID); err != nil {
			return nil, err
		}
		wf, err := stores.Workflows.GetByID(ctx, workflowID)
		if err != nil {
			return starlark.None, fmt.Errorf("workflow.get_definition: %w", err)
		}

		stages, _ := stores.Workflows.ListStages(ctx, workflowID)

		// Build stages list
		stageList := make([]starlark.Value, 0, len(stages))
		for _, s := range stages {
			d := starlark.NewDict(8)
			d.SetKey(starlark.String("id"), starlark.String(s.ID))
			d.SetKey(starlark.String("name"), starlark.String(s.Name))
			d.SetKey(starlark.String("ordinal"), starlark.MakeInt(s.Ordinal))
			d.SetKey(starlark.String("stage_mode"), starlark.String(s.StageMode))
			d.SetKey(starlark.String("audience"), starlark.String(s.Audience))
			d.SetKey(starlark.String("stage_type"), starlark.String(s.StageType))
			d.SetKey(starlark.String("auto_transition"), starlark.Bool(s.AutoTransition))
			if s.StarlarkHook != nil {
				d.SetKey(starlark.String("starlark_hook"), starlark.String(*s.StarlarkHook))
			}
			if s.AssignmentTeamID != nil {
				d.SetKey(starlark.String("assignment_team_id"), starlark.String(*s.AssignmentTeamID))
			}
			if s.SurfacePkgID != nil {
				d.SetKey(starlark.String("surface_pkg_id"), starlark.String(*s.SurfacePkgID))
			}
			stageList = append(stageList, d)
		}

		result := starlark.NewDict(8)
		result.SetKey(starlark.String("id"), starlark.String(wf.ID))
		result.SetKey(starlark.String("name"), starlark.String(wf.Name))
		result.SetKey(starlark.String("slug"), starlark.String(wf.Slug))
		result.SetKey(starlark.String("entry_mode"), starlark.String(wf.EntryMode))
		result.SetKey(starlark.String("is_active"), starlark.Bool(wf.IsActive))
		result.SetKey(starlark.String("version"), starlark.MakeInt(wf.Version))
		result.SetKey(starlark.String("stages"), starlark.NewList(stageList))
		return result, nil
	}
}

// ── Instance Read API (v0.3.2) ──────────────

func workflowGetInstance(ctx context.Context, stores store.Stores) func(*starlark.Thread, *starlark.Builtin, starlark.Tuple, []starlark.Tuple) (starlark.Value, error) {
	return func(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
		var instanceID string
		if err := starlark.UnpackPositionalArgs("workflow.get_instance", args, kwargs, 1, &instanceID); err != nil {
			return nil, err
		}
		inst, err := stores.Workflows.GetInstance(ctx, instanceID)
		if err != nil {
			return starlark.None, fmt.Errorf("workflow.get_instance: %w", err)
		}

		d := starlark.NewDict(8)
		d.SetKey(starlark.String("id"), starlark.String(inst.ID))
		d.SetKey(starlark.String("workflow_id"), starlark.String(inst.WorkflowID))
		d.SetKey(starlark.String("workflow_version"), starlark.MakeInt(inst.WorkflowVersion))
		d.SetKey(starlark.String("current_stage"), starlark.String(inst.CurrentStage))
		d.SetKey(starlark.String("status"), starlark.String(inst.Status))
		d.SetKey(starlark.String("started_by"), starlark.String(inst.StartedBy))

		// Parse stage_data into Starlark dict
		var dataMap map[string]interface{}
		if json.Unmarshal(inst.StageData, &dataMap) == nil {
			starlarkData := starlark.NewDict(len(dataMap))
			for k, v := range dataMap {
				starlarkData.SetKey(starlark.String(k), goValToStarlark(v))
			}
			d.SetKey(starlark.String("stage_data"), starlarkData)
		} else {
			d.SetKey(starlark.String("stage_data"), starlark.NewDict(0))
		}

		if inst.EntryToken != nil {
			d.SetKey(starlark.String("entry_token"), starlark.String(*inst.EntryToken))
		}

		return d, nil
	}
}

func workflowListInstances(ctx context.Context, stores store.Stores) func(*starlark.Thread, *starlark.Builtin, starlark.Tuple, []starlark.Tuple) (starlark.Value, error) {
	return func(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
		var workflowID string
		var status string
		if err := starlark.UnpackPositionalArgs("workflow.list_instances", args, kwargs, 1, &workflowID, &status); err != nil {
			return nil, err
		}

		instances, err := stores.Workflows.ListInstances(ctx, workflowID, status, store.ListOptions{Limit: 100})
		if err != nil {
			return starlark.None, fmt.Errorf("workflow.list_instances: %w", err)
		}

		result := make([]starlark.Value, 0, len(instances))
		for _, inst := range instances {
			d := starlark.NewDict(6)
			d.SetKey(starlark.String("id"), starlark.String(inst.ID))
			d.SetKey(starlark.String("current_stage"), starlark.String(inst.CurrentStage))
			d.SetKey(starlark.String("status"), starlark.String(inst.Status))
			d.SetKey(starlark.String("started_by"), starlark.String(inst.StartedBy))
			d.SetKey(starlark.String("workflow_version"), starlark.MakeInt(inst.WorkflowVersion))
			result = append(result, d)
		}

		return starlark.NewList(result), nil
	}
}

// goValToStarlark converts a Go value to a Starlark value.
func goValToStarlark(v interface{}) starlark.Value {
	switch val := v.(type) {
	case nil:
		return starlark.None
	case bool:
		return starlark.Bool(val)
	case float64:
		if val == float64(int(val)) {
			return starlark.MakeInt(int(val))
		}
		return starlark.Float(val)
	case string:
		return starlark.String(val)
	case map[string]interface{}:
		d := starlark.NewDict(len(val))
		for k, v := range val {
			d.SetKey(starlark.String(k), goValToStarlark(v))
		}
		return d
	case []interface{}:
		elems := make([]starlark.Value, len(val))
		for i, v := range val {
			elems[i] = goValToStarlark(v)
		}
		return starlark.NewList(elems)
	default:
		return starlark.String(fmt.Sprintf("%v", v))
	}
}

// workflowRoute routes the workflow to a named stage (v0.35.0).
// Starlark: workflow.route(channel_id, target_stage, reason)
