import { loadAppDocument, findAppDocuments, } from '@duckcodeailabs/dql-core';
import { PolicyEngine } from '@duckcodeailabs/dql-governance';
import { defaultPersonaRegistry, mergePersonaVariables, } from '@duckcodeailabs/dql-project';
export class DQLAccessDeniedError extends Error {
    constructor(message) {
        super(message);
        this.name = 'DQLAccessDeniedError';
    }
}
export function runtimeVariables(base) {
    return mergePersonaVariables(base ?? {}, defaultPersonaRegistry.active);
}
export function activePersonaAppId() {
    return defaultPersonaRegistry.active?.appId;
}
export function loadRuntimeApp(projectRoot, appId) {
    if (!appId)
        return null;
    for (const p of findAppDocuments(projectRoot)) {
        const { document } = loadAppDocument(p);
        if (document?.id === appId)
            return document;
    }
    return null;
}
export function assertAppAccess(opts) {
    const app = opts.app;
    if (!app)
        return;
    const user = defaultPersonaRegistry.toUserContext();
    const engine = new PolicyEngine(app.policies.map(toAccessPolicy));
    const result = engine.checkAccess(user, opts.domain ?? app.domain, opts.classification ?? 'internal', opts.level ?? 'execute');
    if (!result.allowed) {
        throw new DQLAccessDeniedError(result.reason ?? 'Not authorized');
    }
}
function toAccessPolicy(policy) {
    return {
        id: policy.id,
        name: policy.id,
        description: policy.description ?? policy.id,
        domain: policy.domain,
        minClassification: policy.minClassification,
        allowedRoles: policy.allowedRoles,
        allowedUsers: policy.allowedUsers ?? [],
        accessLevel: policy.accessLevel,
        enabled: policy.enabled !== false,
    };
}
//# sourceMappingURL=governance-runtime.js.map