import{parseSync}from"oxc-parser";const AGENT_FACTORY=`defineAgent`;function applyModelNameToSource(n,r){let i=parseSync(`agent.ts`,n,{lang:`ts`});if(i.errors.length>0){let e=i.errors[0];return{kind:`bail`,reason:`agent.ts does not parse: ${e?.message??`unknown parse error`}`,line:lineAt(n,e?.labels[0]?.start??0)}}let a=findDefineAgentObject(i.program,AGENT_FACTORY);if(a===void 0)return{kind:`bail`,reason:`no \`export default ${AGENT_FACTORY}({ ... })\` call found`,line:1};let o=findStringLiteralProperty(a,`model`);if(o===void 0)return{kind:`bail`,reason:"`model` is absent or is not a string literal (e.g. an env reference, a template, or an inlined SDK model)",line:lineAt(n,a.start)};let s=o.value;if(s===r)return{kind:`applied`,from:s,to:r,nextSource:n};let c=o.raw?.[0]===`'`?`'`:`"`,l=`${c}${escapeForQuote(r,c)}${c}`;return{kind:`applied`,from:s,to:r,nextSource:n.slice(0,o.start)+l+n.slice(o.end)}}function unwrapExpression(e){let t=e;for(;t.type===`ParenthesizedExpression`||t.type===`TSAsExpression`||t.type===`TSSatisfiesExpression`;)t=t.expression;return t}function findDefineAgentObject(e,t){for(let n of e.body){if(n.type!==`ExportDefaultDeclaration`)continue;let e=n.declaration;if(e.type!==`CallExpression`&&e.type!==`ParenthesizedExpression`&&e.type!==`TSAsExpression`&&e.type!==`TSSatisfiesExpression`)continue;let r=unwrapExpression(e);if(r.type!==`CallExpression`||!isFactoryCallee(r.callee,t))continue;let i=r.arguments[0];if(i===void 0||i.type===`SpreadElement`)continue;let a=unwrapExpression(i);if(a.type===`ObjectExpression`)return a}}function isFactoryCallee(e,t){return e.type===`Identifier`&&e.name===t}function findStringLiteralProperty(e,t){for(let n of e.properties){if(n.type!==`Property`||n.computed||!keyMatches(n.key,t))continue;let e=unwrapExpression(n.value);return e.type===`Literal`&&typeof e.value==`string`?e:void 0}}function keyMatches(e,t){return e.type===`Identifier`?e.name===t:e.type===`Literal`?typeof e.value==`string`&&e.value===t:!1}function escapeForQuote(e,t){return e.replaceAll(`\\`,`\\\\`).replaceAll(t,`\\${t}`)}function lineAt(e,t){let n=1;for(let r=0;r<t&&r<e.length;r+=1)e[r]===`
`&&(n+=1);return n}export{applyModelNameToSource};