#!/usr/bin/env node
import{createRequire as $}from"node:module";var Y=$(import.meta.url);import{execSync as X}from"node:child_process";import{existsSync as K,chmodSync as C,readFileSync as D,writeFileSync as Z,readdirSync as L}from"node:fs";import{dirname as R,resolve as G}from"node:path";import{fileURLToPath as T}from"node:url";import{homedir as U}from"node:os";import"./hooks/ensure-deps.mjs";var z=R(T(import.meta.url)),V=process.cwd();process.chdir(z);if(!process.env.PUKU_PROJECT_DIR)process.env.PUKU_PROJECT_DIR=V;if(!process.env.CONTEXT_MODE_PROJECT_DIR)process.env.CONTEXT_MODE_PROJECT_DIR=process.env.PUKU_PROJECT_DIR;if(process.env.PUKU_CONFIG_DIR&&!process.env.CONTEXT_MODE_CONFIG_DIR)process.env.CONTEXT_MODE_CONFIG_DIR=process.env.PUKU_CONFIG_DIR;var W=z.match(/^(.*[\/\\]plugins[\/\\]cache[\/\\][^\/\\]+[\/\\][^\/\\]+[\/\\])([^\/\\]+)$/);if(W)try{let A=W[1],I=W[2],H=L(A).filter((B)=>/^\d+\.\d+\.\d+/.test(B));if(H.length>1){H.sort((N,O)=>{let J=N.split(".").map(Number),E=O.split(".").map(Number);for(let q=0;q<3;q++)if((J[q]??0)!==(E[q]??0))return(J[q]??0)-(E[q]??0);return 0});let B=H[H.length-1];if(B&&B!==I){let N=G(U(),".puku-cli","plugins","installed_plugins.json"),O=JSON.parse(D(N,"utf-8"));for(let[J,E]of Object.entries(O.plugins||{})){if(!J.toLowerCase().includes("context-mode"))continue;for(let q of E)q.installPath=G(A,B),q.version=B,q.lastUpdated=new Date().toISOString()}Z(N,JSON.stringify(O,null,2)+`
`,"utf-8")}}}catch{}for(let A of["turndown","turndown-plugin-gfm","@mixmark-io/domino"])if(!K(G(z,"node_modules",A)))try{X(`npm install ${A} --no-package-lock --no-save --silent`,{cwd:z,stdio:"pipe",timeout:120000})}catch{}if(!K(G(z,"cli.bundle.mjs"))&&K(G(z,"build","cli.js"))){let A=G(z,"cli.bundle.mjs");if(Z(A,`#!/usr/bin/env node
await import("./build/cli.js");
`),process.platform!=="win32")C(A,493)}{let A=process.stdout.write.bind(process.stdout);process.stdout.write=function(I,H,B){try{let J=(typeof I==="string"?I:I.toString("utf8")).split(`
`).map((E)=>{if(!E.trim())return E;try{let q=JSON.parse(E);if(q?.result?.serverInfo?.name)q.result.serverInfo.name="smart-context";if(Array.isArray(q?.result?.content)){for(let Q of q.result.content)if(typeof Q?.text==="string")Q.text=Q.text.replace(/^⚠️ context-mode v[^\n]+\n\n/,"")}return JSON.stringify(q)}catch{return E}});return A(J.join(`
`),H,B)}catch{return A(I,H,B)}}}if(K(G(z,"server.bundle.mjs")))await import("./server.bundle.mjs");else{if(!K(G(z,"node_modules")))try{X("npm install --silent",{cwd:z,stdio:"pipe",timeout:60000})}catch{}if(!K(G(z,"build","server.js")))try{X("npx tsc --silent",{cwd:z,stdio:"pipe",timeout:30000})}catch{}await import("./build/server.js")}
