import { CHECKLIST_ITEM_PENDING } from "./checklist-types.js";
import { PERSISTENT_GOAL_CUSTOM_KEY, mergeCustomDataPatch, readPersistentGoal, serializePersistentGoal } from "./state.js";
//#region src/agent/goals/checklist-user.ts
function baseCustom(customData) {
	return { ...customData ?? {} };
}
function applyChecklistUserMutation(customData, op) {
	const s = readPersistentGoal(customData);
	if (!s || s.status === "cleared") return {
		kind: "error",
		error: "No active goal."
	};
	if (op.type === "reset") {
		const next = {
			...s,
			checklist: [],
			decomposed: false,
			consecutiveParseFailures: 0
		};
		return {
			kind: "updated",
			customData: mergeCustomDataPatch(baseCustom(customData), { [PERSISTENT_GOAL_CUSTOM_KEY]: serializePersistentGoal(next) })
		};
	}
	const list = [...s.checklist ?? []];
	if (op.type === "add") {
		const text = op.text.trim();
		if (!text) return {
			kind: "error",
			error: "Empty checklist item."
		};
		const item = {
			text,
			status: CHECKLIST_ITEM_PENDING,
			addedBy: "user",
			addedAt: Date.now()
		};
		list.push(item);
		const next = {
			...s,
			checklist: list
		};
		return {
			kind: "updated",
			customData: mergeCustomDataPatch(baseCustom(customData), { [PERSISTENT_GOAL_CUSTOM_KEY]: serializePersistentGoal(next) })
		};
	}
	if (!list.length) return {
		kind: "noop",
		message: "Checklist is empty."
	};
	const idx = op.index1Based - 1;
	if (idx < 0 || idx >= list.length) return {
		kind: "error",
		error: `Index out of range (1–${list.length}).`
	};
	if (op.type === "remove") {
		list.splice(idx, 1);
		const next = {
			...s,
			checklist: list
		};
		return {
			kind: "updated",
			customData: mergeCustomDataPatch(baseCustom(customData), { [PERSISTENT_GOAL_CUSTOM_KEY]: serializePersistentGoal(next) })
		};
	}
	const st = op.status;
	if (st !== "pending" && st !== "completed" && st !== "impossible") return {
		kind: "error",
		error: "Invalid status."
	};
	const item = { ...list[idx] };
	item.status = st;
	if (st === "completed" || st === "impossible") {
		item.completedAt = Date.now();
		if (!item.evidence) item.evidence = "marked by user";
	} else item.completedAt = void 0;
	list[idx] = item;
	const next = {
		...s,
		checklist: list
	};
	return {
		kind: "updated",
		customData: mergeCustomDataPatch(baseCustom(customData), { [PERSISTENT_GOAL_CUSTOM_KEY]: serializePersistentGoal(next) })
	};
}
//#endregion
export { applyChecklistUserMutation };

//# sourceMappingURL=checklist-user.js.map