// scripts/bestiary/seenScanner.js
import { system, world } from "@minecraft/server";
import { ENTRY_BY_ID } from "./entries.js";
import { 
  markSeen, 
  markSeenVariant, 
  hasSeen, 
  hasSeenVariant 
} from "./storage.js";
import { checkFull, checkAdvanced } from "./checkAdvanced.js";

const SCAN_INTERVAL_TICKS = 40;
const SCAN_RADIUS = 4;

export function initSeenScanner() {
  system.runInterval(() => {
    for (const player of world.getPlayers()) {

      const dim = player.dimension;
      const loc = player.location;

      const nearby = dim.getEntities({
        location: loc,
        maxDistance: SCAN_RADIUS,
        excludeTypes: ["minecraft:player"],
      });

      for (const ent of nearby) {

        const entry = ENTRY_BY_ID.get(ent.typeId);
        if (!entry) continue;

        let changed = false;

        if (!hasSeen(player, entry.id)) {
          markSeen(player, entry.id);
          changed = true;
        }

        const vars = Array.isArray(entry.variants) ? entry.variants : [];

        if (vars.length > 0) {
          let mcVariant;

          try {
            const comp = ent.getComponent("minecraft:variant");
            mcVariant = comp?.value;
          } catch {}

          if (mcVariant !== undefined) {
            const v = vars.find(x => x.detect?.mcVariant === mcVariant);

            if (v && !hasSeenVariant(player, entry.id, v.id)) {
              markSeenVariant(player, entry.id, v.id);
              changed = true;
            }
          }
        }

        if (changed) {
          checkFull(player, entry);
          checkAdvanced(player, entry);
        }
      }
    }
  }, SCAN_INTERVAL_TICKS);
}