import{writeFileSync as g,existsSync as _,mkdirSync as m}from"node:fs";import{join as d}from"node:path";import f from"chalk";var r={debug:0,info:1,warn:2,error:3,silent:4},u=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return r.debug;if(process.env.ZIBBY_VERBOSE==="true")return r.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in r?r[e]:r.info}_shouldLog(e){return r[e]>=this._level}_formatMessage(e,t,s={}){let o=new Date().toISOString(),n=`${this._getPrefix(e)} ${t}`;return Object.keys(s).length>0&&(n+=f.dim(` ${JSON.stringify(s)}`)),n}_getPrefix(e){return{debug:f.gray("[DEBUG]"),info:f.cyan("[INFO]"),warn:f.yellow("[WARN]"),error:f.red("\u274C [ERROR]")}[e]||""}debug(e,t){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,t))}info(e,t){this._shouldLog("info")&&console.log(this._formatMessage("info",e,t))}warn(e,t){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,t))}error(e,t){this._shouldLog("error")&&console.error(this._formatMessage("error",e,t))}setLevel(e){e in r&&(this._level=r[e])}getLevel(){return Object.keys(r).find(e=>r[e]===this._level)}},c=new u;var h=class l{static saveTitle(e,t){let s=e.state.sessionPath;if(!s)return;let o=l._findInState(e.state,"title")||l._findInState(e.state,"result");if(!(!o||typeof o!="string"))try{let a=d(s,"title.txt");g(a,o,"utf-8"),c.info(`Saved title to session: "${o}"`)}catch(a){console.warn("\u26A0\uFE0F  Could not save title file:",a.message)}}static _findInState(e,t){for(let[,s]of Object.entries(e))if(s&&typeof s=="object"&&s[t]!==void 0)return s[t]}static async saveExecutionData(e){let t=e.state.sessionPath;if(t)for(let[s,o]of Object.entries(e.state)){if(!o||typeof o!="object")continue;let a=Array.isArray(o.actions)&&o.actions.length>0,n=typeof o.scriptPath=="string"&&o.scriptPath.trim().length>0;if(!(!a&&!n))try{let i=d(t,s);_(i)||m(i,{recursive:!0});let p=d(i,"result.json");g(p,JSON.stringify(o,null,2),"utf-8"),c.info(`Saved execution data to ${s} folder`),await this.onNodeSaved(i,o)}catch(i){console.warn(`\u26A0\uFE0F  Could not save execution data for ${s}:`,i.message)}}}static async onNodeSaved(e,t){}static logResult(e,t){let s=Object.entries(e.state).filter(([,n])=>n&&typeof n=="object"&&n.success!==void 0),o=s.length>0&&s.every(([,n])=>n.success),a=s.some(([,n])=>n.success===!1);if(o)c.info("Workflow completed successfully."),t&&c.info(`Output: ${t}`);else if(a){let n=s.filter(([,i])=>!i.success).map(([i])=>i);c.info(`Workflow completed with failures in: ${n.join(", ")}`),t&&c.info(`Output: ${t}`)}return o}static handle(e,t,s){return this.saveTitle(e,t),this.saveExecutionData(e),this.logResult(e,s)}};export{h as ResultHandler};
