/**
 * rSpace Ecosystem Manifest Protocol
 *
 * Each r-ecosystem app (rWallet, rVote, rMaps, etc.) hosts a manifest at:
 *   /.well-known/rspace-manifest.json
 *
 * The manifest declares the app's embeddable shapes, their port/event
 * descriptors, and the ES module URL to dynamically import.
 *
 * Embedding modes:
 *   1. Trusted (Web Component) — dynamic import(), shares CRDT, full port/event access
 *   2. Sandboxed (iframe) — postMessage bridge, limited API, origin-validated
 */

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

// ── Event descriptors ──

export type EventDirection = "emit" | "listen" | "both";

export interface EventDescriptor {
	/** Channel name (e.g. "payment-sent", "vote-cast") */
	name: string;
	/** Whether the shape emits, listens, or both */
	direction: EventDirection;
	/** Human-readable description */
	description?: string;
	/** Expected payload JSON Schema (informational) */
	payloadSchema?: Record<string, unknown>;
}

// ── Shape descriptors ──

export interface EcosystemShapeDescriptor {
	/** Custom element tag name (e.g. "folk-rwallet") */
	tagName: string;
	/** Human-readable shape name */
	name: string;
	/** Short description of the shape */
	description?: string;
	/** Default dimensions when placed on canvas */
	defaults: { width: number; height: number };
	/** Typed data ports for arrow connections */
	portDescriptors: PortDescriptor[];
	/** Event bus channels this shape participates in */
	eventDescriptors: EventDescriptor[];
}

// ── App manifest ──

export interface EcosystemManifest {
	/** Unique app identifier (e.g. "rwallet", "rvote") */
	appId: string;
	/** Human-readable app name */
	name: string;
	/** Semantic version */
	version: string;
	/** Emoji or URL for app icon */
	icon: string;
	/** Short description */
	description: string;
	/** App homepage URL */
	homepage: string;
	/** ES module URL to import (relative to app origin) */
	moduleUrl: string;
	/** Badge color for canvas header */
	color: string;
	/** Embedding modes this app supports */
	embeddingModes: ("trusted" | "sandboxed")[];
	/** Shapes this app exposes for canvas embedding */
	shapes: EcosystemShapeDescriptor[];
	/** Minimum rSpace protocol version required */
	minProtocolVersion?: number;
}

// ── Protocol version ──

/** Current rSpace ecosystem manifest protocol version */
export const ECOSYSTEM_PROTOCOL_VERSION = 1;

// ── Resolved manifest (with origin info from proxy) ──

export interface ResolvedManifest extends EcosystemManifest {
	/** Origin the manifest was fetched from (e.g. "https://rwallet.online") */
	origin: string;
	/** Absolute module URL resolved from origin + moduleUrl */
	resolvedModuleUrl: string;
	/** When this manifest was fetched */
	fetchedAt: number;
}
