// scripts/create-admin.ts
import { randomBytes as randomBytes2 } from "node:crypto";

// src/server/db.ts
import pg from "pg";

// src/server/env.ts
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
var loaded = false;
function loadEnv() {
  if (loaded) return;
  loaded = true;
  const file = path.join(process.cwd(), ".env");
  if (!existsSync(file)) return;
  for (const line of readFileSync(file, "utf8").split(/\r?\n/)) {
    if (!line || line.startsWith("#") || !line.includes("=")) continue;
    const k = line.slice(0, line.indexOf("="));
    if (process.env[k] === void 0) process.env[k] = line.slice(line.indexOf("=") + 1);
  }
}
function config() {
  loadEnv();
  const baseUrl = process.env.APP_BASE_URL ?? "http://127.0.0.1:3140";
  return {
    databaseUrl: process.env.DATABASE_URL ?? "",
    baseUrl,
    port: Number(process.env.APP_PORT ?? 3140),
    secureCookies: baseUrl.startsWith("https://"),
    sessionDays: Number(process.env.SESSION_DAYS ?? 30),
    registrationMode: process.env.REGISTRATION_MODE === "invitation" ? "invitation" : "ouverte",
    allowedOrigins: allowedOrigins(baseUrl)
  };
}
function allowedOrigins(baseUrl) {
  const out = /* @__PURE__ */ new Set([new URL(baseUrl).origin]);
  for (const raw of (process.env.APP_EXTRA_ORIGINS ?? "").split(",")) {
    const v = raw.trim();
    if (!v) continue;
    try {
      const u = new URL(v);
      if (u.protocol === "http:" || u.protocol === "https:") out.add(u.origin);
    } catch {
    }
  }
  return [...out];
}

// src/server/db.ts
var g = globalThis;
function pool() {
  if (!g.__vileriaPool) {
    const url = config().databaseUrl;
    if (!url) throw new Error("DATABASE_URL manquant (ex\xE9cuter npm run local:setup).");
    g.__vileriaPool = new pg.Pool({ connectionString: url, max: 10 });
  }
  return g.__vileriaPool;
}
async function q(sql, params = []) {
  return (await pool().query(sql, params)).rows;
}

// src/server/auth.ts
import { createHash, randomBytes, scrypt as scryptCb, timingSafeEqual } from "node:crypto";
import { promisify } from "node:util";
import { z } from "zod";

// src/server/audit.ts
async function audit(userId, action, details = {}, ip = null) {
  await q("INSERT INTO audit_log(user_id, action, details, ip) VALUES ($1,$2,$3,$4)", [userId, action, JSON.stringify(details), ip]);
}

// src/server/auth.ts
var scrypt = promisify(scryptCb);
var N = 16384;
var RR = 8;
var P = 1;
var KEYLEN = 64;
async function hashPassword(pw) {
  const salt = randomBytes(16);
  const key2 = await scrypt(pw, salt, KEYLEN, { N, r: RR, p: P, maxmem: 64 * 1024 * 1024 });
  return `scrypt$${N}$${RR}$${P}$${salt.toString("base64")}$${key2.toString("base64")}`;
}
var usernameSchema = z.string().trim().regex(/^[A-Za-z0-9_.-]{3,24}$/, "Identifiant : 3 \xE0 24 caract\xE8res (lettres, chiffres, _ . -).");
var passwordSchema = z.string().min(10, "Mot de passe : 10 caract\xE8res minimum.").max(200);
var registerSchema = z.object({
  username: usernameSchema,
  displayName: z.string().trim().min(2).max(40).optional(),
  email: z.string().trim().email().max(200).optional().or(z.literal("")),
  password: passwordSchema,
  invite: z.string().regex(/^[A-Za-z0-9_-]{20,64}$/).optional()
  // jeton du lien d'invitation (mode « invitation »)
}).strict();
var DUMMY_HASH = "scrypt$16384$8$1$AAAAAAAAAAAAAAAAAAAAAA==$" + Buffer.alloc(64).toString("base64");

// src/server/migrate.ts
import { readdirSync, readFileSync as readFileSync2 } from "node:fs";
import path2 from "node:path";

// src/engine/types.ts
var FACTION_IDS = ["skoldaris", "corbiens", "hesperides", "taldars", "velmoreens", "visiliens"];
var UNIT_TYPES = ["infanterie", "chevalier", "elite", "siege", "executeur"];
var BUILDING_TYPES = ["caserne", "fort", "fortification"];
var WONDER_IDS = [
  "obelisque",
  "hall",
  "bibliotheque",
  "bastion",
  "colisee",
  "laboratoire",
  "tour_ivoire",
  "palais",
  "autel",
  "tresor"
];

// src/engine/hex.ts
var HEX_DIRS = [[1, 0], [1, -1], [0, -1], [-1, 0], [-1, 1], [0, 1]];
function neighborLinks(cells) {
  const byPos = new Map(cells.map((c) => [`${c.q},${c.r}`, c.id]));
  const links = [];
  for (const c of cells) {
    for (const [dq, dr] of HEX_DIRS) {
      const other = byPos.get(`${c.q + dq},${c.r + dr}`);
      if (other && c.id < other) links.push([c.id, other]);
    }
  }
  return links;
}

