import{detectDeployment,isProjectResolved,mergeProjectResolution,projectResolutionFromDeployResult,projectResolutionFromDeployment}from"../project-resolution.js";import{hasVercelProject,requireProjectPath}from"../state.js";import{createPromptCommandOutput}from"#setup/cli/index.js";import{HumanActionRequiredError}from"#setup/human-action.js";import{runVercel}from"#setup/primitives/run-vercel.js";import{runPnpmInstall}from"#setup/primitives/run-pnpm.js";const VERCEL_DEPLOY_ENV={VERCEL_USE_EXPERIMENTAL_FRAMEWORKS:`1`};function deployProject(a){let o=a.deps??{runVercel,runPnpmInstall,detectDeployment};return{id:`deploy-project`,shouldRun(e){return a.skip||!e.deploymentPending?!1:hasVercelProject(e)||a.ensureLinkedProject===`interactive-vercel-link`},async gather(){return{headless:a.headless??!1}},async perform({state:e,input:n}){let r=requireProjectPath(e),{log:i}=a.prompter,s=createPromptCommandOutput(i),c=e.project;if(!isProjectResolved(c)){if(n.headless)throw new HumanActionRequiredError({kind:`vercel-link`,command:`vercel link`,reason:`Deployment needs this directory linked to a Vercel project.`});if(i.message(`Linking this directory to a Vercel project before deployment...`),!await o.runVercel([`link`],{cwd:r})||(c=mergeProjectResolution(c,projectResolutionFromDeployment(await o.detectDeployment(r))),!isProjectResolved(c)))throw Error(`Vercel project linking failed. Deployment did not start.`)}if(!e.deploymentDependenciesInstalled&&(i.message(`Installing project dependencies before deployment (pnpm install)...`),!await o.runPnpmInstall(r,{onOutput:s})))throw Error(`Dependency installation failed. Deployment did not start.`);i.message(`Deploying the agent to Vercel production...`);let l=n.headless?[`deploy`,`--prod`,`--yes`,`--non-interactive`]:[`deploy`,`--prod`,`--yes`];if(!await o.runVercel(l,{cwd:r,extraEnv:VERCEL_DEPLOY_ENV,nonInteractive:n.headless,onOutput:s}))throw i.error("`vercel deploy --prod` failed. The deploy output above shows the cause; fix it, then run `vercel deploy --prod` to retry."),Error(`Deployment failed after channel setup.`);i.message(`Pulling Vercel environment variables into .env.local...`),await o.runVercel([`env`,`pull`,`--yes`],{cwd:r,nonInteractive:n.headless,onOutput:s})||i.warning(`Deployment succeeded, but pulling Vercel environment variables did not complete.`);let u=await o.detectDeployment(r);u.state===`deployed`&&u.productionUrl!==void 0&&i.info(`Production URL: ${u.productionUrl}`);let d=u.state===`deployed`,f=projectResolutionFromDeployResult(c,{deployed:d,productionUrl:u.productionUrl});if(!d)throw Error(`Deployment failed after channel setup.`);return{project:f,deploymentPending:!1,deploymentDependenciesInstalled:!0}},apply(e,t){return{...e,project:t.project,deploymentPending:t.deploymentPending,deploymentDependenciesInstalled:t.deploymentDependenciesInstalled}}}}export{deployProject};