import{p as f}from"./chunks/db-CwROBlWC.js";import{a as c}from"./chunks/error-log-iDKIFPsV.js";import"./chunks/idb-kv-Dhbo4CRD.js";chrome.sidePanel.setPanelBehavior({openPanelOnActionClick:!1}).catch(()=>{});const o="vibefilter-background-scrape",s=10;function i(e){const r=Math.max(1,e||s);try{chrome.alarms.create(o,{delayInMinutes:1,periodInMinutes:r}),console.log(`[background] Alarm "${o}" created: every ${r} min`)}catch(a){console.error("[background] Failed to create alarm:",a)}}chrome.runtime.onInstalled.addListener(()=>{chrome.storage.sync.get({refreshInterval:s},e=>{i(e.refreshInterval)})});chrome.runtime.onStartup.addListener(()=>{chrome.storage.sync.get({refreshInterval:s},e=>{i(e.refreshInterval)})});chrome.storage.onChanged.addListener((e,r)=>{r==="sync"&&e.refreshInterval&&i(e.refreshInterval.newValue)});chrome.alarms.onAlarm.addListener(async e=>{if(e.name===o){console.log("[background] Scrape alarm fired — starting background scrape");try{await u()}catch(r){console.error("[background] Unhandled scrape error:",r)}}});let n=!1;async function l(){try{return(await chrome.runtime.getContexts({contextTypes:[chrome.runtime.ContextType.OFFSCREEN_DOCUMENT]})).length>0}catch{return!1}}async function m(){await l()||await chrome.offscreen.createDocument({url:"src/offscreen/offscreen.html",reasons:[chrome.offscreen.Reason.DOM_PARSER],justification:"Parse HTML from Korean community sites for article scraping"})}async function p(){try{await l()&&await chrome.offscreen.closeDocument()}catch{}}async function u(){if(n){console.log("[background] Scrape already in progress, skipping");return}n=!0;try{await m();let e=[];try{e=(await chrome.storage.sync.get("disabledSites")).disabledSites||[]}catch{}const r=await chrome.runtime.sendMessage({type:"scrape-all-sites",disabledSites:e});let a=[];r&&r.type==="scrape-all-done"?(a=r.errors||[],console.log(`[background] Scrape complete: ${r.articlesCount} articles, ${a.length} errors`),a.length>0&&c(a.map(t=>`[scrape] ${t}`)).catch(()=>{})):r&&r.type==="scrape-all-error"&&(console.error(`[background] Scrape failed: ${r.error}`),c([`[scrape] Fatal: ${r.error}`]).catch(()=>{}))}catch(e){console.error("[background] Error during background scrape:",e),c([`[background] ${e instanceof Error?e.message:String(e)}`]).catch(()=>{})}finally{n=!1,await p()}try{await f()}catch(e){console.warn("[background] Cleanup error:",e)}try{await chrome.runtime.sendMessage({type:"scrape-complete"})}catch{}}chrome.runtime.onMessage.addListener((e,r,a)=>{if(e.type==="trigger-scrape-now")return u().then(()=>a({type:"scrape-triggered"})).catch(t=>{console.error("[background] trigger-scrape-now failed:",t),a({type:"scrape-error",error:String(t)})}),!0;e.type==="scrape-progress"&&chrome.runtime.sendMessage(e).catch(()=>{})});
