import fs from 'fs';
import path from 'path';
import BetterSqlite3 from 'better-sqlite3';
import { initArchitectsSchema } from './schema.js';
import { resolveEngineStorageRoot, resolveWorkspaceStateRoot, writeEngineStorageOverride, } from '../../engines/workspace-resolver.js';
function buildArchitectsPaths(requestedRoot, storageRoot, fallbackApplied, fallbackReason) {
    const normalizedRequestedRoot = path.resolve(requestedRoot);
    const normalizedStorageRoot = path.resolve(storageRoot);
    const dir = path.join(normalizedStorageRoot, '.architects');
    return {
        dir,
        dbPath: path.join(dir, 'architects.db'),
        requestedRoot: normalizedRequestedRoot,
        storageRoot: normalizedStorageRoot,
        fallbackApplied,
        fallbackReason,
    };
}
export function resolveArchitectsPaths(root) {
    if (typeof root === 'object' && root !== null) {
        const requestedRoot = path.resolve(root.requestedRoot ?? process.cwd());
        const storageRoot = path.resolve(root.storageRoot ?? requestedRoot);
        return buildArchitectsPaths(requestedRoot, storageRoot, root.fallbackApplied ?? storageRoot !== requestedRoot, root.fallbackReason);
    }
    const resolution = resolveEngineStorageRoot(typeof root === 'string' ? root : process.cwd(), 'architects');
    return buildArchitectsPaths(resolution.requestedRoot, resolution.storageRoot, resolution.fallbackApplied, resolution.fallbackReason);
}
function openDatabaseAt(paths) {
    fs.mkdirSync(paths.dir, { recursive: true });
    const db = new BetterSqlite3(paths.dbPath);
    initArchitectsSchema(db);
    return db;
}
function quarantineBrokenArchitects(paths) {
    if (!fs.existsSync(paths.dir)) {
        return undefined;
    }
    const stamp = new Date().toISOString().replace(/[:.]/g, '-');
    const quarantinePath = path.join(resolveWorkspaceStateRoot(paths.requestedRoot), 'quarantine', 'architects', stamp);
    fs.mkdirSync(path.dirname(quarantinePath), { recursive: true });
    fs.cpSync(paths.dir, quarantinePath, { recursive: true, force: true });
    return quarantinePath;
}
export function openArchitectsDb(root) {
    const paths = resolveArchitectsPaths(root);
    try {
        return {
            db: openDatabaseAt(paths),
            paths,
            degraded: paths.fallbackApplied,
            reason: paths.fallbackReason,
        };
    }
    catch (error) {
        const fallbackStorageRoot = resolveWorkspaceStateRoot(paths.requestedRoot);
        if (path.resolve(paths.storageRoot) === path.resolve(fallbackStorageRoot)) {
            throw error;
        }
        const localReason = error instanceof Error ? error.message : String(error);
        let quarantinePath;
        try {
            quarantinePath = quarantineBrokenArchitects(paths);
        }
        catch {
            quarantinePath = undefined;
        }
        const fallbackReason = [
            `Architects failed to open ${paths.dbPath}: ${localReason}`,
            `using fallback storage at ${fallbackStorageRoot}`,
            quarantinePath ? `quarantined copy: ${quarantinePath}` : null,
        ].filter(Boolean).join(' · ');
        writeEngineStorageOverride({
            engine: 'architects',
            requestedRoot: paths.requestedRoot,
            storageRoot: fallbackStorageRoot,
            reason: fallbackReason,
            createdAt: Date.now(),
            quarantinePath,
            sourceDbPath: paths.dbPath,
        });
        const fallbackPaths = resolveArchitectsPaths({
            requestedRoot: paths.requestedRoot,
            storageRoot: fallbackStorageRoot,
            fallbackApplied: true,
            fallbackReason,
        });
        return {
            db: openDatabaseAt(fallbackPaths),
            paths: fallbackPaths,
            degraded: true,
            reason: fallbackReason,
            quarantinePath,
        };
    }
}
