/**
 * rDocs Local-First Client
 *
 * Wraps the shared local-first stack (DocSyncManager + EncryptedDocStore)
 * into a docs-specific API with proper offline support and encryption.
 */

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 { notebookSchema, notebookDocId } from './schemas';
import type { NotebookDoc, NoteItem, NotebookMeta } from './schemas';

export class DocsLocalFirstClient {
	#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(notebookSchema);
	}

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

	async init(): Promise<void> {
		if (this.#initialized) return;

		await this.#store.open();

		const cachedIds = await this.#store.listByModule('notes', 'notebooks');
		const cached = await this.#store.loadMany(cachedIds);
		for (const [docId, binary] of cached) {
			this.#documents.open<NotebookDoc>(docId, notebookSchema, 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('[DocsClient] WebSocket connection failed, working offline');
		}

		this.#initialized = true;
	}

	async subscribeNotebook(notebookId: string): Promise<NotebookDoc | null> {
		const docId = notebookDocId(this.#space, notebookId) as DocumentId;

		let doc = this.#documents.get<NotebookDoc>(docId);
		if (!doc) {
			const binary = await this.#store.load(docId);
			if (binary) {
				doc = this.#documents.open<NotebookDoc>(docId, notebookSchema, binary);
			} else {
				doc = this.#documents.open<NotebookDoc>(docId, notebookSchema);
			}
		}

		await this.#sync.subscribe([docId]);
		return doc ?? null;
	}

	unsubscribeNotebook(notebookId: string): void {
		const docId = notebookDocId(this.#space, notebookId) as DocumentId;
		this.#sync.unsubscribe([docId]);
	}

	getNotebook(notebookId: string): NotebookDoc | undefined {
		const docId = notebookDocId(this.#space, notebookId) as DocumentId;
		return this.#documents.get<NotebookDoc>(docId);
	}

	listNotebookIds(): string[] {
		return this.#documents.list(this.#space, 'notes');
	}

	updateNote(notebookId: string, noteId: string, changes: Partial<NoteItem>): void {
		const docId = notebookDocId(this.#space, notebookId) as DocumentId;
		this.#sync.change<NotebookDoc>(docId, `Update note ${noteId}`, (d) => {
			if (!d.items[noteId]) {
				d.items[noteId] = {
					id: noteId,
					notebookId,
					authorId: null,
					title: '',
					content: '',
					contentPlain: '',
					type: 'NOTE',
					url: null,
					language: null,
					fileUrl: null,
					mimeType: null,
					fileSize: null,
					duration: null,
					isPinned: false,
					sortOrder: 0,
					tags: [],
					createdAt: Date.now(),
					updatedAt: Date.now(),
					...changes,
				};
			} else {
				const item = d.items[noteId];
				Object.assign(item, changes);
				item.updatedAt = Date.now();
			}
		});
	}

	deleteNote(notebookId: string, noteId: string): void {
		const docId = notebookDocId(this.#space, notebookId) as DocumentId;
		this.#sync.change<NotebookDoc>(docId, `Delete note ${noteId}`, (d) => {
			delete d.items[noteId];
		});
	}

	updateNotebook(notebookId: string, changes: Partial<NotebookMeta>): void {
		const docId = notebookDocId(this.#space, notebookId) as DocumentId;
		this.#sync.change<NotebookDoc>(docId, 'Update notebook', (d) => {
			Object.assign(d.notebook, changes);
			d.notebook.updatedAt = Date.now();
		});
	}

	onChange(notebookId: string, cb: (doc: NotebookDoc) => void): () => void {
		const docId = notebookDocId(this.#space, notebookId) as DocumentId;
		return this.#sync.onChange(docId, 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();
	}
}
