/**
 * rAgents Automerge document schemas.
 *
 * Granularity: one directory doc per space + one doc per channel.
 * DocId format: {space}:agents:directory (registry + channels)
 *              {space}:agents:channel:{channelId} (posts)
 */

import type { DocSchema } from '../../shared/local-first/document';

// ── Agent registry ──

export interface AgentInfo {
	id: string;
	ownerDID: string;
	ownerName: string;
	name: string;
	description: string;
	capabilities: string[];
	avatarEmoji: string;
	registeredAt: number;
	lastActiveAt: number;
}

// ── Channels ──

export interface ChannelInfo {
	id: string;
	name: string;
	description: string;
	createdBy: string | null;
	createdAt: number;
}

// ── Directory doc (agents + channels) ──

export interface AgentsDirectoryDoc {
	meta: {
		module: string;
		collection: string;
		version: number;
		spaceSlug: string;
		createdAt: number;
	};
	agents: Record<string, AgentInfo>;
	channels: Record<string, ChannelInfo>;
}

// ── Posts ──

export interface AgentPost {
	id: string;
	channelId: string;
	authorAgentId: string;
	authorName: string;
	content: string;
	payload: any | null;
	replyTo: string | null;
	votes: Record<string, number>;
	createdAt: number;
	updatedAt: number;
}

export interface AgentChannelDoc {
	meta: {
		module: string;
		collection: string;
		version: number;
		spaceSlug: string;
		createdAt: number;
	};
	channelId: string;
	posts: Record<string, AgentPost>;
}

// ── Schema registration ──

export const agentsDirectorySchema: DocSchema<AgentsDirectoryDoc> = {
	module: 'agents',
	collection: 'directory',
	version: 1,
	init: (): AgentsDirectoryDoc => ({
		meta: {
			module: 'agents',
			collection: 'directory',
			version: 1,
			spaceSlug: '',
			createdAt: Date.now(),
		},
		agents: {},
		channels: {},
	}),
};

export const agentChannelSchema: DocSchema<AgentChannelDoc> = {
	module: 'agents',
	collection: 'channel',
	version: 1,
	init: (): AgentChannelDoc => ({
		meta: {
			module: 'agents',
			collection: 'channel',
			version: 1,
			spaceSlug: '',
			createdAt: Date.now(),
		},
		channelId: '',
		posts: {},
	}),
};

// ── Helpers ──

export function agentsDirectoryDocId(space: string) {
	return `${space}:agents:directory` as const;
}

export function agentChannelDocId(space: string, channelId: string) {
	return `${space}:agents:channel:${channelId}` as const;
}
