/**
 * Workforce DB client — opens/initialises workforce.db.
 * Follows same pattern as synapse/db/client.ts and architects/db/client.ts.
 */
import fs from 'fs';
import path from 'path';
import BetterSqlite3 from 'better-sqlite3';
import { initWorkforceSchema } from './schema.js';
import { resolveEngineStorageRoot, resolveWorkspaceStateRoot, writeEngineStorageOverride, } from '../../engines/workspace-resolver.js';
function buildWorkforcePaths(requestedRoot, storageRoot, fallbackApplied, fallbackReason) {
    const dir = path.join(path.resolve(storageRoot), '.workforce');
    return {
        dir,
        dbPath: path.join(dir, 'workforce.db'),
        requestedRoot: path.resolve(requestedRoot),
        storageRoot: path.resolve(storageRoot),
        fallbackApplied,
        fallbackReason,
    };
}
export function resolveWorkforcePaths(root) {
    const resolution = resolveEngineStorageRoot(root ?? process.cwd(), 'workforce');
    return buildWorkforcePaths(resolution.requestedRoot, resolution.storageRoot, resolution.fallbackApplied, resolution.fallbackReason);
}
function openDatabaseAt(paths) {
    fs.mkdirSync(paths.dir, { recursive: true });
    const db = new BetterSqlite3(paths.dbPath);
    db.pragma('foreign_keys = ON');
    initWorkforceSchema(db);
    return db;
}
export function openWorkforceDb(root) {
    const paths = resolveWorkforcePaths(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 {
            if (fs.existsSync(paths.dir)) {
                const stamp = new Date().toISOString().replace(/[:.]/g, '-');
                quarantinePath = path.join(resolveWorkspaceStateRoot(paths.requestedRoot), 'quarantine', 'workforce', stamp);
                fs.mkdirSync(path.dirname(quarantinePath), { recursive: true });
                fs.cpSync(paths.dir, quarantinePath, { recursive: true, force: true });
            }
        }
        catch { /* ignore quarantine errors */ }
        const fallbackReason = [
            `Workforce failed to open ${paths.dbPath}: ${localReason}`,
            `using fallback at ${fallbackStorageRoot}`,
            quarantinePath ? `quarantined: ${quarantinePath}` : null,
        ].filter(Boolean).join(' · ');
        writeEngineStorageOverride({
            engine: 'workforce',
            requestedRoot: paths.requestedRoot,
            storageRoot: fallbackStorageRoot,
            reason: fallbackReason,
            createdAt: Date.now(),
            quarantinePath,
            sourceDbPath: paths.dbPath,
        });
        const fallbackPaths = buildWorkforcePaths(paths.requestedRoot, fallbackStorageRoot, true, fallbackReason);
        return { db: openDatabaseAt(fallbackPaths), paths: fallbackPaths, degraded: true, reason: fallbackReason, quarantinePath };
    }
}
