import{join}from"node:path";import{SLACK_CHANNEL_DEFAULT_ROUTE}from"#setup/scaffold/index.js";import{createPromptCommandOutput}from"#setup/cli/index.js";import{readFile}from"node:fs/promises";import{captureVercel,runVercel,runVercelCaptureStdout}from"#setup/primitives/run-vercel.js";import{updateSlackChannelConnectorUid}from"#setup/scaffold/update/update-slack-channel.js";const defaultDeps={captureVercel,runVercel,runVercelCaptureStdout},LOOKUP_TIMEOUT_MS=6e4,ATTACH_TIMEOUT_MS=2*6e4;function parseCreatedSlackConnector(e){let t=e.trim();if(!t)return;let n;try{n=JSON.parse(t)}catch{return}if(typeof n!=`object`||!n)return;let{uid:r,id:i}=n;if(!(typeof r!=`string`||typeof i!=`string`))return{uid:r,id:i}}async function readProjectId(t){try{let n=await readFile(join(t,`.vercel`,`project.json`),`utf8`),i=JSON.parse(n);return typeof i.projectId==`string`?i.projectId:void 0}catch{return}}function pickSlackConnector(e,t,n){if(typeof e!=`object`||!e)return;let r=e,i=r.connectors??r.clients;if(!Array.isArray(i))return;let a;for(let e of i){if(e.type!==`slack`||typeof e.uid!=`string`||typeof e.id!=`string`)continue;let r={uid:e.uid,id:e.id};if(n!==void 0&&r.uid===n)return r;let i=typeof e.createdAt==`number`?e.createdAt:0;t!==void 0&&Array.isArray(e.projects)&&e.projects.some(e=>typeof e==`object`&&!!e&&e.id===t)&&(!a||i>a.createdAt)&&(a={ref:r,createdAt:i})}return a?.ref}function parseInstallation(e){if(typeof e!=`object`||!e)return;let t=e.installations;if(!Array.isArray(t)||t.length===0)return;let n=t[0];if(typeof n.tenantUrl==`string`)return{workspaceUrl:n.tenantUrl,workspaceName:typeof n.tenantName==`string`?n.tenantName:void 0}}async function findSlackConnector(e,t,n,r,i){let a=await e.captureVercel([`connect`,`list`,`-F`,`json`,`--all-projects`],{cwd:t,onOutput:i,timeoutMs:LOOKUP_TIMEOUT_MS});if(a.ok)try{return pickSlackConnector(JSON.parse(a.stdout),n,r)}catch{return}}async function fetchInstallationInfo(e,t,n,r){let i=await e.captureVercel([`api`,`/v1/connex/clients/${n}/installations`],{cwd:t,onOutput:r,timeoutMs:LOOKUP_TIMEOUT_MS});if(i.ok)try{return parseInstallation(JSON.parse(i.stdout))}catch{return}}async function provisionSlackbot(e,r,i,a=defaultDeps){let o=createPromptCommandOutput(e),s=await readProjectId(r),c=`slack/${i}`;e.message(`Creating a Slackbot through Vercel Connect...`);let l=await a.runVercelCaptureStdout([`connect`,`create`,`slack`,`--triggers`,`--name`,i,`-F`,`json`],{cwd:r,onOutput:o,timeoutMs:6e5});if(!l.ok)return{kind:`create-failed`,created:!1,attached:!1};e.success(`Slackbot created via Vercel Connect.`);let u=parseCreatedSlackConnector(l.stdout);if(u||=(e.message(`Locating the Slack connector...`),await findSlackConnector(a,r,s,c,o)),!u)return e.warning("Could not locate the Slack connector. Run `vercel connect list --all-projects` to find its UID."),{kind:`connector-unresolved`,created:!0,attached:!1};if(e.info(`Slack connector: ${u.uid}`),e.message(`Configuring Slack event delivery for this agent...`),await a.runVercel([`connect`,`detach`,u.uid,`--yes`],{cwd:r,onOutput:o,timeoutMs:ATTACH_TIMEOUT_MS}),!await a.runVercel([`connect`,`attach`,u.uid,`--triggers`,`--trigger-path`,SLACK_CHANNEL_DEFAULT_ROUTE,`--yes`],{cwd:r,onOutput:o,timeoutMs:ATTACH_TIMEOUT_MS}))return e.warning(`Could not register this project as a trigger destination. Run \`vercel connect attach ${u.uid} --triggers --trigger-path ${SLACK_CHANNEL_DEFAULT_ROUTE} --yes\` to enable event delivery.`),{kind:`attach-failed`,created:!0,attached:!1,connectorUid:u.uid};e.message(`Reading Slack workspace details...`);let d=await fetchInstallationInfo(a,r,u.id,o);return d?{kind:`attached`,created:!0,attached:!0,connectorUid:u.uid,workspaceUrl:d.workspaceUrl,workspaceName:d.workspaceName}:{kind:`attached`,created:!0,attached:!0,connectorUid:u.uid}}async function reconcileSlackUid(t,n,r,i){if(r.kind!==`attached`||r.connectorUid===i)return!0;t.info(`Connect assigned UID ${r.connectorUid} (expected ${i}). Updating agent/channels/slack.ts before deployment...`);let{patched:a}=await updateSlackChannelConnectorUid(join(n,`agent/channels/slack.ts`),r.connectorUid);return a?!0:(t.warning(`Could not patch agent/channels/slack.ts automatically. Update \`connectSlackCredentials("...")\` to \`"${r.connectorUid}"\` and run \`vercel deploy --prod\`.`),!1)}export{parseCreatedSlackConnector,parseInstallation,pickSlackConnector,provisionSlackbot,reconcileSlackUid};