// src/engine/rules-default.ts
var g2 = (gold, moralith = 0) => ({ gold, moralith });
var factions = {
  skoldaris: {
    id: "skoldaris",
    name: "Sk\xF6ldaris",
    color: "#3d7fb8",
    colorDark: "#1d3f5e",
    motto: "Le fer et la temp\xEAte",
    modifiers: []
    // 3.0 : aucun trait de faction (voir les héros)
  },
  corbiens: {
    id: "corbiens",
    name: "Corbiens",
    color: "#3f8f4e",
    colorDark: "#1f4727",
    motto: "Les racines se souviennent",
    modifiers: []
    // 3.0 : aucun trait de faction (voir les héros)
  },
  hesperides: {
    id: "hesperides",
    name: "Hesp\xE9rides",
    color: "#e8e1cf",
    colorDark: "#7a6f55",
    motto: "Par la loi et le marbre",
    modifiers: []
    // 3.0 : aucun trait de faction (voir les héros)
  },
  taldars: {
    id: "taldars",
    name: "Taldars",
    color: "#d9a520",
    colorDark: "#6e520c",
    motto: "Sous la lune, l'or",
    modifiers: []
    // 3.0 : aucun trait de faction (voir les héros)
  },
  velmoreens: {
    id: "velmoreens",
    name: "Velmor\xE9ens",
    color: "#c8442f",
    colorDark: "#651f14",
    motto: "La gloire ou la cendre",
    // Décision EMAP du 2026-11-16 (variante C adoptée) : un chevalier de plus dans l'armée de départ (nouvelles parties).
    // Pouvoirs de Lucha inchangés (variante D rejetée).
    modifiers: [{ type: "startingUnits", unit: "chevalier", count: 1 }],
    boardNote: "D\xE9part : 2 fantassins et 1 chevalier (d\xE9cision du 16/11/2026, variante C)."
  },
  visiliens: {
    id: "visiliens",
    name: "Empire Visilien",
    color: "#7a3fa0",
    colorDark: "#3a1b4e",
    motto: "L'Empire n'a pas de fronti\xE8re",
    modifiers: []
    // 3.0 : aucun trait de faction (voir les héros)
  }
};
var hero = (c) => ({
  id: c.id,
  name: c.name,
  title: c.title,
  faction: c.faction,
  category: "heros",
  portrait: `/heros-4.0/${c.id}.png`,
  power: c.power,
  description: c.power,
  levels: [c.effects, []],
  implemented: true
});
var characters = [
  hero({ faction: "hesperides", id: "selene", name: "S\xE9l\xE8ne", title: "Imp\xE9ratrice", power: "+1 pi\xE8ce d'or \xE0 chaque d\xE9but de tour (passif).", effects: [{ type: "passiveGold", gold: 1 }] }),
  hero({ faction: "hesperides", id: "andreas", name: "Andreas", title: "Fils prodigue", power: "+1 or par mine contr\xF4l\xE9e (au d\xE9but de chaque tour).", effects: [{ type: "goldPerMine", gold: 1 }] }),
  hero({ faction: "hesperides", id: "gabrielle", name: "Gabrielle", title: "Archiviste", power: "+1 attaque pour les unit\xE9s d'\xE9lite par carte bonus en main (en attaque).", effects: [{ type: "eliteAttackPerCard", bonus: 1 }] }),
  hero({ faction: "hesperides", id: "hectelion", name: "H\xE9ct\xE8lion", title: "Prince de la cit\xE9", power: "+1 d'attaque par merveille construite (en attaque, vos merveilles).", effects: [{ type: "attackPerWonder", bonus: 1 }] }),
  hero({ faction: "velmoreens", id: "izora", name: "Izora", title: "Premi\xE8re astronome", power: "Gagne 1 chevalier par caserne ou fortin construit.", effects: [{ type: "infantryAfterBuilding", unit: "chevalier" }] }),
  hero({ faction: "velmoreens", id: "lucha", name: "Lucha", title: "Prince h\xE9ritier", power: "+1 d'attaque \xE0 tous vos chevaliers.", effects: [{ type: "unitAttackBonus", unit: "chevalier", bonus: 1 }] }),
  hero({ faction: "velmoreens", id: "hernan", name: "Hernan", title: "Lieutenant strat\xE8ge", power: "Deux chevaliers peuvent \xEAtre transform\xE9s en unit\xE9 d'\xE9lite.", effects: [{ type: "convertKnightsToElite" }] }),
  hero({ faction: "velmoreens", id: "raul", name: "Raul de Gaya", title: "Grand inquisiteur", power: "Recrute gratuitement deux unit\xE9s (hors \xE9lite) par merveille construite.", effects: [{ type: "freeUnitsPerWonder", count: 2 }] }),
  hero({ faction: "taldars", id: "yaznara", name: "Yaznara", title: "Sorci\xE8re du d\xE9sert", power: "Les b\xE2timents vous co\xFBtent une pi\xE8ce d'or en moins.", effects: [{ type: "buildingCostDelta", gold: -1 }] }),
  hero({ faction: "taldars", id: "malazir", name: "Mal'Azir", title: "Grand vizir", power: "+1 d'attaque par type d'unit\xE9 diff\xE9rent dans ses arm\xE9es.", effects: [{ type: "attackPerDistinctUnitType", bonus: 1 }] }),
  hero({ faction: "taldars", id: "alfalek", name: "Al Falek", title: "Le joaillier", power: "Peut \xE9changer quinze pi\xE8ces d'or contre un Moralith.", effects: [{ type: "goldToMoralithExchange", gold: 15 }] }),
  hero({ faction: "taldars", id: "mansa", name: "Mansa Al'Azir", title: "Le conqu\xE9rant", power: "R\xE9cup\xE8re la valeur de l'arm\xE9e battue en or.", effects: [{ type: "goldFromBeatenArmy" }] }),
  hero({ faction: "visiliens", id: "maelia", name: "Maelia", title: "Reine visilienne", power: "+1 or par unit\xE9 d'\xE9lite d\xE9ploy\xE9e (au d\xE9but de chaque tour).", effects: [{ type: "goldPerElite", gold: 1 }] }),
  hero({ faction: "visiliens", id: "varkos", name: "Varkos", title: "G\xE9n\xE9ral brutal", power: "Les chevaliers ont 3 en attaque mais 1 en d\xE9fense.", effects: [{ type: "knightStats", attack: 3, defense: 1 }] }),
  hero({ faction: "visiliens", id: "ozrik", name: "Ozrik", title: "Tisseur de v\xE9rit\xE9s", power: "+2 en d\xE9fense pour les casernes. Les fortins peuvent recruter.", effects: [{ type: "casernDefenseBonus", bonus: 2 }, { type: "fortRecruit" }] }),
  hero({ faction: "visiliens", id: "darian", name: "Darian Ier", title: "Roi visilien", power: "Recrute une unit\xE9 d'\xE9lite lorsque vous avez constitu\xE9 votre premi\xE8re arm\xE9e de 5 unit\xE9s.", effects: [{ type: "eliteOnFirstFullArmy" }] }),
  hero({ faction: "skoldaris", id: "vagnar", name: "Vagnar", title: "Le fl\xE9au", power: "+1 d'attaque dans toutes ses arm\xE9es.", effects: [{ type: "armyAttackBonus", minUnits: 0, bonus: 1 }] }),
  hero({ faction: "skoldaris", id: "hilda", name: "Hilda", title: "Ravageuse", power: "+1 or au d\xE9but de chaque tour par tranche de 5 territoires contr\xF4l\xE9s.", effects: [{ type: "goldPerTerritories", per: 5, gold: 1 }] }),
  hero({ faction: "skoldaris", id: "filkja", name: "Filkja", title: "Ravageuse", power: "+3 or apr\xE8s avoir jou\xE9 une carte bonus.", effects: [{ type: "goldAfterCard", gold: 3 }] }),
  hero({ faction: "skoldaris", id: "erik", name: "Erik", title: "Ma\xEEtre forgeron", power: "+1 d'attaque aux unit\xE9s d'\xE9lite par unit\xE9 perdue dans la partie.", effects: [{ type: "eliteAttackPerLoss", bonus: 1 }] }),
  hero({ faction: "corbiens", id: "telmor", name: "Tel'Mor", title: "Spectre", power: "Double les p\xE9nalit\xE9s ennemies au combat.", effects: [{ type: "doubleEnemyLosses" }] }),
  hero({ faction: "corbiens", id: "draeven", name: "Draeven", title: "Proph\xE8te", power: "+1 d'attaque par Moralith dans son stock pour les unit\xE9s d'\xE9lite (bonus plafonn\xE9 \xE0 +8 par \xE9lite).", effects: [{ type: "eliteAttackPerMoralith", perMoralith: 1, maxBonus: 8 }] }),
  hero({ faction: "corbiens", id: "vaktar", name: "Vaktar", title: "Ma\xEEtre des ruses", power: "+1 or par Moralith en stock (au d\xE9but de chaque tour).", effects: [{ type: "goldPerMoralith", gold: 1 }] }),
  hero({ faction: "corbiens", id: "danyra", name: "Danyra", title: "Mage noire", power: "Peut recruter les p\xE9nalit\xE9s ennemies au combat.", effects: [{ type: "recruitEnemyLosses" }] })
];
var wonders = [
  { id: "obelisque", name: "Ob\xE9lisque des \xC2ges", description: "Les unit\xE9s d'\xE9lite passent \xE0 6 d'attaque.", cost: g2(15, 1) },
  { id: "hall", name: "Hall des B\xE2tisseurs", description: "Permet de construire gratuitement 1 caserne et 1 fortin.", cost: g2(15, 1) },
  { id: "bibliotheque", name: "Grande Biblioth\xE8que", description: "\xC0 sa construction, rapporte la valeur en or de tous vos b\xE2timents construits (hors merveilles) ; 0 or si vous n'en avez aucun. (4.0, provisoire)", cost: g2(15, 2) },
  { id: "bastion", name: "Bastion", description: "+2 de d\xE9fense aux territoires adjacents \xE0 une de vos casernes.", cost: g2(15, 2) },
  { id: "colisee", name: "Colis\xE9e", description: "+3 d'attaque \xE0 vos arm\xE9es.", cost: g2(20, 2) },
  { id: "laboratoire", name: "Laboratoire", description: "Choisissez une carte bonus.", cost: g2(20, 2) },
  { id: "tour_ivoire", name: "Tour d'Ivoire", description: "Les ennemis ne peuvent pas jouer de cartes bonus contre vous.", cost: g2(15, 3) },
  { id: "palais", name: "Palais imp\xE9rial", description: "N\xE9cessite la capitale. Permet de recruter l'Ex\xE9cuteur dans votre fief.", cost: g2(10, 4), requiresCapital: true },
  { id: "autel", name: "Autel sacrificiel", description: "Sacrifiez une unit\xE9 ou un b\xE2timent pour r\xE9cup\xE9rer son co\xFBt en or. (6 joueurs)", cost: g2(15, 1), sixPlayersOnly: true },
  { id: "tresor", name: "Tr\xE9sor imp\xE9rial", description: "Vos mines d'or produisent 5 or par tour. (6 joueurs) Mines vierges : 2 or par tour, sans majoration (arbitrage du 16/11/2026).", cost: g2(15, 2), sixPlayersOnly: true }
];
var card = (c) => ({ copies: 1, usableBy: "hors_combat", status: "actif", ...c });
var cards = [
  card({ id: "chatiment", name: "Ch\xE2timent des dieux", kind: "justice", image: "/cartes/chatiment.png", description: "Renvoyez les unit\xE9s d'\xE9lite ennemies dans leur fief.", effect: { type: "returnEnemyElites" } }),
  card({ id: "voix-du-sang", name: "La voix du sang", kind: "combat", image: "/cartes/voix-du-sang.png", description: "Si vous remportez un combat, vous pouvez recruter, gratuitement, deux unit\xE9s diff\xE9rentes dans votre caserne la plus proche.", effect: { type: "freeUnitsAfterVictory", count: 2, allowed: ["infanterie", "chevalier"] } }),
  card({ id: "frenesie", name: "Fr\xE9n\xE9sie", kind: "combat", image: "/cartes/frenesie.png", description: "Vos unit\xE9s d'\xE9lite gagne +2 d'attaque lors du prochain combat\u2026", effect: { type: "nextCombatUnitBonus", unit: "elite", bonus: 2 } }),
  card({ id: "pretre", name: "Pr\xEAtre Morgharien", kind: "combat", image: "/cartes/pretre.png", description: "Retournez l'effet d'une carte bonus contre son utilisateur.", effect: { type: "reverseCard" }, usableBy: "defenseur" }),
  card({ id: "caravane", name: "Caravane oubli\xE9e", kind: "economie", image: "/cartes/caravane.png", description: "Gagnez quinze pi\xE8ces d'or.", effect: { type: "gainGold", amount: 15 } }),
  card({ id: "un-en-avant", name: "Un en avant, deux en arri\xE8re", kind: "combat", image: "/cartes/un-en-avant.png", description: "Activable avant un combat : vous faites reculer l'arm\xE9e ennemie de deux zones.", effect: { type: "pushBack", zones: 2 }, usableBy: "les_deux" }),
  card({ id: "mutinerie", name: "Mutinerie", kind: "combat", image: "/cartes/mutinerie.png", description: "R\xE9duit l'attaque de tous les fantassins ennemis \xE0 z\xE9ro lors de votre prochaine attaque.", effect: { type: "nextAttackEnemyUnitZero", unit: "infanterie" } }),
  card({ id: "vol-a-la-tire", name: "Vol \xE0 la tire", kind: "economie", image: "/cartes/vol-a-la-tire.png", description: "Voler un \xE0 deux joueurs diff\xE9rents.", effect: { type: "stealCards", maxTargets: 2 } }),
  card({ id: "soutien", name: "Soutien", kind: "combat", image: "/cartes/soutien.png", description: "Renforce l'arm\xE9e d'une autre faction lors d'un combat +3 attaque.", effect: { type: "supportCombat", power: 3 } }),
  card({ id: "ralliement", name: "Ralliement", kind: "economie", image: "/cartes/ralliement.png", description: "Recrutez deux unit\xE9s gratuitement (hors \xE9lite).", effect: { type: "freeUnits", count: 2, allowed: ["infanterie", "chevalier"] } }),
  card({ id: "corne", name: "Corne de guerre", kind: "combat", image: "/cartes/corne.png", description: "Effectuez un deuxi\xE8me d\xE9placement durant ce tour.", effect: { type: "extraMove" } }),
  card({ id: "investissement", name: "Investissement judicieux", kind: "economie", image: "/cartes/investissement.png", description: "Toutes vos unit\xE9s d'\xE9lites d\xE9ploy\xE9es vous rapportent cinq pi\xE8ces d'or.", effect: { type: "goldPerOwnUnit", unit: "elite", gold: 5 } }),
  card({ id: "invasion", name: "Invasion", kind: "combat", image: "/cartes/invasion.png", description: "Vous gagnez +2 d'attaque sur tous vos combats durant ce tour.", effect: { type: "turnAttackBonus", power: 2 } }),
  card({ id: "invasion-controlee", name: "Invasion contr\xF4l\xE9e", kind: "combat", image: "/cartes/invasion-controlee.png", description: "Vous gagnez +3 d'attaque pour votre prochain combat.", effect: { type: "nextCombatBonus", power: 3 } }),
  card({ id: "palissades", name: "Palissades \xE9ph\xE9m\xE8res", kind: "combat", image: "/cartes/palissades.png", description: "Pi\xE9ger une zone qu'aucune unit\xE9 ne pourra traverser pendant ce tour.", effect: { type: "blockZone" } }),
  card({ id: "charge", name: "Charge de cavalerie", kind: "combat", image: "/cartes/charge.png", description: "L'attaque de vos chevaliers est doubl\xE9e pour le prochain combat.", effect: { type: "nextCombatUnitFactor", unit: "chevalier", factor: 2 } }),
  card({ id: "sabotage", name: "Sabotage", kind: "justice", image: "/cartes/sabotage.png", description: "Annule l'effet d'une merveille ennemie.", effect: { type: "neutralizeWonder" } }),
  card({ id: "depouillement", name: "D\xE9pouillement", kind: "justice", image: "/cartes/depouillement.png", description: "Volez une carte bonus ennemie apr\xE8s l'avoir d\xE9fait au combat.", effect: { type: "stealAfterVictory" } }),
  card({ id: "malice", name: "Malice", kind: "justice", image: "/cartes/malice.png", description: "Les r\xE9coltes de Moralith sont impossibles.", effect: { type: "blockMoralithHarvest" } }),
  card({ id: "chantage", name: "Chantage", kind: "economie", image: "/cartes/chantage.png", description: "Chaque joueur vous donne 3 pi\xE8ces d'or par Moralith dans sa r\xE9serve. Pour chaque tranche de 3 or non pay\xE9e, ils perdent 1 unit\xE9.", effect: { type: "blackmail", goldPerMoralith: 3 } })
];
var DEFAULT_RULES = {
  label: "VILERIA 4.0 \u2014 16/11/2026 : quatre h\xE9ros par faction, deux choisis, un pouvoir chacun (arbitrages Q1 \xE0 Q17) ; Grande Biblioth\xE8que provisoire ; reprend VILERIA 3.0 \u2014 16/11/2026 : victoire \xE0 4 fiefs, d\xE9fausse des cartes bonus, Andreas +1/merveille, si\xE8ge retir\xE9, chevalier velmor\xE9en, arbitrages des mines ; arbitrages du 2026-11-15 (r\xE9colte d'or +1, Varkos -1/+2 et blocage du Moralith) ; h\xE9ros, Moralith et cartes bonus ; r\xE8gles communes 2.7.1 : \xE9limination sans victoire, fiefs neutres d\xE9fendus, dernier joueur en lice ; reprend VILERIA 2.7 : une attaque par arm\xE9e, fortifications-murs, d\xE9fense fixe des fiefs de d\xE9part (2), lieux saints sans bonus, aucune construction sur fief, lieu saint ou capitale (D37), victoire par la Capitale tenue 5 tours",
  players: { min: 3, max: 6 },
  start: { gold: 10, moralith: 0, units: [{ unit: "infanterie", count: 2 }] },
  // Arbitrage du 2026-11-15 : chaque récolte d'or rapporte 1 or de plus (5 → 6). Revenus passifs (Gabrielle, Hilda), coûts et autres sources inchangés.
  economy: { harvestGold: 6, harvestMoralithHolySite: 1, harvestMoralithCapital: 2, bothHarvestsSameTurn: false },
  units: {
    infanterie: { name: "Infanterie", attack: 1, cost: g2(3) },
    chevalier: { name: "Chevalier", attack: 2, cost: g2(5) },
    elite: { name: "\xC9lite", attack: 4, cost: g2(8, 1) },
    // 2026-11-16 : unités de siège retirées des NOUVELLES parties (définition conservée pour l'affichage ; jamais recrutables ni accordées).
    // Les parties créées avant gardent leur propre version des règles (rulesets en base), siège compris.
    siege: { name: "Si\xE8ge", attack: 2, cost: g2(6), retired: true },
    executeur: { name: "Ex\xE9cuteur", attack: 10, cost: g2(20, 2), uniquePerPlayer: true, requiresCapital: true, lostWithCapital: true, reRecruitAfterLoss: true }
  },
  army: { maxUnits: 5, lossPriority: ["infanterie", "chevalier", "elite", "executeur"], eliteLimitPerPlayer: 2 },
  // décision EMAP 2026-11-09 : 2 élites par joueur (Ozrik niv. 2 : 3)
  // 2.7 : attacksPerTurn n'est plus utilisé (attackLimit = "armee" : une attaque par armée et par tour).
  movement: { stepsPerTurn: 1, attacksPerTurn: 1, undefendedCaptureCountsAsAttack: false, attackLimit: "armee", wallsBlock: true },
  combat: {
    tieAttackerLosses: 1,
    lossTable: [{ minDiff: 1, losses: 0 }, { minDiff: 2, losses: 1 }, { minDiff: 4, losses: 2 }],
    defenderLoser: "retreat_or_destroy",
    colisseumAppliesTo: "attaque",
    fiefFixedDefense: 2,
    neutralFiefDefense: true
    // 2.7.1 (commun) : les fiefs neutres (factions absentes ou fiefs redevenus neutres) se défendent avec 2
  },
  limits: { buildsPerTurn: 1, noBuildOn: ["fief", "lieu_saint", "capitale"] },
  // D37 : aucun bâtiment ni fortification sur ces cases (merveilles non concernées)
  recruitment: { allowedIn: "fief_ou_caserne" },
  buildings: {
    // Grille des cartons de faction V1.1 (décision EMAP 2026-11-09) : caserne 6 or (2 max), fortin 5 or (3 max, défense 3), fortification 4 or (4 max).
    caserne: { name: "Caserne", cost: g2(6), limitPerPlayer: 2, defense: 0 },
    fort: { name: "Fortin", cost: g2(5), limitPerPlayer: 3, defense: 3 },
    fortification: { name: "Fortification", cost: g2(4), limitPerPlayer: 4, defense: 1 }
  },
  mine: { levels: [{ production: 1, upgradeCost: 0 }, { production: 2, upgradeCost: 3 }, { production: 3, upgradeCost: 5 }], productionAtTurnStart: true, enabled: false },
  // 2.7 : bonuses=false — les lieux saints ne donnent que du Moralith (et comptent pour la victoire). Valeurs ci-dessous conservées pour l'historique, sans effet.
  holySites: { forceAttackBonus: 1, sagesseGoldPerMoralith: 4, sagesseMoralithToGold: 3, fertiliteGoldReduction: 1, bonuses: false },
  wonders: { catalog: wonders, requireHolySiteForEffects: true, uniquePerGame: true, bastionBonus: 2, colisseumBonus: 3, obeliskEliteAttack: 6, tresorMineProduction: 5 },
  characters: { upgradeCost: g2(0, 1), changeCost: g2(5), catalog: characters, heroes: true, pick: 2 },
  // 4.0 : 2 héros choisis sur 4, sans amélioration // 3.0 : coût réel par héros (upgradeCost du héros)
  cards: { bonusCardCost: g2(0, 2), usedReturnToDeck: false, catalog: cards, catalogProvisional: false },
  // 3.0 : carte bonus à 2 Moralith ; plus de cartes événements
  fief: { eliminationDelayRounds: 1 },
  // 2.7 : contrôle prolongé = la Capitale pendant 5 tours consécutifs (les lieux saints ne comptent plus pour la victoire).
  // 2.7.1 (commun à la 3.0) : l'élimination ne fait plus gagner ; le dernier joueur en lice gagne immédiatement.
  elimination: { destroyBuildings: ["caserne", "fort"], destroyWonders: true, resourcesLost: true, lastStandingWins: true },
  victory: { holySiteTurns: 5, fiefsToControl: 4, wondersToBuild: 4, eliminationWins: false, holdKind: "capitale" },
  factions,
  provisional: [
    "start",
    "units.executeur.cost",
    "army.lossPriority",
    "movement.undefendedCaptureCountsAsAttack",
    "combat.colisseumAppliesTo",
    "limits.buildsPerTurn",
    "recruitment.allowedIn",
    "buildings.fortification.defense",
    "mine.productionAtTurnStart",
    "characters.changeCost",
    "characters.catalog",
    "cards.catalog",
    "mine.enabled"
  ]
};

