/**
 * MI Action Protocol — types and parser for [MI_ACTION:{...}] markers
 * embedded in LLM responses.
 *
 * The LLM outputs prose interleaved with action markers. The parser
 * extracts actions and returns clean display text for the user.
 */

export type MiAction =
	| { type: "create-shape"; tagName: string; props: Record<string, any>; ref?: string }
	| { type: "update-shape"; shapeId: string; fields: Record<string, any> }
	| { type: "delete-shape"; shapeId: string }
	| { type: "connect"; sourceId: string; targetId: string; color?: string }
	| { type: "move-shape"; shapeId: string; x: number; y: number }
	| { type: "navigate"; path: string }
	| {
			type: "transform";
			transform: string;
			shapeIds: string[];
	  };

export interface ParsedMiResponse {
	displayText: string;
	actions: MiAction[];
}

const ACTION_PATTERN = /\[MI_ACTION:([\s\S]*?)\]/g;

/**
 * Parse [MI_ACTION:{...}] markers from streamed text.
 * Returns the clean display text (markers stripped) and an array of actions.
 */
export function parseMiActions(text: string): ParsedMiResponse {
	const actions: MiAction[] = [];
	const displayText = text.replace(ACTION_PATTERN, (_, json) => {
		try {
			const action = JSON.parse(json.trim()) as MiAction;
			if (action && action.type) {
				actions.push(action);
			}
		} catch {
			// Malformed action — skip silently
		}
		return "";
	});

	return {
		displayText: displayText.replace(/\n{3,}/g, "\n\n").trim(),
		actions,
	};
}

/** Summarise executed actions for a confirmation chip. */
export function summariseActions(actions: MiAction[]): string {
	const counts: Record<string, number> = {};
	for (const a of actions) {
		counts[a.type] = (counts[a.type] || 0) + 1;
	}
	const parts: string[] = [];
	if (counts["create-shape"]) parts.push(`Created ${counts["create-shape"]} shape(s)`);
	if (counts["update-shape"]) parts.push(`Updated ${counts["update-shape"]} shape(s)`);
	if (counts["delete-shape"]) parts.push(`Deleted ${counts["delete-shape"]} shape(s)`);
	if (counts["connect"]) parts.push(`Connected ${counts["connect"]} pair(s)`);
	if (counts["move-shape"]) parts.push(`Moved ${counts["move-shape"]} shape(s)`);
	if (counts["transform"]) parts.push(`Applied ${counts["transform"]} transform(s)`);
	if (counts["navigate"]) parts.push(`Navigating`);
	return parts.join(", ") || "";
}
