package runtimeapi

import (
	"context"
	"os"
	"strconv"
	"time"

	"github.com/nexuscrm/kernel/pkg/perftiming"
)

const (
	runtimeFlowPerfTimingEnabledEnv = "NEXUSCRM_RUNTIME_FLOW_PERF_TIMING_ENABLED"
	runtimeAPIProfilingEnabledEnv   = "NEXUSCRM_RUNTIME_API_PROFILING_ENABLED"
)

// withRuntimeFlowProfiling enables the existing bounded, metadata-neutral
// performance events for ExecuteFlow when an operator explicitly opts in. It
// changes no request, authorization, transaction, or response semantics.
func withRuntimeFlowProfiling(ctx context.Context) context.Context {
	// Detailed Flow/Records/SQL timing is part of the same opt-in diagnostic
	// mode as pprof. Keeping it enabled for ordinary Test2 serving makes the
	// measurement itself part of every request's critical path: one business
	// action can synchronously emit hundreds of structured log events. The
	// legacy Flow-specific flag remains an additional explicit opt-in for local
	// diagnostics, but cannot silently override a disabled process profile.
	profilingEnabled, profilingErr := strconv.ParseBool(os.Getenv(runtimeAPIProfilingEnabledEnv))
	flowEnabled, flowErr := strconv.ParseBool(os.Getenv(runtimeFlowPerfTimingEnabledEnv))
	if profilingErr != nil || flowErr != nil || !profilingEnabled || !flowEnabled {
		return ctx
	}
	return perftiming.WithEnabled(ctx)
}

func startRuntimeFlowStage(ctx context.Context) time.Time {
	if !perftiming.Enabled(ctx) {
		return time.Time{}
	}
	return time.Now()
}

func finishRuntimeFlowStage(ctx context.Context, stage string, started time.Time, err error) {
	if started.IsZero() {
		return
	}
	perftiming.Event(ctx, "runtime_flow_stage_timing", started, err).
		Str("stage", stage).
		Msg("Runtime Flow stage timing")
}
