export class RuntimeCredentialInjector {
    broker;
    audit;
    constructor(broker, audit) {
        this.broker = broker;
        this.audit = audit;
    }
    async buildOpenAiEnvironment(ref) {
        if (ref.provider !== "openai" || ref.kind !== "openai_api_key") {
            this.appendProviderFailed(ref, "provider-unsupported");
            throw new Error("Unsupported credential reference for OpenAI runtime injection.");
        }
        let credential;
        try {
            credential = await this.broker.acquire(ref);
        }
        catch (error) {
            this.appendProviderFailed(ref, "provider-credential-unavailable");
            throw error;
        }
        this.audit?.append({
            type: "provider_used",
            severity: "info",
            message: "Provider credential prepared for runtime use.",
            metadata: {
                providerProfileKey: "openai",
                provider: "openai",
                credentialKind: "api_key",
                reasonCode: "provider-used",
                credentialVersionLabel: "current",
            },
        });
        // Decode the cached bytes to a string only here, at the unavoidable env
        // boundary (process env vars are strings). We keep no long-lived string
        // copy of our own: the only surviving reference is env.OPENAI_API_KEY,
        // which the spawned runtime requires and which is GC-owned and short-lived.
        // cleanup() releases the broker entry, which wipes the cached byte buffer.
        return {
            env: {
                OPENAI_API_KEY: new TextDecoder().decode(credential.secret),
            },
            cleanup: () => this.broker.release(ref),
        };
    }
    appendProviderFailed(ref, reasonCode) {
        this.audit?.append({
            type: "provider_failed",
            severity: "warning",
            message: "Provider credential could not be prepared for runtime use.",
            metadata: {
                providerProfileKey: ref.provider === "openai" ? "openai" : "unknown",
                provider: ref.provider,
                credentialKind: ref.kind === "openai_api_key" ? "api_key" : "unknown",
                reasonCode,
                credentialVersionLabel: "unavailable",
            },
        });
    }
}