// src/engine/map-demo.ts
var NAMES = [
  "Val-Brumeux",
  "Combe-aux-Loups",
  "Gu\xE9-Sombre",
  "Lande-Grise",
  "Haut-Ch\xEAne",
  "Pierre-Lev\xE9e",
  "Marais-d'Ys",
  "Clair-Bois",
  "Roc-Ardent",
  "Plaine-d'Or",
  "Col-du-Vent",
  "Bois-Hant\xE9",
  "Rive-P\xE2le",
  "Tertre-Rouge",
  "Vallon-Clos",
  "Cime-Bleue",
  "Pr\xE9s-Sal\xE9s",
  "For\xEAt-Noire",
  "Ravin-Sec",
  "Champs-Ocres",
  "Brande-Haute",
  "Lac-Miroir",
  "Sente-Perdue",
  "Foss\xE9-Vieux",
  "Coteau-Vert",
  "\xC9cueil-Gris"
];
function buildDemoMap() {
  const cells = [];
  for (let q2 = -3; q2 <= 3; q2++) {
    for (let r = Math.max(-3, -q2 - 3); r <= Math.min(3, -q2 + 3); r++) cells.push({ q: q2, r });
  }
  const removed = /* @__PURE__ */ new Set(["1,2", "-1,-2"]);
  const fiefs = {
    "3,-3": "skoldaris",
    "3,0": "taldars",
    "0,3": "velmoreens",
    "-3,3": "hesperides",
    "-3,0": "corbiens",
    "0,-3": "visiliens"
  };
  const fiefNames = {
    skoldaris: "Fief de Skjoldheim",
    corbiens: "Fief de Korvanya",
    hesperides: "Fief d'Hesp\xE9rion",
    taldars: "Fief de Tal-Qamar",
    velmoreens: "Fief de Velmora",
    visiliens: "Fief de Visilia"
  };
  const holy = { "1,-1": "force", "-1,1": "sagesse", "1,0": "fertilite", "-1,0": "force" };
  const mines = /* @__PURE__ */ new Set(["2,-2", "-2,0", "0,2"]);
  const terrains = ["plaine", "foret", "colline", "marais", "plaine", "foret"];
  let n = 0;
  let holyIdx = 0;
  const territories = [];
  for (const c of cells) {
    const key2 = `${c.q},${c.r}`;
    if (removed.has(key2)) continue;
    const base = { q: c.q, r: c.r };
    if (c.q === 0 && c.r === 0) {
      territories.push({ id: "capitale", name: "Aurelys, la Capitale", kind: "capitale", terrain: "plaine", ...base });
    } else if (fiefs[key2]) {
      territories.push({ id: `fief-${fiefs[key2]}`, name: fiefNames[fiefs[key2]], kind: "fief", fiefOf: fiefs[key2], terrain: "montagne", ...base });
    } else if (holy[key2]) {
      holyIdx++;
      const labels = { force: "Lieu saint", sagesse: "Lieu saint", fertilite: "Lieu saint" };
      territories.push({ id: `lieu-saint-${holyIdx}`, name: `${labels[holy[key2]]}${holy[key2] === "force" && holyIdx > 1 ? " II" : ""}`, kind: "lieu_saint", holyType: holy[key2], terrain: "colline", ...base });
    } else {
      const name = NAMES[n % NAMES.length];
      territories.push({ id: `t-${String(n + 1).padStart(2, "0")}`, name, kind: "normal", mine: mines.has(key2), terrain: mines.has(key2) ? "colline" : terrains[n * 7 % terrains.length], ...base });
      n++;
    }
  }
  return { name: "Carte de d\xE9monstration (non officielle)", demo: true, territories, links: neighborLinks(territories) };
}

