/**
 * rFiles Local-First Client
 *
 * Wraps the shared local-first stack into a files-specific API.
 * Binary file data stays on the filesystem — only metadata is in Automerge.
 */

import * as Automerge from '@automerge/automerge';
import { DocumentManager } from '../../shared/local-first/document';
import type { DocumentId } from '../../shared/local-first/document';
import { EncryptedDocStore } from '../../shared/local-first/storage';
import { DocSyncManager } from '../../shared/local-first/sync';
import { DocCrypto } from '../../shared/local-first/crypto';
import { filesSchema, filesDocId } from './schemas';
import type { FilesDoc, MediaFile, MemoryCard } from './schemas';

export class FilesLocalFirstClient {
	#space: string;
	#documents: DocumentManager;
	#store: EncryptedDocStore;
	#sync: DocSyncManager;
	#initialized = false;

	constructor(space: string, docCrypto?: DocCrypto) {
		this.#space = space;
		this.#documents = new DocumentManager();
		this.#store = new EncryptedDocStore(space, docCrypto);
		this.#sync = new DocSyncManager({
			documents: this.#documents,
			store: this.#store,
		});
		this.#documents.registerSchema(filesSchema);
	}

	get isConnected(): boolean { return this.#sync.isConnected; }

	async init(): Promise<void> {
		if (this.#initialized) return;
		await this.#store.open();
		const cachedIds = await this.#store.listByModule('files', 'cards');
		const cached = await this.#store.loadMany(cachedIds);
		for (const [docId, binary] of cached) {
			this.#documents.open<FilesDoc>(docId, filesSchema, binary);
		}
		await this.#sync.preloadSyncStates(cachedIds);
		const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
		const wsUrl = `${proto}//${location.host}/ws/${this.#space}`;
		try { await this.#sync.connect(wsUrl, this.#space); } catch { console.warn('[FilesClient] Working offline'); }
		this.#initialized = true;
	}

	async subscribeSharedSpace(sharedSpace: string): Promise<FilesDoc | null> {
		const docId = filesDocId(this.#space, sharedSpace) as DocumentId;
		let doc = this.#documents.get<FilesDoc>(docId);
		if (!doc) {
			const binary = await this.#store.load(docId);
			doc = binary
				? this.#documents.open<FilesDoc>(docId, filesSchema, binary)
				: this.#documents.open<FilesDoc>(docId, filesSchema);
		}
		await this.#sync.subscribe([docId]);
		return doc ?? null;
	}

	updateFile(sharedSpace: string, fileId: string, changes: Partial<MediaFile>): void {
		const docId = filesDocId(this.#space, sharedSpace) as DocumentId;
		this.#sync.change<FilesDoc>(docId, `Update file ${fileId}`, (d) => {
			if (d.files[fileId]) {
				Object.assign(d.files[fileId], changes);
				d.files[fileId].updatedAt = Date.now();
			}
		});
	}

	updateMemoryCard(sharedSpace: string, cardId: string, changes: Partial<MemoryCard>): void {
		const docId = filesDocId(this.#space, sharedSpace) as DocumentId;
		this.#sync.change<FilesDoc>(docId, `Update card ${cardId}`, (d) => {
			if (d.memoryCards[cardId]) {
				Object.assign(d.memoryCards[cardId], changes);
				d.memoryCards[cardId].updatedAt = Date.now();
			}
		});
	}

	onChange(sharedSpace: string, cb: (doc: FilesDoc) => void): () => void {
		return this.#sync.onChange(filesDocId(this.#space, sharedSpace) as DocumentId, cb as (doc: any) => void);
	}

	onConnect(cb: () => void): () => void { return this.#sync.onConnect(cb); }
	onDisconnect(cb: () => void): () => void { return this.#sync.onDisconnect(cb); }

	async disconnect(): Promise<void> {
		await this.#sync.flush();
		this.#sync.disconnect();
	}
}
