import{pipeline,env}from"./transformers.min.js";env.useBrowserCache=!0,env.allowLocalModels=!0,env.allowRemoteModels=!1,env.localModelPath="./models/";try{env.backends&&env.backends.onnx&&env.backends.onnx.wasm&&(env.backends.onnx.wasm.numThreads=1,env.backends.onnx.wasm.wasmPaths="./")}catch(e){console.warn("[Aruana] WASM config:",e.message)}env.useBrowserCache=!1;let classifier=null,ner=null,loading=!1;async function loadPipelines(){if(!classifier)if(loading)for(;loading;)await new Promise(e=>setTimeout(e,300));else{loading=!0;try{classifier=await pipeline("text-classification","PIIrarara",{device:"wasm"});try{ner=await pipeline("token-classification","PIIranha",{device:"wasm",aggregation_strategy:"simple"})}catch(e){console.error("[Aruana AI] PIIranha FALHOU:",e)}loading=!1}catch(e){throw loading=!1,e}}}async function classify(e){await loadPipelines();var a=await classifier(e,{top_k:5}),r=Array.isArray(a[0])?a[0]:a,s=r[0],t=r.map(function(e){return{label:e.label,score:e.score}});return{topLabel:s.label,confidence:s.score,isScam:"legitima"!==s.label&&s.score>.5,categories:t.slice(0,5)}}async function detectNER(e){return await loadPipelines(),ner?(await ner(e)).filter(function(e){return e.score>.7&&e.word.length>3&&e.word.indexOf("##")<0}).map(function(e){return{entity:e.entity_group,word:e.word,score:e.score,start:e.start,end:e.end}}):[]}chrome.runtime.onMessage.addListener((e,a,r)=>!(!e||"offscreen"!==e.target)&&((async()=>{try{if("ner"===e.type){const a=await detectNER(e.text);r({ok:!0,results:a})}else if("classify"===e.type){const a=await classify(e.text);r({ok:!0,results:a.categories.map(e=>({entity:e.label,word:e.label,score:e.score,start:0,end:0})),classification:a})}}catch(e){r({ok:!1,error:e.message})}})(),!0));var stg="undefined"!=typeof chrome&&chrome.storage&&chrome.storage.local?chrome.storage.local:null;loadPipelines().then(()=>{stg&&stg.set({aruana_ai_ready:"1"});try{chrome.runtime.sendMessage({target:"background",direction:"ready",aiAvailable:!0})}catch(e){}}).catch(e=>{console.error("[Aruana] Models failed:",e.message||e),stg&&stg.set({aruana_ai_ready:"0"});try{chrome.runtime.sendMessage({target:"background",direction:"ready",aiAvailable:!1})}catch(e){}}),"undefined"!=typeof chrome&&chrome.storage&&chrome.storage.onChanged&&chrome.storage.onChanged.addListener(e=>{if(e.aruana_ai_request){var a=e.aruana_ai_request.newValue;a&&a.text&&a.id&&(async()=>{try{if("ner"===a.type){var e=await detectNER(a.text);chrome.storage.local.set({aruana_ai_response:{id:a.id,ok:!0,results:e}})}else{var r=await classify(a.text);chrome.storage.local.set({aruana_ai_response:{id:a.id,ok:!0,classification:r}})}}catch(e){chrome.storage.local.set({aruana_ai_response:{id:a.id,ok:!1,error:e.message}})}})()}});