// src/engine/map-official.ts
var OFFICIAL_MAP_NAME = "Carte officielle de Vileria";
var FIEFS = {
  "3,3": "skoldaris",
  "-6,3": "corbiens",
  "6,-3": "hesperides",
  "-3,-2": "taldars",
  "2,-4": "velmoreens",
  "-2,4": "visiliens"
};
var HOLY = { "-1,-1": "force", "2,-1": "sagesse", "-2,1": "fertilite", "1,1": "force" };
var VIRGIN_MINES = {
  "3,-2": "hesperides+velmoreens",
  "3,0": "hesperides+skoldaris",
  "1,2": "skoldaris+visiliens",
  "-3,2": "corbiens+visiliens",
  "-3,1": "corbiens+taldars",
  "-1,-3": "taldars+velmoreens"
};
var SMALL_MOUNTAINS = /* @__PURE__ */ new Set(["-3,-3", "1,-3", "4,-2", "-2,-1", "-4,1", "0,1", "2,2", "-2,3"]);
var FIEF_NAMES = {
  skoldaris: "Fief de Skjoldheim",
  corbiens: "Fief de Korvanya",
  hesperides: "Fief d'Hesp\xE9rion",
  taldars: "Fief de Tal-Qamar",
  velmoreens: "Fief de Velmora",
  visiliens: "Fief de Visilia"
};
var HOLY_NAMES = { force: "Lieu saint", sagesse: "Lieu saint", fertilite: "Lieu saint" };
function buildOfficialMap() {
  const territories = [];
  let holyIdx = 0;
  for (let row = 0; row < 9; row++) {
    const cols = row % 2 === 0 ? 9 : 10;
    for (let col = 0; col < cols; col++) {
      const r = row - 4;
      const q2 = col - (row + (row & 1)) / 2 - 2;
      const key2 = `${q2},${r}`;
      const label = `${String.fromCharCode(65 + row)}${col + 1}`;
      const base = { q: q2, r };
      if (q2 === 0 && r === 0) territories.push({ id: "capitale", name: "Capitale", kind: "capitale", terrain: "plaine", ...base });
      else if (FIEFS[key2]) territories.push({ id: `fief-${FIEFS[key2]}`, name: FIEF_NAMES[FIEFS[key2]], kind: "fief", fiefOf: FIEFS[key2], terrain: "montagne", ...base });
      else if (HOLY[key2]) {
        holyIdx++;
        territories.push({ id: `lieu-saint-${holyIdx}`, name: `${HOLY_NAMES[HOLY[key2]]} (${label})`, kind: "lieu_saint", holyType: HOLY[key2], terrain: "plaine", ...base });
      } else {
        territories.push({ id: `case-${label.toLowerCase()}`, name: VIRGIN_MINES[key2] ? `Mine ${label}` : SMALL_MOUNTAINS.has(key2) ? `Mont ${label}` : `Plaine ${label}`, kind: "normal", terrain: SMALL_MOUNTAINS.has(key2) ? "montagne" : "plaine", ...VIRGIN_MINES[key2] ? { mine: true } : {}, ...base });
      }
    }
  }
  return {
    name: OFFICIAL_MAP_NAME,
    demo: false,
    territories,
    links: neighborLinks(territories),
    background: { src: "/maps/vileria-officielle-3.0.png", width: 1448, height: 1086, originX: 690.4, originY: 543, hexSize: 72.1 },
    // 2026-11-16 : mines vierges ; le premier qui prend une mine choisit définitivement or (+2 or/tour) ou Moralith (+1/tour).
    specialRules: { mines: { upgrades: false, resource: "choix", production: { or: 2, moralith: 1 } } }
  };
}

