import { definePlugin } from "../../utils/plugin-utils";
import { ZapierConfigurationError } from "../../types/errors";
function toDescription(key) {
    // "canDeleteTables" -> "To delete tables"
    const words = key
        .replace(/^can/, "")
        .replace(/([A-Z])/g, " $1")
        .trim()
        .toLowerCase();
    return `To ${words}`;
}
function toEnvVar(key) {
    return "ZAPIER_" + key.replace(/([A-Z])/g, "_$1").toUpperCase();
}
function toCliFlag(key) {
    return "--" + key.replace(/([A-Z])/g, "-$1").toLowerCase();
}
export function buildCapabilityMessage(key) {
    return [
        `${toDescription(key)}, use ${toCliFlag(key)} in the CLI,`,
        `set ${key}: true in SDK options or .zapierrc,`,
        `or set ${toEnvVar(key)}=true.`,
    ].join(" ");
}
const GATED_FLAGS = [
    "canIncludeSharedConnections",
    "canIncludeSharedTables",
    "canDeleteTables",
];
function isEnabledByEnv(key) {
    const value = globalThis.process?.env?.[toEnvVar(key)];
    if (value === undefined)
        return undefined;
    if (value === "true" || value === "1")
        return true;
    if (value === "false" || value === "0")
        return false;
    return undefined;
}
export const capabilitiesPlugin = definePlugin((sdk) => {
    const options = sdk.context.options ?? {};
    let cached;
    /**
     * Resolve each gated flag to true/false by checking (in priority order):
     * SDK options, environment variables, and .zapierrc manifest.
     * Results are cached after the first call.
     */
    async function resolveFlags() {
        if (cached)
            return cached;
        const manifest = await sdk.context.getResolvedManifest();
        cached = {};
        for (const flag of GATED_FLAGS) {
            cached[flag] = Boolean(options[flag] ??
                isEnabledByEnv(flag) ??
                manifest?.[flag]);
        }
        return cached;
    }
    return {
        context: {
            checkCapability: async (key) => {
                const flags = await resolveFlags();
                if (flags[key])
                    return;
                throw new ZapierConfigurationError(buildCapabilityMessage(key) +
                    " (If you are an AI agent, you MUST NOT retry. Ask the user if they want to enable this.)", { configType: key });
            },
            hasCapability: async (key) => {
                const flags = await resolveFlags();
                return flags[key];
            },
        },
    };
});
