import{join}from"node:path";import{createPromptCommandOutput}from"#setup/cli/index.js";import{readFile}from"node:fs/promises";import{captureVercel,runVercel,runVercelCaptureStdout}from"#setup/primitives/run-vercel.js";import{updateConnectionConnectorUid}from"#setup/scaffold/update/update-connection-connector.js";function parseCreatedConnector(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}}function attachedToProject(e,t){return t===void 0||!Array.isArray(e.projects)?!1:e.projects.some(e=>typeof e==`object`&&!!e&&e.id===t)}function pickConnectConnector(e,t,n){if(typeof e!=`object`||!e)return;let r=e,i=r.connectors??r.clients;if(!Array.isArray(i))return;let a,o;for(let e of i){if(typeof e.service==`string`&&e.service!==t||typeof e.uid!=`string`||typeof e.id!=`string`)continue;let r={uid:e.uid,id:e.id},i=typeof e.createdAt==`number`?e.createdAt:0;(!o||i>o.createdAt)&&(o={ref:r,createdAt:i}),attachedToProject(e,n)&&(!a||i>a.createdAt)&&(a={ref:r,createdAt:i})}return(a??o)?.ref}async function readProjectId(t){try{let r=await readFile(join(t,`.vercel`,`project.json`),`utf8`),i=JSON.parse(r);return typeof i.projectId==`string`?i.projectId:void 0}catch{return}}async function ensureLinkedProject(e,t,n){return await readProjectId(t)||(e.message(`Linking a Vercel project for Connect...`),await runVercel([`link`],{cwd:t,onOutput:n}),readProjectId(t))}async function findConnector(e,t,n,i){let a=await captureVercel([`connect`,`list`,`-F`,`json`,`--all-projects`,`--service`,t],{cwd:e,onOutput:i});if(a.ok)try{return pickConnectConnector(JSON.parse(a.stdout),t,n)}catch{return}}async function setupConnectionConnector(e){let{log:n,projectRoot:r,slug:s,service:c,connectionFilePath:l}=e,u=createPromptCommandOutput(n),d=e.linkProject?await e.linkProject():await ensureLinkedProject(n,r,u);n.message(`Connecting ${s} via Vercel Connect...`);let f=await runVercelCaptureStdout([`connect`,`create`,c,`--name`,s,`-F`,`json`],{cwd:r,onOutput:u});if(!f.ok)return n.warning(`Could not create the connector. Run \`vercel connect create ${c} --name ${s}\`, then set the UID in agent/connections/${s}.ts.`),{kind:`create-failed`,created:!1};let p=parseCreatedConnector(f.stdout);if(p||=await findConnector(r,c,d,u),!p)return n.warning(`Could not locate the connector. Run \`vercel connect list --all-projects\` to find its UID, then set it in agent/connections/${s}.ts.`),{kind:`connector-unresolved`,created:!0};d?await runVercel([`connect`,`attach`,p.uid,`--yes`],{cwd:r,onOutput:u})||n.warning(`Created connector ${p.uid} but could not attach it to this project. Run \`vercel connect attach ${p.uid} --yes\`.`):n.warning(`Created connector ${p.uid} but no Vercel project is linked, so it isn't attached. Run \`vercel link\`, then \`vercel connect attach ${p.uid} --yes\`.`);let{patched:m}=await updateConnectionConnectorUid(l,p.uid);return m?(n.success(`Linked ${s} to ${p.uid}`),{kind:`patched`,created:!0,connectorUid:p.uid}):(n.warning(`Created connector ${p.uid}. Update \`connect("…")\` in agent/connections/${s}.ts to "${p.uid}".`),{kind:`patch-failed`,created:!0,connectorUid:p.uid})}export{parseCreatedConnector,pickConnectConnector,setupConnectionConnector};