/**
 * Applet type system — compact dashboard cards with typed I/O ports.
 *
 * Modules declare AppletDefinition[] to expose applets on the canvas.
 * Each applet renders a compact card, wires via FolkArrow ports, and
 * optionally expands into a circuit editor (sub-node graph).
 */

import type { PortDescriptor } from "../lib/data-types";

// ── Sub-graph types (for expanded circuit view) ──

export interface AppletSubNode {
	id: string;
	type: string;
	label: string;
	icon: string;
	position: { x: number; y: number };
	config: Record<string, unknown>;
}

export interface AppletSubEdge {
	id: string;
	fromNode: string;
	fromPort: string;
	toNode: string;
	toPort: string;
}

// ── Applet definition (declared by modules) ──

export interface AppletDefinition {
	/** Unique within module, e.g. "signoff-gate" */
	id: string;
	/** Display name, e.g. "Signoff Gate" */
	label: string;
	/** Emoji icon */
	icon: string;
	/** Accent color for header bar */
	accentColor: string;
	/** Typed I/O ports */
	ports: PortDescriptor[];
	/** Render compact card body HTML from live data */
	renderCompact(data: AppletLiveData): string;
	/** Optional: provide sub-graph for expanded circuit view */
	getCircuit?(space: string): { nodes: AppletSubNode[]; edges: AppletSubEdge[] };
	/** Optional: handle data arriving on an input port */
	onInputReceived?(portName: string, value: unknown, ctx: AppletContext): void;
	/** Optional: self-fetch live data on init + interval (called every 30s) */
	fetchLiveData?(space: string): Promise<Record<string, unknown>>;
}

// ── Runtime data ──

export interface AppletLiveData {
	space: string;
	moduleId: string;
	appletId: string;
	snapshot: Record<string, unknown>;
	outputValues: Record<string, unknown>;
}

export interface AppletContext {
	space: string;
	shapeId: string;
	emitOutput(portName: string, value: unknown): void;
}

// ── Template serialization ──

export interface AppletTemplateShape {
	/** Relative ID for cross-referencing within the template */
	relativeId: string;
	type: string;
	relX: number;
	relY: number;
	width: number;
	height: number;
	rotation: number;
	/** All shape-specific properties (moduleId, appletId, etc.) */
	props: Record<string, unknown>;
}

export interface AppletTemplateArrow {
	relativeId: string;
	sourceRelId: string;
	targetRelId: string;
	sourcePort?: string;
	targetPort?: string;
}

export interface AppletTemplateRecord {
	id: string;
	name: string;
	description: string;
	icon: string;
	color: string;
	createdAt: number;
	createdBy: string;
	shapes: AppletTemplateShape[];
	arrows: AppletTemplateArrow[];
	boundingWidth: number;
	boundingHeight: number;
}
