import { stableValueHash } from "./stable-json.js";
import { sortToolPrefixSpecs } from "./tool-registry-contract.js";
export function buildProviderToolPayload(entries) {
    const prefixSpecs = sortToolPrefixSpecs(entries.map((entry) => toPrefixSpec(entry)));
    const sortedEntries = prefixSpecs.map((spec) => {
        const entry = entries.find((candidate) => candidate.name === spec.name);
        if (!entry)
            throw new Error(`missing tool entry for ${spec.name}`);
        return entry;
    });
    const tools = sortedEntries.map((entry) => toProviderPayload(entry));
    const contracts = sortedEntries.map((entry) => toProviderContractView(entry));
    return {
        tools,
        contracts,
        toolPlaneHash: stableValueHash(tools),
    };
}
export function assertToolPlaneHashMatchesPayload(payload) {
    const actual = stableValueHash(payload.tools);
    if (actual !== payload.toolPlaneHash) {
        throw new Error(`provider tool payload hash mismatch: expected ${payload.toolPlaneHash}, got ${actual}`);
    }
}
function toPrefixSpec(entry) {
    return {
        name: entry.name,
        description: entry.description ?? "",
        parameters: (entry.inputSchema ?? {}),
        readOnly: entry.readOnly === true,
        parallelSafe: entry.parallelSafe === true,
        stormExempt: entry.stormExempt === true,
        skipRetentionSave: entry.skipRetentionSave === true,
    };
}
function toProviderPayload(entry) {
    return {
        type: "function",
        function: {
            name: entry.name,
            description: entry.description ?? "",
            parameters: entry.inputSchema ?? {},
        },
    };
}
function toProviderContractView(entry) {
    const readOnly = entry.readOnly === true;
    return {
        name: entry.name,
        schemaHash: stableValueHash(entry.inputSchema ?? {}),
        readOnly,
        parallelSafe: entry.parallelSafe === true,
        mutatesState: !readOnly,
        cacheRelevant: entry.skipRetentionSave !== true,
    };
}