// src/engine/schemas.ts
import { z as z2 } from "zod";
var id = z2.string().min(1).max(64);
var unit = z2.enum(UNIT_TYPES);
var building = z2.enum(BUILDING_TYPES);
var actionSchema = z2.discriminatedUnion("type", [
  z2.object({ type: z2.literal("harvest"), kind: z2.enum(["gold", "moralith"]) }).strict(),
  z2.object({ type: z2.literal("recruit"), territoryId: id, unit, count: z2.number().int().min(1).max(10), payMoralithWithGold: z2.boolean().optional() }).strict(),
  z2.object({ type: z2.literal("build"), territoryId: id, building, wallDir: z2.number().int().min(0).max(5).optional() }).strict(),
  z2.object({ type: z2.literal("upgradeMine"), territoryId: id }).strict(),
  z2.object({ type: z2.literal("move"), from: id, to: id, unitIds: z2.array(id).min(1).max(10), cardId: id.nullable().optional(), goldBoost: z2.number().int().min(0).max(100).optional(), via: id.optional(), pushPath: z2.array(id).min(1).max(4).optional() }).strict(),
  z2.object({ type: z2.literal("respondCombat"), cardId: id.nullable(), maeliaAttempt: z2.boolean().optional(), pushPath: z2.array(id).min(1).max(4).optional(), reverseCardDefId: id.optional() }).strict(),
  z2.object({ type: z2.literal("respondCard"), cardId: id.nullable() }).strict(),
  z2.object({ type: z2.literal("respondSupport"), cardId: id.nullable(), side: z2.enum(["attaquant", "defenseur"]).optional() }).strict(),
  z2.object({ type: z2.literal("respondPriest"), cardId: id.nullable() }).strict(),
  z2.object({
    type: z2.literal("resolveChoice"),
    choiceId: id,
    pass: z2.boolean().optional(),
    mineType: z2.enum(["or", "moralith"]).optional(),
    heroId: id.optional(),
    unitIds: z2.array(id).max(10).optional(),
    units: z2.array(z2.object({ type: unit, territoryId: id }).strict()).max(5).optional(),
    recruits: z2.array(z2.object({ type: unit, territoryId: id }).strict()).max(10).optional(),
    territoryId: id.optional()
  }).strict(),
  z2.object({ type: z2.literal("destroyBuilding"), territoryId: id, building }).strict(),
  z2.object({ type: z2.literal("convertKnights"), territoryId: id, unitIds: z2.array(id).length(2).optional() }).strict(),
  z2.object({ type: z2.literal("deployReserve"), territoryId: id, count: z2.number().int().min(1).max(5), unit: unit.optional() }).strict(),
  z2.object({ type: z2.literal("chooseRetreat"), territoryId: id }).strict(),
  z2.object({ type: z2.literal("buildWonder"), wonderId: z2.enum(WONDER_IDS) }).strict(),
  z2.object({ type: z2.literal("nextPhase") }).strict(),
  z2.object({ type: z2.literal("endTurn") }).strict(),
  z2.object({ type: z2.literal("selectCharacter"), characterId: id }).strict(),
  z2.object({ type: z2.literal("upgradeCharacter"), characterId: id }).strict(),
  z2.object({ type: z2.literal("useAbility"), characterId: id, targetPlayerId: id.optional(), targetCharacterId: id.optional(), territoryId: id.optional(), unitId: id.optional() }).strict(),
  z2.object({ type: z2.literal("chooseDrawnCard"), cardId: id }).strict(),
  z2.object({ type: z2.literal("buyBonusCard") }).strict(),
  z2.object({
    type: z2.literal("playCard"),
    cardId: id,
    targetPlayerIds: z2.array(id).min(1).max(5).optional(),
    territoryId: id.optional(),
    units: z2.array(z2.object({ type: unit, territoryId: id }).strict()).max(5).optional(),
    wonderId: z2.enum(WONDER_IDS).optional(),
    combatRole: z2.enum(["attaque", "defense"]).optional()
  }).strict(),
  z2.object({ type: z2.literal("sagesseExchange"), give: z2.enum(["gold", "moralith"]) }).strict(),
  z2.object({ type: z2.literal("factionExchange") }).strict(),
  z2.object({ type: z2.literal("labChooseCard"), cardDefId: id }).strict(),
  z2.object({ type: z2.literal("sacrifice"), territoryId: id, unitId: id.optional(), building: building.optional() }).strict()
]);
var mapSchema = z2.object({
  name: z2.string().min(1).max(120),
  key: z2.string().regex(/^[a-z0-9-]{1,40}$/).optional(),
  description: z2.string().max(300).optional(),
  features: z2.array(z2.string().max(120)).max(6).optional(),
  demo: z2.boolean(),
  territories: z2.array(z2.object({
    id: z2.string().regex(/^[a-z0-9-]{1,40}$/),
    name: z2.string().min(1).max(60),
    q: z2.number().int().min(-30).max(30),
    r: z2.number().int().min(-30).max(30),
    kind: z2.enum(["normal", "fief", "capitale", "lieu_saint"]),
    fiefOf: z2.enum(FACTION_IDS).optional(),
    holyType: z2.enum(["force", "sagesse", "fertilite"]).optional(),
    mine: z2.boolean().optional(),
    terrain: z2.enum(["plaine", "foret", "colline", "montagne", "marais", "eau"]).optional()
  }).strict()).min(2).max(200),
  links: z2.array(z2.tuple([z2.string(), z2.string()])).max(1200),
  background: z2.object({
    src: z2.string().regex(/^\/maps\/[A-Za-z0-9._-]+\.(png|jpe?g|webp)$/, "Image servie depuis /maps/ uniquement"),
    width: z2.number().positive().max(1e4),
    height: z2.number().positive().max(1e4),
    originX: z2.number(),
    originY: z2.number(),
    hexSize: z2.number().positive().max(500)
  }).strict().optional(),
  players: z2.object({ min: z2.number().int().min(2).max(6), max: z2.number().int().min(2).max(6) }).strict().optional(),
  // 2026-11-15 : participants prévus pour la carte
  specialRules: z2.object({ mines: z2.object({ upgrades: z2.boolean(), resource: z2.enum(["or", "moralith", "choix"]).optional(), production: z2.object({ or: z2.number().int().min(0).max(10), moralith: z2.number().int().min(0).max(10) }).strict().optional() }).strict().optional(), effectsWithoutHolySite: z2.boolean().optional(), fiefsToWin: z2.number().int().min(1).max(12).optional() }).strict().optional(),
  fiefSlots: z2.object({ players: z2.array(z2.string().regex(/^-?\d+,-?\d+$/)).max(6), neutral: z2.array(z2.string().regex(/^-?\d+,-?\d+$/)).max(6) }).strict().optional()
}).strict();
var cost = z2.object({ gold: z2.number().int().min(0).max(999), moralith: z2.number().int().min(0).max(99) }).strict();
var ruleSetSchema = z2.object({
  label: z2.string().min(1).max(120),
  players: z2.object({ min: z2.number().int().min(2).max(6), max: z2.number().int().min(2).max(6) }).strict(),
  start: z2.object({ gold: z2.number().int().min(0), moralith: z2.number().int().min(0), units: z2.array(z2.object({ unit, count: z2.number().int().min(0).max(5) }).strict()) }).strict(),
  economy: z2.object({ harvestGold: z2.number().int().min(0), harvestMoralithHolySite: z2.number().int().min(0), harvestMoralithCapital: z2.number().int().min(0), bothHarvestsSameTurn: z2.boolean() }).strict(),
  units: z2.record(unit, z2.object({ name: z2.string(), attack: z2.number().int().min(0).nullable(), cost: cost.nullable(), retired: z2.boolean().optional(), uniquePerPlayer: z2.boolean().optional(), requiresCapital: z2.boolean().optional(), lostWithCapital: z2.boolean().optional(), reRecruitAfterLoss: z2.boolean().optional() }).strict()),
  army: z2.object({ maxUnits: z2.number().int().min(1).max(20), lossPriority: z2.array(unit), eliteLimitPerPlayer: z2.number().int().min(0).max(20).optional() }).strict(),
  movement: z2.object({ stepsPerTurn: z2.number().int().min(1), attacksPerTurn: z2.number().int().min(0), undefendedCaptureCountsAsAttack: z2.boolean(), attackLimit: z2.enum(["joueur", "armee"]).optional(), wallsBlock: z2.boolean().optional() }).strict(),
  combat: z2.object({
    tieAttackerLosses: z2.number().int().min(0),
    lossTable: z2.array(z2.object({ minDiff: z2.number().int().min(0), losses: z2.number().int().min(0) }).strict()).min(1),
    defenderLoser: z2.enum(["retreat_or_destroy", "destroy"]),
    colisseumAppliesTo: z2.enum(["attaque", "attaque_et_defense"]),
    fiefFixedDefense: z2.number().int().min(0).optional(),
    neutralFiefDefense: z2.boolean().optional()
  }).strict(),
  limits: z2.object({ buildsPerTurn: z2.number().int().min(0), noBuildOn: z2.array(z2.enum(["fief", "lieu_saint", "capitale"])).optional() }).strict(),
  recruitment: z2.object({ allowedIn: z2.literal("fief_ou_caserne") }).strict(),
  buildings: z2.record(building, z2.object({ name: z2.string(), cost, limitPerPlayer: z2.number().int().min(0), defense: z2.number().int().min(0) }).strict()),
  mine: z2.object({ levels: z2.array(z2.object({ production: z2.number().int().min(0), upgradeCost: z2.number().int().min(0) }).strict()).min(1), productionAtTurnStart: z2.boolean(), enabled: z2.boolean().optional() }).strict(),
  holySites: z2.object({ forceAttackBonus: z2.number().int(), sagesseGoldPerMoralith: z2.number().int().min(1), sagesseMoralithToGold: z2.number().int().min(0), fertiliteGoldReduction: z2.number().int().min(0), bonuses: z2.boolean().optional() }).strict(),
  wonders: z2.object({
    catalog: z2.array(z2.object({ id: z2.enum(WONDER_IDS), name: z2.string(), description: z2.string(), cost, sixPlayersOnly: z2.boolean().optional(), requiresCapital: z2.boolean().optional() }).strict()),
    requireHolySiteForEffects: z2.boolean(),
    uniquePerGame: z2.boolean(),
    bastionBonus: z2.number().int(),
    colisseumBonus: z2.number().int(),
    obeliskEliteAttack: z2.number().int(),
    tresorMineProduction: z2.number().int()
  }).strict(),
  characters: z2.object({ upgradeCost: cost, changeCost: cost, catalog: z2.array(z2.object({ id, name: z2.string(), faction: z2.enum(FACTION_IDS), category: z2.enum(["militaire", "economique", "heros"]), description: z2.string(), levels: z2.tuple([z2.array(z2.any()), z2.array(z2.any())]), implemented: z2.boolean(), title: z2.string().optional(), levelTexts: z2.tuple([z2.string(), z2.string()]).optional(), levelStatus: z2.tuple([z2.enum(["actif", "en_attente"]), z2.enum(["actif", "en_attente"])]).optional(), upgradeCost: cost.optional(), portrait: z2.string().optional(), power: z2.string().optional() }).strict()), heroes: z2.boolean().optional(), pick: z2.number().int().min(1).max(4).optional() }).strict(),
  // 4.0 : power (pouvoir unique), pick (héros choisis)
  cards: z2.object({ eventCardCost: cost.optional(), bonusCardCost: cost.optional(), separateDecks: z2.boolean().optional(), usedReturnToDeck: z2.boolean().optional(), catalogProvisional: z2.boolean(), catalog: z2.array(z2.object({ id, name: z2.string(), kind: z2.enum(["combat", "defense", "retraite", "annulation", "evenement", "economie", "justice"]), description: z2.string(), copies: z2.number().int().min(0).max(50), effect: z2.object({ type: z2.string() }).passthrough(), usableBy: z2.enum(["attaquant", "defenseur", "les_deux", "hors_combat"]), image: z2.string().optional(), status: z2.enum(["actif", "en_attente"]).optional() }).strict()) }).strict(),
  fief: z2.object({ eliminationDelayRounds: z2.number().int().min(0) }).strict(),
  elimination: z2.object({ destroyBuildings: z2.array(z2.enum(["caserne", "fort", "fortification"])), destroyWonders: z2.boolean(), resourcesLost: z2.boolean(), lastStandingWins: z2.boolean() }).strict().optional(),
  victory: z2.object({ holySiteTurns: z2.number().int().min(1), fiefsToControl: z2.number().int().min(1), wondersToBuild: z2.number().int().min(1), eliminationWins: z2.boolean(), holdKind: z2.enum(["lieu_saint", "capitale"]).optional() }).strict(),
  factions: z2.record(z2.enum(FACTION_IDS), z2.object({ id: z2.enum(FACTION_IDS), name: z2.string(), color: z2.string(), colorDark: z2.string(), motto: z2.string(), boardNote: z2.string().max(500).optional(), modifiers: z2.array(z2.object({ type: z2.string() }).passthrough()) }).strict()),
  provisional: z2.array(z2.string())
}).strict();

