#!/usr/bin/env node
import{existsSync as e,readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i}from"node:url";import{createLogger as a}from"../../core/dist/index.js";import{homedir as o}from"node:os";import{execFile as s}from"node:child_process";const c=a(`server`);function l(){let e=r(n(i(import.meta.url)),`..`,`..`,`..`,`package.json`);try{return JSON.parse(t(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function u(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){let t=(n[e]??0)-(r[e]??0);if(t!==0)return t>0?1:-1}return 0}function d(){let e=l();fetch(`https://registry.npmjs.org/@vpxa/aikit/latest`,{signal:AbortSignal.timeout(5e3)}).then(e=>{if(e.ok)return e.json()}).then(t=>{if(!t||typeof t!=`object`)return;let n=t.version;n&&u(e,n)<0&&c.warn(`Update available`,{currentVersion:e,latestVersion:n,updateCommand:`aikit upgrade`})}).catch(()=>{})}function f(){try{let n=r(o(),`.copilot`,`.aikit-scaffold.json`);return e(n)?JSON.parse(t(n,`utf-8`)).version??null:null}catch{return null}}function p(){try{let n=r(process.cwd(),`.github`,`.aikit-scaffold.json`);return e(n)?JSON.parse(t(n,`utf-8`)).version??null:null}catch{return null}}let m=`idle`,h=null;function g(){return{state:m,error:h}}function _(){try{let t=l(),a=f(),o=p();if(!(a!=null&&a!==t)&&!(o!=null&&o!==t)||m===`pending`||m===`success`)return;m=`pending`,h=null,c.info(`Scaffold version mismatch — auto-upgrading`,{serverVersion:t,userScaffoldVersion:a,workspaceScaffoldVersion:o});let u=n(i(import.meta.url)),d=[r(u,`..`,`..`,`..`,`bin`,`aikit.mjs`),r(u,`..`,`bin`,`aikit.mjs`),...process.argv[1]?[r(n(process.argv[1]),`aikit.mjs`)]:[]],g=d.find(t=>e(t));if(!g){m=`failed`,h=`aikit CLI binary not found. Tried: ${d.join(`, `)}`,c.warn(`Cannot auto-upgrade: aikit CLI binary not found`,{candidates:d,platform:process.platform});return}s(process.execPath,[g,`upgrade`],{timeout:3e4,windowsHide:!0},(e,n,r)=>{e?(m=`failed`,h=e.message,c.warn(`Auto-upgrade failed`,{error:e.message,stderr:r?.slice(0,500),binPath:g,platform:process.platform})):(m=`success`,h=null,c.info(`Auto-upgrade completed to version ${t}`))}).unref()}catch(e){m=`failed`,h=e instanceof Error?e.message:String(e),c.warn(`Auto-upgrade check failed`,{error:h})}}export{_ as autoUpgradeScaffold,d as checkForUpdates,l as getCurrentVersion,g as getUpgradeState};