import"./modulepreload-polyfill-B5Qt9EMX.js";import{S as f}from"./storage-pXeRtiJs.js";const l=new Map;let a=null;function s(t,n=3e3){const e=document.getElementById("status");e&&(e.textContent=t||"",e.style.display=t?"block":"none",t&&n>0&&setTimeout(()=>{e.textContent===t&&(e.textContent="",e.style.display="none")},n))}async function I(){return new Promise(t=>{chrome.storage.sync.get([f.PLATFORM_URL,f.API_KEY,f.SELECTED_PROJECT],n=>{const e=n[f.PLATFORM_URL],r=n[f.API_KEY],c=n[f.SELECTED_PROJECT];t(!e||!r||!c?null:{baseUrl:e,apiKey:r,projectId:c})})})}function P(t,n=2,e=200){if(!t)return"";const c=String(t).replace(/\n+/g," ").trim().split(new RegExp("(?<=[.!?])\\s+"));let i="",o=0;for(const m of c)if(m&&(i+=(i?" ":"")+m.trim(),o++,o>=n))break;return i.length>e&&(i=i.slice(0,e).trim()+"…"),i}function v(){const t=document.getElementById("selectedCount"),n=document.getElementById("optimizeBtn");t&&(t.textContent=`${l.size} selected`);const e=document.getElementById("userPrompt"),r=e&&e.value.trim().length>0,c=l.size>0;n&&(n.disabled=!(r&&c))}async function C(){const t=document.getElementById("searchQuery"),n=document.getElementById("searchLimit"),e=document.getElementById("resultsContainer"),r=document.getElementById("searchBtn");if(!t||!e)return;const c=t.value.trim();if(!c){s("Please enter a search term");return}const i=n?parseInt(n.value):20;if(a||(a=await I()),!a){s("Please configure the extension first (click extension icon)",0);return}s("Searching…",0),r.disabled=!0;try{const o=`${a.baseUrl}/wp-json/memory/v1/search?project_id=${encodeURIComponent(a.projectId)}&query=${encodeURIComponent(c)}&limit=${i}`,m=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${a.apiKey}`,"Content-Type":"application/json","X-Memory-Platform-Client":"browser-extension"}});if(!m.ok)throw new Error(`Search failed: ${m.status}`);const y=(await m.json()).results||[];if(y.length===0){e.innerHTML='<p style="padding: 12px; color: #94a3b8;">No memories found. Try different keywords.</p>',e.classList.remove("hidden"),s("No memories found");return}e.innerHTML="",e.classList.remove("hidden"),y.forEach(E=>{const p=E.memory_id,B=P(E.content,2,180),u=document.createElement("div");u.className="memory-item";const d=document.createElement("input");d.type="checkbox",d.id=`mem-${p}`,d.checked=l.has(p),d.addEventListener("change",()=>{d.checked?l.set(p,E):l.delete(p),v()});const h=document.createElement("div");h.className="memory-content",h.innerHTML=`
        ${B}
        <div class="memory-id">ID: ${p}</div>
      `,u.appendChild(d),u.appendChild(h),e.appendChild(u)}),s(`Found ${y.length} memories`)}catch(o){console.error("[optimizer] search error",o),s(o instanceof Error?o.message:"Search failed"),e.innerHTML='<p style="padding: 12px; color: #ef4444;">Error during search. Check console.</p>'}finally{r.disabled=!1}}async function b(){const t=document.getElementById("userPrompt"),n=document.getElementById("outputSection"),e=document.getElementById("optimizedPrompt"),r=document.getElementById("optimizeBtn");if(!t||!n||!e)return;const c=t.value.trim();if(!c){s("Please enter your question or task");return}if(l.size===0){s("Please select at least one memory");return}if(a||(a=await I()),!a){s("Please configure the extension first",0);return}s("Generating optimized prompt…",0),r.disabled=!0;try{const i=[];for(const[L]of l.entries())i.push(L);const o=document.getElementById("presetSelect"),m=document.getElementById("tokenBudget"),g=document.getElementById("modelName"),y=o?o.value:"general",E=m?parseInt(m.value||"2048"):2048,p=g&&g.value.trim()?g.value.trim():"gpt-4o-mini",B=`${a.baseUrl}/wp-json/memory/v1/optimize`,u=await fetch(B,{method:"POST",headers:{Authorization:`Bearer ${a.apiKey}`,"Content-Type":"application/json","X-Memory-Platform-Client":"browser-extension"},body:JSON.stringify({instruction:c,project_id:a.projectId,memory_ids:i,preset:y,token_budget:E,model:p})});if(!u.ok)throw new Error(`Optimization failed: ${u.status}`);const d=await u.json();if(!d||!d.optimized_prompt)throw new Error("No optimized prompt in response");e.textContent=d.optimized_prompt,n.classList.remove("hidden"),n.scrollIntoView({behavior:"smooth",block:"nearest"});const h=d.debug?.used_ai?`AI (${d.debug.model||"GPT"})`:"Local",z=d.debug?.fact_count||l.size;s(`Optimized with ${h} • ${z} memories included`)}catch(i){console.error("[optimizer] generation error",i),s(i instanceof Error?i.message:"Optimization failed"),e.textContent="Error generating optimized prompt. Please try again.",n.classList.remove("hidden")}finally{r.disabled=!1}}function w(){const t=document.getElementById("optimizedPrompt");if(!t)return;const n=t.textContent||"";if(!n){s("Nothing to copy");return}navigator.clipboard.writeText(n).then(()=>{s("✅ Copied to clipboard!")}).catch(e=>{console.error("[optimizer] copy failed",e),s("Failed to copy")})}function k(){l.clear();const t=document.getElementById("userPrompt"),n=document.getElementById("searchQuery");t&&(t.value=""),n&&(n.value="");const e=document.getElementById("outputSection"),r=document.getElementById("resultsContainer");e&&e.classList.add("hidden"),r&&(r.classList.add("hidden"),r.innerHTML=""),v(),s(""),window.scrollTo({top:0,behavior:"smooth"})}window.addEventListener("DOMContentLoaded",()=>{const t=document.getElementById("searchBtn"),n=document.getElementById("optimizeBtn"),e=document.getElementById("copyBtn"),r=document.getElementById("resetBtn"),c=document.getElementById("userPrompt");t&&t.addEventListener("click",o=>{o.preventDefault(),C()}),n&&n.addEventListener("click",o=>{o.preventDefault(),b()}),e&&e.addEventListener("click",o=>{o.preventDefault(),w()}),r&&r.addEventListener("click",o=>{o.preventDefault(),k()}),c&&c.addEventListener("input",()=>{v()});const i=document.getElementById("searchQuery");i&&i.addEventListener("keypress",o=>{o.key==="Enter"&&(o.preventDefault(),C())}),I().then(o=>{a=o,o||s("⚠️ Extension not configured. Click the extension icon to set up.",0)})});
