import{existsSync as l,readFileSync as f}from"node:fs";import{join as u}from"node:path";import{homedir as _}from"node:os";function A(){try{let o=u(_(),".zibby","config.json");return l(o)?JSON.parse(f(o,"utf-8")):{}}catch{return{}}}function t(o){return String(o||"").replace(/\/v1\/?$/,"")}function y(o,r){let s=process.env.OPENAI_PROXY_URL;if(s)return t(s);if(o==="session")return r.proxyUrl?t(r.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(o==="byok"){let n=process.env.OPENAI_BASE_URL;return t(n||"https://api.openai.com")}return t(s||"")}function m(){let o=A(),r=process.env.ZIBBY_USER_TOKEN||o.sessionToken||null,s=process.env.OPENAI_API_KEY||null,n=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),c=process.env.OPENAI_PROXY_NO_AUTH==="true",p=process.env.OPENAI_PROXY_URL,e="session";n==="byok"||n==="local"||n==="session"?e=n:r?e="session":s?e="byok":p&&c&&(e="local");let a=y(e,o),i={"Content-Type":"application/json"};if(e==="session"){if(!r)return{ok:!1,mode:e,reason:"missing_session_token"};i.Authorization=`Bearer ${r}`}else if(e==="byok"){if(!s)return{ok:!1,mode:e,reason:"missing_openai_api_key"};i.Authorization=`Bearer ${s}`}else if(e==="local"){if(!a)return{ok:!1,mode:e,reason:"missing_openai_proxy_url"};!c&&s&&(i.Authorization=`Bearer ${s}`)}return a?{ok:!0,mode:e,baseUrl:a,headers:i,tokenPreview:i.Authorization?`***${i.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:e,reason:"missing_base_url"}}export{m as resolveAssistantAuth};