// src/engine/map-six.ts
var SIX_MARCHES_MAP_NAME = "Les Six Marches";
var SIX_CONTINENTS_MAP_NAME = "Les Six Continents";
var rotate60 = (q2, r) => [-r, q2 + r];
var rot = (q2, r, k) => {
  let p = [q2, r];
  for (let i = 0; i < k; i++) p = rotate60(...p);
  return p;
};
var hexDist = (a, b) => Math.max(Math.abs(a.q - b.q), Math.abs(a.r - b.r), Math.abs(a.q + a.r - b.q - b.r));
var key = (q2, r) => `${q2},${r}`;
var SIX_SECTOR_FACTIONS = ["velmoreens", "hesperides", "skoldaris", "visiliens", "corbiens", "taldars"];
var SECTOR_TERRAIN = ["colline", "plaine", "foret", "plaine", "marais", "colline"];
var FIEF_NAMES2 = {
  skoldaris: "Fief de Skjoldheim",
  corbiens: "Fief de Korvanya",
  hesperides: "Fief d'Hesp\xE9rion",
  taldars: "Fief de Tal-Qamar",
  velmoreens: "Fief de Velmora",
  visiliens: "Fief de Visilia"
};
var REGION_NAMES = {
  skoldaris: "Skjoldheim",
  corbiens: "Korvanya",
  hesperides: "Hesp\xE9rion",
  taldars: "Tal-Qamar",
  velmoreens: "Velmora",
  visiliens: "Visilia"
};
var TERRAIN_NAMES = { plaine: "Plaine", foret: "For\xEAt", colline: "Colline", marais: "Marais", montagne: "Mont", eau: "Mer" };
var HOLY2 = [[1, 1], [-1, 2], [-1, -1], [1, -2]];
var HOLY_TYPES = ["force", "sagesse", "fertilite", "force"];
var MINES_RULES = { mines: { upgrades: false, resource: "choix", production: { or: 2, moralith: 1 } } };
function sectorOf(q2, r) {
  const n = hexDist({ q: q2, r }, { q: 0, r: 0 });
  if (n === 0) return null;
  const d = [0, 1, 2, 3, 4, 5].map((k) => {
    const [cq, cr] = rot(n, 0, k);
    return hexDist({ q: q2, r }, { q: cq, r: cr });
  });
  const m = Math.min(...d);
  return d.filter((x) => x === m).length > 1 ? null : d.indexOf(m);
}
function territoriesOf(cells, fief, mine, centerRadius, kind, water = /* @__PURE__ */ new Set()) {
  const fiefAt = /* @__PURE__ */ new Map(), mineAt = /* @__PURE__ */ new Set();
  for (let k = 0; k < 6; k++) {
    fiefAt.set(key(...rot(fief.q, fief.r, k)), SIX_SECTOR_FACTIONS[k]);
    mineAt.add(key(...rot(mine.q, mine.r, k)));
  }
  const holyAt = new Map(HOLY2.map(([q2, r], i) => [key(q2, r), i]));
  const sorted = [...cells].sort((a, b) => a.r - b.r || a.q - b.q);
  const minR = sorted[0].r;
  const rows = /* @__PURE__ */ new Map();
  return sorted.map(({ q: q2, r }) => {
    const col = (rows.get(r) ?? 0) + 1;
    rows.set(r, col);
    const label = `${String.fromCharCode(65 + r - minR)}${col}`;
    const id2 = `case-${label.toLowerCase()}`;
    if (q2 === 0 && r === 0) return { id: "capitale", name: "Capitale", kind: "capitale", terrain: "plaine", q: q2, r };
    const hi = holyAt.get(key(q2, r));
    if (hi !== void 0) return { id: `lieu-saint-${hi + 1}`, name: `Lieu saint (${label})`, kind: "lieu_saint", holyType: HOLY_TYPES[hi], terrain: "plaine", q: q2, r };
    const f = fiefAt.get(key(q2, r));
    if (f) return { id: `fief-${f}`, name: FIEF_NAMES2[f], kind: "fief", fiefOf: f, terrain: "montagne", q: q2, r };
    if (water.has(key(q2, r))) return { id: id2, name: `Mer ${label}`, kind: "normal", terrain: "eau", q: q2, r };
    const sec = sectorOf(q2, r);
    const inCenter = hexDist({ q: q2, r }, { q: 0, r: 0 }) <= centerRadius;
    const terrain = inCenter || sec === null ? "plaine" : SECTOR_TERRAIN[sec];
    const region = sec !== null && !inCenter ? ` \u2014 ${kind === "marches" ? "Marche" : "Terres"} de ${REGION_NAMES[SIX_SECTOR_FACTIONS[sec]]}` : "";
    if (mineAt.has(key(q2, r))) return { id: id2, name: `Mine ${label}${region}`, kind: "normal", mine: true, terrain, q: q2, r };
    return { id: id2, name: `${TERRAIN_NAMES[terrain]} ${label}${region}`, kind: "normal", terrain, q: q2, r };
  });
}
var SIX_MARCHES_FIEF = { q: 4, r: 0 };
var SIX_MARCHES_MINE = { q: 2, r: 2 };
function buildSixMarchesMap() {
  const cells = [];
  for (let q2 = -5; q2 <= 5; q2++) for (let r = -5; r <= 5; r++) {
    const s = -q2 - r;
    if (Math.max(Math.abs(q2), Math.abs(r), Math.abs(s)) > 5) continue;
    if ([q2, r, s].filter((x) => Math.abs(x) === 5).length === 2) continue;
    cells.push({ q: q2, r });
  }
  const territories = territoriesOf(cells, SIX_MARCHES_FIEF, SIX_MARCHES_MINE, 1, "marches");
  return {
    name: SIX_MARCHES_MAP_NAME,
    key: "six-marches",
    description: "Six marches frontali\xE8res autour d'un c\u0153ur commun : la Capitale et quatre lieux saints. Terrain d'un seul tenant, sans goulot.",
    features: ["Six fiefs \xE0 4 pas de la Capitale", "Six mines vierges disput\xE9es entre marches voisines", "Nombreuses routes vers le centre"],
    demo: false,
    territories,
    links: neighborLinks(territories),
    players: { min: 3, max: 6 },
    specialRules: MINES_RULES
  };
}
var SIX_CONTINENTS_SECTOR = [
  { q: 4, r: 0 },
  { q: 4, r: -1 },
  { q: 3, r: 1 },
  { q: 5, r: 0 },
  { q: 5, r: -1 },
  { q: 4, r: 1 },
  { q: 6, r: 0 },
  { q: 6, r: -1 },
  { q: 6, r: -2 },
  { q: 5, r: 1 },
  { q: 4, r: 2 }
];
var SIX_CONTINENTS_FIEF = { q: 5, r: 0 };
var SIX_CONTINENTS_MINE = { q: 4, r: 2 };
function buildSixContinentsMap() {
  const land = /* @__PURE__ */ new Set();
  for (let q2 = -2; q2 <= 2; q2++) for (let r = -2; r <= 2; r++) if (hexDist({ q: q2, r }, { q: 0, r: 0 }) <= 2) land.add(key(q2, r));
  for (let k = 0; k < 6; k++) for (const c of SIX_CONTINENTS_SECTOR) land.add(key(...rot(c.q, c.r, k)));
  const cells = [], water = /* @__PURE__ */ new Set();
  for (let q2 = -6; q2 <= 6; q2++) for (let r = -6; r <= 6; r++) {
    if (hexDist({ q: q2, r }, { q: 0, r: 0 }) > 6) continue;
    cells.push({ q: q2, r });
    if (!land.has(key(q2, r))) water.add(key(q2, r));
  }
  const territories = territoriesOf(cells, SIX_CONTINENTS_FIEF, SIX_CONTINENTS_MINE, 2, "continents", water);
  return {
    name: SIX_CONTINENTS_MAP_NAME,
    key: "six-continents",
    description: "Six continents autour d'une \xEEle centrale (Capitale et lieux saints), s\xE9par\xE9s par des mers et des d\xE9troits que l'on traverse comme la terre.",
    features: ["Cases d'eau : cases ordinaires (d\xE9placement, combat, conqu\xEAte)", "Anneau maritime autour de l'\xEEle centrale", "Mines vierges sur les c\xF4tes des d\xE9troits"],
    demo: false,
    territories,
    links: neighborLinks(territories),
    players: { min: 3, max: 6 },
    specialRules: MINES_RULES
  };
}

