// 액트 1 병영 대장장이와 액트 5 니흘라탁 방향 화살표 스마트 패치.
// 프리셋 JSON 전체를 덮지 않고 기존 방향 화살표 엔티티만 교체한다.

const ARROW_CODES = ["0045", "0135", "0225", "0315"];
const ARROW_PARTICLE_PREFIX = "data/hd/directionarrows/particles/directionarrows_";
const ARROW_ENTITY_ID = 2101618603;

const ARROW_PRESETS = [
  {
    filePath: "hd\\env\\preset\\act1\\court\\courte.json",
    particle: "data/hd/directionarrows/particles/directionarrows_0315.particles",
    position: { x: 259.0, z: 310.0 }
  },
  {
    filePath: "hd\\env\\preset\\act1\\court\\courtn.json",
    particle: "data/hd/directionarrows/particles/directionarrows_0045.particles",
    position: { x: 311.0, z: 242.0 }
  },
  {
    filePath: "hd\\env\\preset\\act1\\court\\courtw.json",
    particle: "data/hd/directionarrows/particles/directionarrows_0135.particles",
    position: { x: 320.0, z: 271.0 }
  },
  {
    filePath: "hd\\env\\preset\\expansion\\wildtemple\\nihle.json",
    particle: "data/hd/directionarrows/particles/directionarrows_0315.particles",
    position: { x: 455.0, z: 455.0 }
  },
  {
    filePath: "hd\\env\\preset\\expansion\\wildtemple\\nihln.json",
    particle: "data/hd/directionarrows/particles/directionarrows_0045.particles",
    position: { x: 455.0, z: 455.0 }
  },
  {
    filePath: "hd\\env\\preset\\expansion\\wildtemple\\nihls.json",
    particle: "data/hd/directionarrows/particles/directionarrows_0225.particles",
    position: { x: 455.0, z: 455.0 }
  },
  {
    filePath: "hd\\env\\preset\\expansion\\wildtemple\\nihlw.json",
    particle: "data/hd/directionarrows/particles/directionarrows_0135.particles",
    position: { x: 455.0, z: 455.0 }
  }
];

function normalizePath(value) {
  return typeof value === "string" ? value.replace(/\\/g, "/").toLowerCase() : "";
}

function entityUsesDirectionArrow(entity) {
  if (!entity || !Array.isArray(entity.components)) return false;

  return entity.components.some((component) => {
    const filename = normalizePath(component && component.filename);
    return filename.indexOf(ARROW_PARTICLE_PREFIX) === 0;
  });
}

function ensureDependency(root, group, path) {
  if (!root.dependencies || typeof root.dependencies !== "object") {
    root.dependencies = {};
  }
  if (!Array.isArray(root.dependencies[group])) {
    root.dependencies[group] = [];
  }

  const normalizedTarget = normalizePath(path);
  const exists = root.dependencies[group].some((entry) => {
    const entryPath = typeof entry === "string" ? entry : entry && entry.path;
    return normalizePath(entryPath) === normalizedTarget;
  });

  if (!exists) root.dependencies[group].push({ path });
}

function createArrowEntity(particle, position) {
  return {
    type: "Entity",
    name: "entity_root",
    id: ARROW_ENTITY_ID,
    components: [
      {
        type: "VfxDefinitionComponent",
        name: "entity_root_VfxDefinition",
        filename: particle,
        hardKillOnDestroy: false
      },
      {
        type: "TransformDefinitionComponent",
        name: "component_transform1",
        position: {
          x: position.x,
          y: 20.0,
          z: position.z
        },
        orientation: {
          x: 0.0,
          y: 0.0,
          z: 0.0,
          w: 1.0
        },
        scale: {
          x: 1.0,
          y: 1.0,
          z: 1.0
        },
        inheritOnlyPosition: false
      }
    ]
  };
}

// MPQ 원본에 포함된 파티클·텍스처 에셋만 복사한다.
ARROW_CODES.forEach((code) => {
  D2RMM.copyFile(
    `assets\\directionarrows\\particles\\directionarrows_${code}.particles`,
    `hd\\directionarrows\\particles\\directionarrows_${code}.particles`,
    true
  );
  D2RMM.copyFile(
    `assets\\directionarrows\\textures\\directionarrows_${code}.texture`,
    `hd\\directionarrows\\textures\\directionarrows_${code}.texture`,
    true
  );
});

ARROW_PRESETS.forEach((entry) => {
  const preset = D2RMM.readJson(entry.filePath);

  if (!Array.isArray(preset.entities)) preset.entities = [];

  // 다른 프리셋 요소는 보존하고 방향 화살표 엔티티만 교체한다.
  preset.entities = preset.entities.filter((entity) => !entityUsesDirectionArrow(entity));
  ensureDependency(preset, "particles", entry.particle);
  preset.entities.push(createArrowEntity(entry.particle, entry.position));

  D2RMM.writeJson(entry.filePath, preset);
});
