import{logger as o}from"../../../tools/notifiers/logger.js";import{loadEnvVariables as g}from"../../../utils/envs/load-env-variables.js";import{CatalogEntitiesService as S}from"../../../plugins/catalog-entities/database/catalog-entities-service.js";import{ScorecardsConfigService as y}from"../../../plugins/scorecards/database/scorecards-config-service.js";import{transformEntitiesToFilter as v}from"../../../providers/database/pagination/entities-to-filter.js";const m=3e3;let c=null;async function C(i){try{const{baseDbDir:r,scorecardsConfig:t,pollingIntervalMs:a=m}=i;o.verbose(`Start Scorecards Worker: initializing (polling interval ${a}ms)`);const n=await y.getInstance({baseDbDir:r}),d=await S.getInstance({baseDbDir:r});await g(r);const s=p(t);return await E({scorecardsConfig:t,entitiesFilters:s,entitiesService:d,configService:n}),P({pollingIntervalMs:a,scorecardsConfig:t,entitiesFilters:s,entitiesService:d}),{success:!0,message:"Start Scorecards Worker: success"}}catch(r){return c&&(clearInterval(c),c=null),{success:!1,message:"Start Scorecards Worker: failed",error:r instanceof Error?r.message:String(r)}}}function p(i){const r={};for(const t of i)r[t.key]=v(t.entities);return r}async function E(i){const{configService:r,scorecardsConfig:t,entitiesFilters:a,entitiesService:n}=i,d=async s=>{await n.setEntitiesAsOutdated(a[s]),o.verbose(`Update entities as outdated: success (scorecard ${s})`)};try{await r.syncConfig(t,d),o.verbose("Sync scorecard configuration: success")}catch(s){const e=s instanceof Error?s.message:String(s);o.error(`Sync scorecard configuration: failed (${e})`)}}async function P(i){const{scorecardsConfig:r,pollingIntervalMs:t,entitiesFilters:a,entitiesService:n}=i;return c=setInterval(s,t),new Promise(()=>{});async function d(e,l){return await n.updateEntityScorecardsStatus(e.id,"CALCULATING"),await new Promise(u=>{setTimeout(async()=>{u()},1)}),await n.updateEntityScorecardsStatusIfCalculating(e.id,"UP_TO_DATE")?o.verbose(`Process entity scorecard: success (entity ${e.key}, scorecard ${l})`):(await n.updateEntityScorecardsStatus(e.id,"OUTDATED"),o.verbose(`Process entity scorecard: entity updated during calculation (entity ${e.key})`)),Promise.resolve()}async function s(){try{for(const e of r){const l=a[e.key];if(!l){o.warn(`Process scorecard: filter not found (scorecard ${e.key})`);continue}const f=await n.getOutdatedEntities(l);if(f.length===0){o.verbose(`Poll scorecards: no entities found for scorecard ${e.key}`);continue}o.verbose(`Poll scorecards: found ${f.length} entity(ies) for scorecard ${e.key}`),c&&(clearInterval(c),c=null,o.verbose(`Poll scorecards: stopped (processing ${f.length} entity(ies) for scorecard ${e.key})`));for(const u of f)await d(u,e.key)}c||(o.verbose(`Poll scorecards: resumed (interval ${t}ms)`),c=setInterval(s,t))}catch(e){const l=e instanceof Error?e.message:String(e);o.error(`Poll scorecards: failed (${l})`),c||(c=setInterval(s,t))}}}export{C as startScorecardsWorker};