// src/engine/map-triade.ts
var TRIADE_MAP_NAME = "La Triade";
var TRIADE_RADIUS = 4;
var TRIADE_PLAYER_SLOTS = [[4, -2], [-2, -2], [-2, 4]];
var TRIADE_MINE_SLOTS = [[2, -4], [-4, 2], [2, 2]];
var TERRAIN_ORBITS = [
  [2, 0, "foret"],
  [3, -3, "foret"],
  // forêts : sur la route de la Capitale et à la lisière du fief neutre
  [1, -2, "colline"],
  // collines
  [3, 0, "marais"]
  // marais
];
var FIEF_NAMES3 = {
  skoldaris: "Fief de Skjoldheim",
  corbiens: "Fief de Korvanya",
  hesperides: "Fief d'Hesp\xE9rion",
  taldars: "Fief de Tal-Qamar",
  velmoreens: "Fief de Velmora",
  visiliens: "Fief de Visilia"
};
var TERRAIN_NAMES2 = { plaine: "Plaine", foret: "For\xEAt", colline: "Colline", marais: "Marais", montagne: "Mont", eau: "Mer" };
var rotateTriade = (q2, r) => [-q2 - r, q2];
var orbit = (q2, r) => {
  const a = rotateTriade(q2, r), b = rotateTriade(...a);
  return [[q2, r], a, b].map(([x, y]) => `${x},${y}`);
};
function triadeCells() {
  const out = [];
  for (let r = -TRIADE_RADIUS; r <= TRIADE_RADIUS; r++) for (let q2 = -TRIADE_RADIUS; q2 <= TRIADE_RADIUS; q2++) {
    const s = -q2 - r;
    if (Math.max(Math.abs(q2), Math.abs(r), Math.abs(s)) > TRIADE_RADIUS) continue;
    if ([q2, r, s].filter((x) => Math.abs(x) === TRIADE_RADIUS).length === 2) continue;
    out.push({ q: q2, r });
  }
  return out;
}
function buildTriadeMap(fiefFactions = [...FACTION_IDS]) {
  const fiefAt = new Map(TRIADE_PLAYER_SLOTS.map(([q2, r], i) => [`${q2},${r}`, fiefFactions[i]]));
  const mines = new Set(TRIADE_MINE_SLOTS.map(([q2, r]) => `${q2},${r}`));
  const terrainAt = /* @__PURE__ */ new Map();
  for (const [q2, r, t] of TERRAIN_ORBITS) for (const k of orbit(q2, r)) terrainAt.set(k, t);
  const rows = /* @__PURE__ */ new Map();
  const territories = triadeCells().map(({ q: q2, r }) => {
    const col = (rows.get(r) ?? 0) + 1;
    rows.set(r, col);
    const label = `${String.fromCharCode(65 + r + TRIADE_RADIUS)}${col}`;
    if (q2 === 0 && r === 0) return { id: "capitale", name: "Capitale", kind: "capitale", terrain: "plaine", q: q2, r };
    const f = fiefAt.get(`${q2},${r}`);
    if (f) return { id: `fief-${f}`, name: FIEF_NAMES3[f], kind: "fief", fiefOf: f, terrain: "plaine", q: q2, r };
    if (mines.has(`${q2},${r}`)) return { id: `case-${label.toLowerCase()}`, name: `Mine de Moralith ${label}`, kind: "normal", mine: true, terrain: "colline", q: q2, r };
    const terrain = terrainAt.get(`${q2},${r}`) ?? "plaine";
    return { id: `case-${label.toLowerCase()}`, name: `${TERRAIN_NAMES2[terrain]} ${label}`, kind: "normal", terrain, q: q2, r };
  });
  return {
    name: TRIADE_MAP_NAME,
    demo: false,
    territories,
    links: neighborLinks(territories),
    players: { min: 3, max: 3 },
    fiefSlots: { players: TRIADE_PLAYER_SLOTS.map(([q2, r]) => `${q2},${r}`), neutral: [] },
    specialRules: { mines: { upgrades: false, resource: "moralith" }, effectsWithoutHolySite: true, fiefsToWin: 3 }
    // 3 fiefs : décision EMAP du 2026-11-16
  };
}

