import { createOpfsVfs } from './opfs.js';
import { createWaSqliteApi } from './adapter.js';
import { makeDbAdapter } from './db.js';
export async function openTreecrdtDb(opts) {
    const baseUrl = opts.baseUrl.endsWith('/') ? opts.baseUrl : `${opts.baseUrl}/`;
    const sqliteModule = await import(/* @vite-ignore */ `${baseUrl}wa-sqlite/wa-sqlite-async.mjs`);
    const sqliteApi = await import(/* @vite-ignore */ `${baseUrl}wa-sqlite/sqlite-api.js`);
    const module = await sqliteModule.default({
        locateFile: (file) => file.endsWith('.wasm') ? `${baseUrl}wa-sqlite/wa-sqlite-async.wasm` : file,
    });
    const sqlite3 = sqliteApi.Factory(module);
    let storage = opts.storage === 'opfs' ? 'opfs' : 'memory';
    let opfsError;
    if (storage === 'opfs') {
        try {
            const vfs = await createOpfsVfs(module, { name: 'opfs', kind: opts.opfsVfs });
            sqlite3.vfs_register(vfs, true);
        }
        catch (err) {
            opfsError = err instanceof Error ? err.message : String(err);
            if (opts.requireOpfs) {
                throw new Error(`OPFS requested but could not be initialized: ${opfsError}`);
            }
            storage = 'memory';
        }
    }
    const filename = storage === 'opfs' ? (opts.filename ?? '/treecrdt.db') : ':memory:';
    const handle = await sqlite3.open_v2(filename);
    const db = makeDbAdapter(sqlite3, handle);
    const api = createWaSqliteApi(db, { onMaterialized: opts.onMaterialized });
    await api.setDocId(opts.docId);
    return opfsError ? { db, api, storage, filename, opfsError } : { db, api, storage, filename };
}
