import{a as e}from"./bG-fsHMS.js";var t=8,n=3,r=1536;function i(e){let t=[],n=0;for(let r=0;r<e;r+=2){let i=Math.random()||1e-300,a=Math.random(),o=Math.sqrt(-2*Math.log(i)),s=2*Math.PI*a,c=o*Math.cos(s),l=o*Math.sin(s);t.push(c),n+=c*c,r+1<e&&(t.push(l),n+=l*l)}let r=Math.sqrt(n)||1;return t.map(e=>e/r)}function a(e,t){let n=0,r=Math.min(e.length,t.length);for(let i=0;i<r;i++)n+=(e[i]??0)*(t[i]??0);return n}function o(e){if(e.length===0)return null;let t=e[0]?.length??0,n=Array(t).fill(0);for(let r of e)for(let e=0;e<t;e++)n[e]=(n[e]??0)+(r[e]??0);return n.map(t=>t/e.length)}function s(e,t,n,c,l){let u=e.map(e=>e.embedding),d=o(u);if(e.length<=l||t>=c)return{depth:t,leafIds:e.map(e=>e.id),centroid:d,parentDbId:n,children:[]};let f=i(u[0]?.length??r),p=e.map(e=>({obs:e,proj:a(e.embedding,f)})),m=p.map(e=>e.proj).sort((e,t)=>e-t),h=m[Math.floor(m.length/2)]??0,g=p.filter(e=>e.proj<=h).map(e=>e.obs),_=p.filter(e=>e.proj>h).map(e=>e.obs);return g.length===0||_.length===0?{depth:t,leafIds:e.map(e=>e.id),centroid:d,parentDbId:n,children:[]}:{depth:t,leafIds:[],centroid:d,parentDbId:n,children:[s(g,t+1,null,c,l),s(_,t+1,null,c,l)]}}function c(e,t,n){let r=e.centroid?JSON.stringify(e.centroid):null,i=JSON.stringify(e.leafIds),a=new Date().toISOString(),o=t.prepare(`INSERT INTO brain_memory_trees (depth, leaf_ids, centroid, parent_id, created_at)
       VALUES (?, ?, ?, ?, ?)`).run(e.depth,i,r,n,a),s=Number(o.lastInsertRowid);for(let n of e.children)c(n,t,s);return s}function l(e,t,n,r){if(e.leafIds.length>0)for(let n of e.leafIds)r.set(n,t);if(e.children.length>0){let e=n.prepare(`SELECT id, leaf_ids FROM brain_memory_trees WHERE parent_id = ?`).all(t);for(let t of e){let e=JSON.parse(t.leaf_ids);if(e.length>0)for(let n of e)r.set(n,t.id)}}}function u(r,i={}){let{maxDepth:a=t,minLeafSize:o=n,db:u}=i,d={nodesWritten:0,obsAssigned:0,actualMaxDepth:0},f=r.filter(e=>e.embedding.length>0);if(f.length<2)return d;let p=u===void 0?e():u;if(!p)return console.warn(`[surprisal-tree] No database available; skipping tree build.`),d;try{p.exec(`DELETE FROM brain_memory_trees`);let e=s(f,0,null,a,o),t=c(e,p,null);d.nodesWritten=p.prepare(`SELECT COUNT(*) AS cnt FROM brain_memory_trees`).get()?.cnt??0,d.actualMaxDepth=p.prepare(`SELECT MAX(depth) AS maxd FROM brain_memory_trees`).get()?.maxd??0;let n=new Map;l(e,t,p,n);let r=p.prepare(`SELECT id, leaf_ids FROM brain_memory_trees WHERE leaf_ids != '[]'`).all();for(let e of r){let t=JSON.parse(e.leaf_ids);for(let r of t)n.set(r,e.id)}for(let[e,t]of n)p.prepare(`UPDATE brain_observations SET tree_id = ? WHERE id = ?`).run(t,e),d.obsAssigned++;return d}catch(e){return console.warn(`[surprisal-tree] Error building tree:`,e),d}}export{u as buildSurprisalTree};