// src/server/migrate.ts
async function migrate(p) {
  const applied = [];
  await p.query("CREATE TABLE IF NOT EXISTS schema_migrations (name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())");
  const dir = path2.join(process.cwd(), "migrations");
  for (const f of readdirSync(dir).filter((x) => x.endsWith(".sql")).sort()) {
    const done = await p.query("SELECT 1 FROM schema_migrations WHERE name = $1", [f]);
    if (done.rowCount) continue;
    const c = await p.connect();
    try {
      await c.query("BEGIN");
      await c.query(readFileSync2(path2.join(dir, f), "utf8"));
      await c.query("INSERT INTO schema_migrations(name) VALUES ($1)", [f]);
      await c.query("COMMIT");
      applied.push(f);
    } catch (e) {
      await c.query("ROLLBACK");
      throw e;
    } finally {
      c.release();
    }
  }
  const mp = await p.query("SELECT 1 FROM maps LIMIT 1");
  if (!mp.rowCount) {
    const m = buildDemoMap();
    await p.query("INSERT INTO maps(version, name, status, data, is_default) VALUES (1, $1, 'demonstration', $2, false)", [m.name, JSON.stringify(m)]);
  }
  const off = await p.query("SELECT 1 FROM maps WHERE name = $1", [OFFICIAL_MAP_NAME]);
  if (!off.rowCount) {
    const m = buildOfficialMap();
    await p.query("UPDATE maps SET is_default = false WHERE is_default");
    await p.query("INSERT INTO maps(version, name, status, data, is_default) VALUES ((SELECT coalesce(max(version),0)+1 FROM maps), $1, 'officielle', $2, true)", [m.name, JSON.stringify(m)]);
    applied.push(`carte : ${m.name}`);
  }
  const def = await p.query("SELECT data FROM maps WHERE is_default LIMIT 1");
  const dm = def.rows[0]?.data;
  if (dm && dm.territories.some((t) => t.kind === "lieu_saint" && /^Sanctuaire de /.test(t.name))) {
    for (const t of dm.territories) if (t.kind === "lieu_saint") t.name = t.name.replace(/^Sanctuaire de (Force|Sagesse|Fertilité)/, "Lieu saint");
    await p.query("UPDATE maps SET is_default = false WHERE is_default");
    await p.query("INSERT INTO maps(version, name, status, data, is_default) VALUES ((SELECT coalesce(max(version),0)+1 FROM maps), $1, 'officielle', $2, true)", [dm.name, JSON.stringify(dm)]);
    applied.push(`carte : ${dm.name} (lieux saints au nom neutre, 2.7)`);
  }
  const tri = await p.query("SELECT data FROM maps WHERE name = $1 ORDER BY version DESC LIMIT 1", [TRIADE_MAP_NAME]);
  if (!tri.rowCount || canonical(tri.rows[0].data) !== canonical(buildTriadeMap())) {
    const m = buildTriadeMap();
    await p.query("INSERT INTO maps(version, name, status, data, is_default) VALUES ((SELECT coalesce(max(version),0)+1 FROM maps), $1, 'officielle', $2, false)", [m.name, JSON.stringify(m)]);
    applied.push(`carte : ${m.name}`);
  }
  for (const build of [buildSixMarchesMap, buildSixContinentsMap]) {
    const m = build();
    const last = await p.query("SELECT data FROM maps WHERE name = $1 ORDER BY version DESC LIMIT 1", [m.name]);
    if (!last.rowCount || canonical(last.rows[0].data) !== canonical(m)) {
      await p.query("INSERT INTO maps(version, name, status, data, is_default) VALUES ((SELECT coalesce(max(version),0)+1 FROM maps), $1, 'officielle', $2, false)", [m.name, JSON.stringify(m)]);
      applied.push(`carte : ${m.name}`);
    }
  }
  const cur = await p.query("SELECT data FROM maps WHERE is_default LIMIT 1");
  const dmap = cur.rows[0]?.data;
  if (dmap && dmap.name === OFFICIAL_MAP_NAME && !dmap.specialRules?.mines) {
    const ref = buildOfficialMap();
    const mines = new Set(ref.territories.filter((t) => t.mine).map((t) => `${t.q},${t.r}`));
    const next = { ...dmap, territories: dmap.territories.map((t) => mines.has(`${t.q},${t.r}`) && t.kind === "normal" ? { ...t, mine: true, name: ref.territories.find((x) => x.q === t.q && x.r === t.r).name } : t), specialRules: ref.specialRules };
    await p.query("UPDATE maps SET is_default = false WHERE is_default");
    await p.query("INSERT INTO maps(version, name, status, data, is_default) VALUES ((SELECT coalesce(max(version),0)+1 FROM maps), $1, 'officielle', $2, true)", [next.name, JSON.stringify(next)]);
    applied.push(`carte : ${next.name} (mines vierges, 2026-11-16)`);
  }
  const rs = await p.query("SELECT 1 FROM rulesets WHERE label = $1", [DEFAULT_RULES.label]);
  if (!rs.rowCount) {
    await p.query("UPDATE rulesets SET is_default = false WHERE is_default");
    await p.query(
      "INSERT INTO rulesets(version, label, status, data, notes, is_default) VALUES ((SELECT coalesce(max(version),0)+1 FROM rulesets), $1, 'provisoire', $2, $3, true)",
      [DEFAULT_RULES.label, JSON.stringify(DEFAULT_RULES), "R\xE8gles 2.7 du 2026-11-08 : une attaque par arm\xE9e et par tour, fortifications-murs, d\xE9fense fixe 2 des fiefs de d\xE9part, lieux saints sans bonus. Plus les valeurs provisoires du registre."]
    );
    applied.push(`r\xE8gles : ${DEFAULT_RULES.label}`);
  }
  return applied;
}
function canonical(v) {
  if (Array.isArray(v)) return `[${v.map(canonical).join(",")}]`;
  if (v && typeof v === "object") return `{${Object.keys(v).filter((k) => v[k] !== void 0).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`;
  return JSON.stringify(v);
}

// scripts/create-admin.ts
var [username, given] = process.argv.slice(2);
if (!username) {
  console.error("Usage : npm run admin:create -- <identifiant> [motDePasse]");
  process.exit(1);
}
usernameSchema.parse(username);
await migrate(pool());
var existing = await q("SELECT id FROM users WHERE username_lower = lower($1)", [username]);
if (existing[0]) {
  await q("UPDATE users SET role = 'admin' WHERE id = $1", [existing[0].id]);
  await audit(existing[0].id, "admin_promoted_cli");
  console.log(`Compte ${username} promu administrateur.`);
} else {
  const pw = given ?? randomBytes2(12).toString("base64url");
  if (pw.length < 10) {
    console.error("Mot de passe : 10 caract\xE8res minimum.");
    process.exit(1);
  }
  const [u] = await q("INSERT INTO users(username, display_name, password_hash, role) VALUES ($1,$1,$2,'admin') RETURNING id", [username, await hashPassword(pw)]);
  await audit(u.id, "admin_created_cli");
  console.log(`Administrateur ${username} cr\xE9\xE9.${given ? "" : ` Mot de passe g\xE9n\xE9r\xE9 : ${pw} (\xE0 changer apr\xE8s connexion)`}`);
}
await pool().end();
