const { missionHelpers, pool } = require('../mariadb');

const SQUAD_TACTICS_CHECK = {
  name: 'Squad Tactics',
  skill: 'Tactics',
  characteristic: 'Int',
  target: 45,
  modifier: 0,
  rulesNote: 'Core: Tactics is an Advanced Intelligence Skill with groups such as Assault Doctrine, Defensive Doctrine, Orbital Drop Procedures, and Recon and Stealth. It gives tactical reading/positioning; it does not grant free Cohesion or Squad Mode abilities.',
  reward: 'On success, the Kill-team identifies the best tactical approach for this scene; extra Degrees of Success may reveal a safer route, priority threat, ambush vector, or better position.',
};

function hasSquadTactics(scene) {
  return (scene.checks || []).some(check => String(check.name || '').toLowerCase() === 'squad tactics');
}

function addSquadTactics(scene) {
  if (hasSquadTactics(scene)) return scene;
  return {
    ...scene,
    checks: [SQUAD_TACTICS_CHECK, ...(Array.isArray(scene.checks) ? scene.checks : [])],
  };
}

(async function main() {
  const missions = await missionHelpers.getAll();
  const targets = missions.filter(mission => mission.name === 'Vesalius Echo: Theta-92' || mission.is_active);
  const results = [];

  for (const mission of targets) {
    const scenes = Array.isArray(mission.scenes) ? mission.scenes : [];
    const nextScenes = scenes.map(addSquadTactics);
    const changed = JSON.stringify(scenes) !== JSON.stringify(nextScenes);
    if (!changed) {
      results.push({ id: mission.id, name: mission.name, changed: false });
      continue;
    }

    const ok = await missionHelpers.update(mission.id, {
      name: mission.name,
      theme: mission.theme,
      sceneCount: nextScenes.length,
      enemyCount: mission.enemy_count || 0,
      threatLevel: mission.threat_level || 'Medium',
      playerCount: mission.player_count || 4,
      scenes: nextScenes,
    });
    results.push({ id: mission.id, name: mission.name, changed: ok });
  }

  console.log(JSON.stringify({ updated: results }, null, 2));
  await pool.end();
})().catch(async error => {
  console.error(error);
  try { await pool.end(); } catch {}
  process.exit(1);
});
