import{appendEnv}from"../append-env.js";import{isProjectResolved}from"../project-resolution.js";import{requireProjectPath}from"../state.js";import{runVercelEnvPull}from"../run-vercel-link.js";import{detectAiGatewayResolution}from"./detect-ai-gateway.js";import{join}from"node:path";import{createPromptCommandOutput}from"#setup/cli/index.js";const AI_GATEWAY_ENV_KEY=`AI_GATEWAY_API_KEY`,ENV_FILE_NAME=`.env.local`;function applyAiGatewayCredential(o){let s=o.deps??{appendEnv,runVercelEnvPull,detectAiGatewayResolution};async function writeAiGatewayApiKey(e,t){let n=join(e,ENV_FILE_NAME);await s.appendEnv(n,{[AI_GATEWAY_ENV_KEY]:t.trim()},{force:!0}),o.prompter.log.success(`Wrote ${AI_GATEWAY_ENV_KEY} to ${n}`)}return{id:`apply-ai-gateway-credential`,shouldRun(e){let{aiGateway:n,project:r}=e;return n.kind===`byok`||n.kind===`inherit`&&isProjectResolved(r)},async gather(){return null},async perform({state:e}){let{prompter:r}=o,i=requireProjectPath(e),a=e.aiGateway,c=isProjectResolved(e.project);if(a.kind===`byop`)return{kind:`unresolved`};if(a.kind===`byok`)return await writeAiGatewayApiKey(i,a.apiGatewayKey),{kind:`api-key`,envFile:ENV_FILE_NAME};if(!c)return r.log.warning(`No Vercel project linked and no API key provided. The agent will not reach a model until you set ${AI_GATEWAY_ENV_KEY} in ${ENV_FILE_NAME} or link a project.`),{kind:`unresolved`};r.log.message(`Pulling Vercel environment variables into .env.local...`);let l=createPromptCommandOutput(r.log);return await s.runVercelEnvPull(i,l)?r.log.success(`Connected the agent to the Vercel AI Gateway.`):r.log.warning(`Linked the project, but pulling environment variables did not complete.`),s.detectAiGatewayResolution(i)},apply(e,t){return{...e,aiGatewayCredentials:t}}}}export{applyAiGatewayCredential};