import { builtinInstructionEntriesForModule } from "../../contracts/builtin-run-command-manifest.js";
import { resolveActorWithFallback } from "../../core/policy.js";
import { runListApprovalQueue } from "./list-approval-queue-runtime.js";
import { runListSessionGrants } from "./list-session-grants-runtime.js";
import { runReviewItem } from "./review-runtime.js";
export const approvalsModule = {
    registration: {
        id: "approvals",
        version: "0.5.0",
        contractVersion: "1",
        stateSchema: 1,
        capabilities: ["approvals"],
        dependsOn: ["task-engine"],
        optionalPeers: [],
        enabledByDefault: true,
        config: {
            path: "src/modules/approvals/config.md",
            format: "md",
            description: "Approvals module policy and queue configuration contract."
        },
        instructions: {
            directory: "src/modules/approvals/instructions",
            entries: builtinInstructionEntriesForModule("approvals")
        }
    },
    async onCommand(command, ctx) {
        const handlers = {
            "list-approval-queue": async () => {
                const result = await runListApprovalQueue(ctx);
                return {
                    ok: result.ok,
                    code: result.code,
                    message: result.message,
                    data: result.data
                };
            },
            "list-session-grants": async () => {
                const result = await runListSessionGrants(ctx);
                return {
                    ok: result.ok,
                    code: result.code,
                    message: result.message,
                    data: result.data
                };
            },
            "review-item": async () => {
                const args = command.args ?? {};
                const actor = typeof args.actor === "string" && args.actor.trim().length > 0
                    ? args.actor.trim()
                    : ctx.resolvedActor ?? (await resolveActorWithFallback(ctx.workspacePath, args, process.env));
                const taskId = typeof args.taskId === "string" ? args.taskId : "";
                const decision = args.decision;
                if (decision !== "accept" && decision !== "decline" && decision !== "accept_edited") {
                    return {
                        ok: false,
                        code: "invalid-args",
                        message: "decision must be accept, decline, or accept_edited"
                    };
                }
                const editedSummary = typeof args.editedSummary === "string" ? args.editedSummary : undefined;
                let policyTraceRef;
                const ptr = args.policyTraceRef;
                if (ptr && typeof ptr === "object" && !Array.isArray(ptr)) {
                    const o = ptr;
                    if (typeof o.operationId === "string" && typeof o.timestamp === "string") {
                        policyTraceRef = { operationId: o.operationId, timestamp: o.timestamp };
                    }
                }
                let configMutationRef;
                const cmr = args.configMutationRef;
                if (cmr && typeof cmr === "object" && !Array.isArray(cmr)) {
                    const o = cmr;
                    if (typeof o.timestamp === "string" && typeof o.key === "string") {
                        configMutationRef = { timestamp: o.timestamp, key: o.key };
                    }
                }
                const result = await runReviewItem(ctx, {
                    taskId,
                    decision,
                    editedSummary,
                    policyTraceRef,
                    configMutationRef
                }, actor);
                return {
                    ok: result.ok,
                    code: result.code,
                    message: result.message,
                    data: "idempotent" in result && result.idempotent
                        ? { idempotent: true }
                        : undefined
                };
            }
        };
        const handler = handlers[command.name];
        if (!handler) {
            return {
                ok: false,
                code: "unsupported-command",
                message: `Approvals module does not support '${command.name}'`
            };
        }
        return handler();
    }
};
