/**
 * dev-workflow-engine.ts — DevWorkflowEngine implementation.
 *
 * Implements WorkflowEngine by delegating to existing SF state derivation
 * and dispatch logic. This is the "dev" engine — it wraps the current SF
 * autonomous mode behavior behind the engine-polymorphic interface.
 */

import { loadEffectiveSFPreferences } from "./preferences.js";
import { deriveState } from "./state.js";
import { resolveDispatch } from "./uok/auto-dispatch.js";
// ─── Bridge: DispatchAction → EngineDispatchAction ────────────────────────
/**
 * Map a SF-specific DispatchAction (which carries `matchedRule`, `unitType`,
 * etc.) to the engine-generic EngineDispatchAction discriminated union.
 *
 * Exported for unit testing.
 */
/**
 * Map a SF-specific DispatchAction to the engine-generic EngineDispatchAction.
 * Exported for unit testing.
 */
export function bridgeDispatchAction(da) {
	switch (da.action) {
		case "dispatch":
			return {
				action: "dispatch",
				step: {
					unitType: da.unitType,
					unitId: da.unitId,
					prompt: da.prompt,
				},
			};
		case "stop":
			return {
				action: "stop",
				reason: da.reason,
				level: da.level,
			};
		case "skip":
			return { action: "skip" };
	}
}
// ─── DevWorkflowEngine ───────────────────────────────────────────────────
/**
 * DevWorkflowEngine wraps current SF autonomous mode behavior behind the engine interface.
 * Implements WorkflowEngine by delegating to existing state derivation and dispatch logic.
 */
export class DevWorkflowEngine {
	engineId = "dev";
	async deriveState(basePath) {
		const sf = await deriveState(basePath);
		return {
			phase: sf.phase,
			currentMilestoneId: sf.activeMilestone?.id ?? null,
			activeSliceId: sf.activeSlice?.id ?? null,
			activeTaskId: sf.activeTask?.id ?? null,
			isComplete: sf.phase === "complete",
			raw: sf,
		};
	}
	async resolveDispatch(state, context) {
		const sf = state.raw;
		const mid = sf.activeMilestone?.id ?? "";
		const midTitle = sf.activeMilestone?.title ?? "";
		const loaded = loadEffectiveSFPreferences();
		const prefs = loaded?.preferences ?? undefined;
		const dispatchCtx = {
			basePath: context.basePath,
			mid,
			midTitle,
			state: sf,
			prefs,
		};
		const result = await resolveDispatch(dispatchCtx);
		return bridgeDispatchAction(result);
	}
	async reconcile(state, _completedStep) {
		return {
			outcome: state.isComplete ? "milestone-complete" : "continue",
		};
	}
	getDisplayMetadata(state) {
		return {
			engineLabel: "SF Dev",
			currentPhase: state.phase,
			progressSummary: `${state.currentMilestoneId ?? "no milestone"} / ${state.activeSliceId ?? "—"} / ${state.activeTaskId ?? "—"}`,
			stepCount: null,
		};
	}
}
