File size: 31,000 Bytes
2a8d2d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20cc92a
2a8d2d3
 
20cc92a
 
 
 
 
 
 
 
2a8d2d3
 
 
 
 
 
20cc92a
2a8d2d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
#!/usr/bin/env node
// Unified validation command: one parse pass, all findings.
//
// Merges the four former tools into a single `node tools/validate.mjs` run:
//   1. tools/eu4_clausewitz/bin/validate.mjs (refs, encoding, loc, unowned-land, ambiguities)
//   2. tools/bin/audit.mjs (duplicate definitions in common/ and events/)
//   3. tools/build_variants.mjs check (English overlay + manifest consistency)
//   4. tools/localisation.ps1 check (localisation source vs built output)
//
// New: province/area/region/trade-node scope refs in events/decisions/missions.
//
// Output: findings grouped by category, file:line:col format, summary count
// per level (error/warn/info). Exit non-zero only on errors.

import { createHash } from 'node:crypto';
import { readdir, readFile, stat } from 'node:fs/promises';
import { dirname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
import process from 'node:process';

import { load } from './eu4_clausewitz/src/index.mjs';
import { readGameText } from './eu4_clausewitz/src/codec.mjs';
import { tokenize } from './eu4_clausewitz/src/lexer.mjs';
import { parse } from './eu4_clausewitz/src/ast.mjs';
import { isDateKey } from './eu4_clausewitz/src/node.mjs';
import { buildDefinedSets, buildRefGraph } from './eu4_clausewitz/src/refs.mjs';
import { runRules, summarize } from './eu4_clausewitz/src/validate.mjs';
import { loadDir } from './eu4_clausewitz/src/overlay.mjs';

import provincesRegistry from './eu4_clausewitz/registry/provinces.mjs';
import countriesRegistry from './eu4_clausewitz/registry/countries.mjs';
import provinceRules, { provinceRefRules } from './eu4_clausewitz/registry/provinces.rules.mjs';
import countryRules, { countryRefRules } from './eu4_clausewitz/registry/countries.rules.mjs';
import encodingRules from './eu4_clausewitz/registry/encoding.rules.mjs';

import { loadManifest, validateManifestAgainstRoot } from './history_language_manifest.mjs';

import { hasUtf8Bom, encodeBuffer } from './eu4_han_convert/src/codec.js';

// --- paths ------------------------------------------------------------------

const root = join(dirname(fileURLToPath(import.meta.url)), '..');
const MOD_ROOT = root;
const VANILLA_ROOT = 'C:/Program Files (x86)/Steam/steamapps/common/Europa Universalis IV';
const GAME_LOCALISATION = join(VANILLA_ROOT, 'localisation');
const REGISTRIES = [provincesRegistry, countriesRegistry];
const MANIFEST_PATH = join(root, 'history_language_manifest.json');
const LOC_MANIFEST_PATH = join(root, 'localisation_manifest.json');
const CODEC_PATH = join(root, 'tools', 'eu4_han_convert', 'src', 'codec.js');
const LOC_SOURCE_ROOT = join(root, 'localisation_source');
const LOC_ENCODED_ROOT = join(root, 'localisation');
const ENGLISH_SOURCE = join(root, 'localisation_english_source');
const ENGLISH_PROVENANCE = join(root, 'localisation_english_provenance.json');
const CHINESE_SOURCE = join(root, 'localisation_source');

// --- helpers ----------------------------------------------------------------

async function walkTxtFiles(dir, out = []) {
  let entries;
  try {
    entries = await readdir(dir, { withFileTypes: true });
  } catch {
    return out;
  }
  for (const entry of entries) {
    const path = join(dir, entry.name);
    if (entry.isDirectory()) await walkTxtFiles(path, out);
    else if (entry.isFile() && entry.name.toLowerCase().endsWith('.txt')) out.push(path);
  }
  return out;
}

async function walkYmlFiles(dir, out = []) {
  let entries;
  try {
    entries = await readdir(dir, { withFileTypes: true });
  } catch {
    return out;
  }
  for (const entry of entries) {
    const path = join(dir, entry.name);
    if (entry.isDirectory()) await walkYmlFiles(path, out);
    else if (entry.isFile() && entry.name.toLowerCase().endsWith('.yml')) out.push(path);
  }
  return out;
}

function rel(path) {
  return relative(MOD_ROOT, path).replace(/\\/g, '/');
}

async function parseFile(path) {
  const { text } = await readGameText(path);
  return { text, tree: parse(tokenize(text)) };
}

async function exists(path) {
  try {
    await stat(path);
    return true;
  } catch (error) {
    if (error.code === 'ENOENT') return false;
    throw error;
  }
}

// ===========================================================================
// Phase 1: Build defined sets + map-level valid ID sets
// ===========================================================================

async function buildMapSets() {
  // Province IDs from definition.csv: "province;red;green;blue;x;x" per line
  const defPath = join(MOD_ROOT, 'map', 'definition.csv');
  const provinces = new Set();
  try {
    const content = await readFile(defPath, 'utf8');
    for (const line of content.split(/\r?\n/)) {
      const trimmed = line.trim();
      if (!trimmed || trimmed.startsWith('#')) continue;
      const id = trimmed.split(';')[0];
      if (/^\d+$/.test(id)) provinces.add(Number(id));
    }
  } catch { /* definition.csv missing - leave empty */ }

  // Areas from area.txt: top-level "<name>_area = { ... }" blocks
  const areas = new Set();
  try {
    const { tree } = await parseFile(join(MOD_ROOT, 'map', 'area.txt'));
    for (const item of tree.items) {
      if (item.kind === 'pair' && item.value.type === 'block') {
        areas.add(item.keyToken.value);
      }
    }
  } catch { /* missing - leave empty */ }

  // Regions from region.txt: top-level "<name>_region = { ... }" blocks
  const regions = new Set();
  try {
    const { tree } = await parseFile(join(MOD_ROOT, 'map', 'region.txt'));
    for (const item of tree.items) {
      if (item.kind === 'pair' && item.value.type === 'block') {
        regions.add(item.keyToken.value);
      }
    }
  } catch { /* missing - leave empty */ }

  // Trade nodes from common/tradenodes/: top-level "<name> = { ... }" blocks
  const tradeNodes = new Set();
  const tradeNodeFiles = await walkTxtFiles(join(MOD_ROOT, 'common', 'tradenodes'));
  for (const path of tradeNodeFiles) {
    const { tree } = await parseFile(path);
    for (const item of tree.items) {
      if (item.kind === 'pair' && item.value.type === 'block') {
        tradeNodes.add(item.keyToken.value);
      }
    }
  }

  return { provinces, areas, regions, tradeNodes };
}

// ===========================================================================
// Phase 2: Ref integrity (from old validate.mjs runRefs)
// ===========================================================================

async function runRefs(eu4, ctx) {
  const graph = await buildRefGraph(eu4, { gameRoot: VANILLA_ROOT, modRoot: MOD_ROOT }, REGISTRIES, ctx.definedSets);
  const rules = [...provinceRefRules, ...countryRefRules];
  return runRules(rules, graph.forward, ctx);
}

// ===========================================================================
// Phase 3: Province/country warnings (from old validate.mjs)
// ===========================================================================

async function collectRecords(eu4, registry) {
  const { entries } = await loadDir({ gameRoot: VANILLA_ROOT, modRoot: MOD_ROOT, relPath: registry.path });
  const collection = await eu4.dir(registry.path);
  const records = [];
  for (const id of entries.keys()) {
    records.push({ id, node: await collection.get(id) });
  }
  return records;
}

async function runProvinceCountryWarnings(eu4, ctx) {
  const provinceRecords = await collectRecords(eu4, provincesRegistry);
  const countryRecords = await collectRecords(eu4, countriesRegistry);
  return [
    ...runRules(provinceRules, provinceRecords, ctx),
    ...runRules(countryRules, countryRecords, ctx),
  ];
}

// ===========================================================================
// Phase 4: Encoding (from old validate.mjs runEncoding)
// ===========================================================================

async function runEncoding() {
  const dirs = [
    join(VANILLA_ROOT, 'history'),
    join(VANILLA_ROOT, 'common'),
    join(MOD_ROOT, 'history'),
    join(MOD_ROOT, 'common'),
  ];
  const files = [];
  for (const dir of dirs) await walkTxtFiles(dir, files);
  const records = [];
  for (const path of files) {
    const { text, bom } = await readGameText(path);
    records.push({ path, text, bom });
  }
  return runRules(encodingRules, records, {});
}

// ===========================================================================
// Phase 5: Overlay ambiguities (from old validate.mjs)
// ===========================================================================

function runAmbiguities(eu4) {
  return eu4.ambiguities
    .filter((a) => !(a.key === 'SOF' && a.layer === 'vanilla'))
    .map((a) => ({
      id: 'overlay-ambiguity',
      level: 'info',
      message: `${a.dir}: key "${a.key}" (${a.layer} layer) is ambiguous between ${a.paths.map((p) => rel(p)).join(', ')}`,
    }));
}

// ===========================================================================
// Phase 6: Duplicate definitions (from audit.mjs)
// ===========================================================================

const AUDIT_SKIP_DIRS = new Set(['common/defines', 'common/custom_gui']);
const AUDIT_SKIP_PREFIXES = ['common/countries'];

function noteKey(buckets, bucket, key, file, line) {
  let byKey = buckets.get(bucket);
  if (!byKey) {
    byKey = new Map();
    buckets.set(bucket, byKey);
  }
  let occ = byKey.get(key);
  if (!occ) {
    occ = [];
    byKey.set(key, occ);
  }
  occ.push({ file, line });
}

function dupFindings(id, level, bucket, key, occ) {
  const sorted = [...occ].sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
  return [{
    id,
    level,
    file: sorted[0].file,
    line: sorted[0].line,
    message: `duplicate "${key}" in ${bucket}: ${sorted.map((s) => `${s.file}:${s.line}`).join(', ')}`,
  }];
}

async function runDuplicateDefinitions() {
  const findings = [];

  // --- common/ ---
  const commonBuckets = new Map(); // bucket -> Map<key, Array<{file, line}>>
  const commonFiles = await walkTxtFiles(join(MOD_ROOT, 'common'));
  for (const path of commonFiles) {
    const bucket = rel(join(path, '..'));
    if (AUDIT_SKIP_DIRS.has(bucket) || AUDIT_SKIP_PREFIXES.some((p) => bucket === p || bucket.startsWith(p + '/'))) continue;
    const { tree } = await parseFile(path);
    let keyBucket = bucket;
    if (bucket === 'common/province_names') {
      const stem = rel(path).split('/').pop().replace(/\.txt$/i, '').replace(/_new$/i, '');
      keyBucket = `${bucket}/${stem}`;
    }
    for (const item of tree.items) {
      if (item.kind !== 'pair') continue;
      noteKey(commonBuckets, keyBucket, item.keyToken.value, rel(path), item.keyToken.line);
    }
  }

  for (const [bucket, byKey] of [...commonBuckets.entries()].sort()) {
    for (const [key, occ] of byKey) {
      const files = new Set(occ.map((o) => o.file));
      if (occ.length > 1 && files.size > 1) {
        findings.push(...dupFindings('dup-common-cross-file', 'warn', bucket, key, occ));
      } else if (occ.length > 1) {
        findings.push(...dupFindings('dup-common-in-file', 'warn', bucket, key, occ));
      }
    }
  }

  // --- events/ ---
  const eventIds = new Map(); // id -> Array<{file, line}>
  const eventFiles = await walkTxtFiles(join(MOD_ROOT, 'events'));
  for (const path of eventFiles) {
    const { tree } = await parseFile(path);
    let namespace = null;
    for (const item of tree.items) {
      if (item.kind === 'pair' && item.keyToken.value === 'namespace'
          && item.value.type === 'scalar' && item.value.token) {
        namespace = item.value.token.value;
        continue;
      }
      if (item.kind !== 'pair' || !item.keyToken.value.endsWith('_event')
          || item.value.type !== 'block') continue;
      for (const inner of item.value.items) {
        if (inner.kind === 'pair' && inner.keyToken.value === 'id'
            && inner.value.type === 'scalar' && inner.value.token) {
          let id = inner.value.token.value;
          if (!id.includes('.') && namespace) id = `${namespace}.${id}`;
          let occ = eventIds.get(id);
          if (!occ) {
            occ = [];
            eventIds.set(id, occ);
          }
          occ.push({ file: rel(path), line: inner.keyToken.line });
          break;
        }
      }
    }
  }

  for (const [id, occ] of [...eventIds.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
    if (occ.length > 1) {
      findings.push(...dupFindings('dup-event-id', 'error', 'events', id, occ));
    }
  }

  // --- common/scripted_effects/ and common/scripted_triggers/ ---
  for (const subdir of ['common/scripted_effects', 'common/scripted_triggers']) {
    const files = await walkTxtFiles(join(MOD_ROOT, subdir));
    const names = new Map(); // name -> Array<{file, line}>
    for (const path of files) {
      const { tree } = await parseFile(path);
      for (const item of tree.items) {
        if (item.kind === 'pair') {
          let occ = names.get(item.keyToken.value);
          if (!occ) {
            occ = [];
            names.set(item.keyToken.value, occ);
          }
          occ.push({ file: rel(path), line: item.keyToken.line });
        }
      }
    }
    const id = subdir === 'common/scripted_effects' ? 'dup-scripted-effect' : 'dup-scripted-trigger';
    for (const [name, occ] of names) {
      if (occ.length > 1) {
        findings.push(...dupFindings(id, 'warn', subdir, name, occ));
      }
    }
  }

  return findings;
}

// ===========================================================================
// Phase 7: Province/area/region/trade-node refs in events/decisions/missions (NEW)
// ===========================================================================

const ENGINE_AREA_KEYWORDS = new Set([
  'random_owned_area', 'random_enemy_area', 'random_neighboring_area',
  'random_area', 'any_owned_area', 'any_area', 'every_owned_area',
  'every_area', 'any_neighbor_area', 'every_neighbor_area',
  'random_neighbor_area', 'has_trade_company_investment_in_area',
]);

const ENGINE_REGION_KEYWORDS = new Set([
  'random_owned_region', 'random_region', 'any_owned_region', 'any_region',
  'every_owned_region', 'every_region', 'random_new_world_region',
  'any_neighbor_region', 'every_neighbor_region', 'random_neighbor_region',
]);

// Trade-node iterator scopes and trigger/effect names that end in _node but
// are NOT trade-node-name scopes. A real trade node scope is just
// "<node_name> = { ... }" where node_name is a lowercase identifier from
// 00_tradenodes.txt.
const ENGINE_TRADE_NODE_KEYWORDS = new Set([
  'any_active_trade_node', 'home_trade_node', 'any_trade_node',
  'every_trade_node', 'random_trade_node', 'any_neighbor_trade_node',
  'every_neighbor_trade_node', 'random_neighbor_trade_node',
  'capital_trade_node', 'random_active_trade_node',
  'every_active_trade_node', 'any_core_trade_node', 'every_core_trade_node',
  'random_core_trade_node', 'all_trade_node',
  'has_privateer_share_in_trade_node', 'has_trade_power_in_trade_node',
  'has_missionary_in_trade_node',
]);

// Prefixes/patterns that indicate a key is a trigger, effect, event_target,
// or variable rather than a named scope. These never represent area/region/
// trade-node definitions.
const NON_SCOPE_PREFIXES = ['has_', 'event_target:', '@', 'set_', 'change_',
  'add_', 'remove_', 'is_', 'can_', 'does_'];

function isNonScopeKey(key) {
  return NON_SCOPE_PREFIXES.some((p) => key.startsWith(p)) || key.includes(':');
}

// Fields whose scalar value should be a province ID
const PROVINCE_ID_FIELDS = new Set([
  'province_id', 'owns_core_province', 'capital', 'capital_province',
  'province', 'target_province', 'hidden_province',
  'fleet_size_province', 'missionary_province', 'reformation_center',
]);

const DATE_LIKE = /^\d{1,4}\.\d{1,2}\.\d{1,2}$/;
const PURE_NUMBER = /^\d+$/;

function walkItems(items, fn) {
  for (const item of items) {
    fn(item);
    if (item.kind === 'pair' && item.value.type === 'block') {
      walkItems(item.value.items, fn);
    }
  }
}

async function runScopeRefs(mapSets) {
  const findings = [];
  const dirs = ['events', 'decisions', 'missions'];

  for (const dirName of dirs) {
    const files = await walkTxtFiles(join(MOD_ROOT, dirName));
    for (const path of files) {
      const { tree } = await parseFile(path);
      const fileRel = rel(path);

      walkItems(tree.items, (item) => {
        if (item.kind !== 'pair') return;
        const key = item.keyToken.value;
        const line = item.keyToken.line;

        // Check province-id fields with scalar numeric values
        if (PROVINCE_ID_FIELDS.has(key) && item.value.type === 'scalar' && item.value.token) {
          const val = item.value.token.value;
          if (PURE_NUMBER.test(val)) {
            const id = Number(val);
            if (!mapSets.provinces.has(id)) {
              findings.push({
                id: 'scope-province-ref', level: 'warn', file: fileRel, line,
                message: `province_id ${val} (field "${key}") is not a valid province in definition.csv`,
              });
            }
          }
        }

        // Check bare-number scopes: "1234 = { ... }" - verify it's a valid province
        if (item.value.type === 'block' && PURE_NUMBER.test(key) && !DATE_LIKE.test(key)) {
          const id = Number(key);
          if (!mapSets.provinces.has(id)) {
            findings.push({
              id: 'scope-province-scope', level: 'warn', file: fileRel, line,
              message: `province scope "${key}" is not a valid province in definition.csv`,
            });
          }
        }

        // Check _area scopes
        if (item.value.type === 'block' && key.endsWith('_area') && !ENGINE_AREA_KEYWORDS.has(key) && !isNonScopeKey(key)) {
          if (!mapSets.areas.has(key)) {
            findings.push({
              id: 'scope-area-ref', level: 'warn', file: fileRel, line,
              message: `area "${key}" is not defined in map/area.txt`,
            });
          }
        }

        // Check _region scopes
        if (item.value.type === 'block' && key.endsWith('_region') && !ENGINE_REGION_KEYWORDS.has(key) && !isNonScopeKey(key)) {
          if (!mapSets.regions.has(key)) {
            findings.push({
              id: 'scope-region-ref', level: 'warn', file: fileRel, line,
              message: `region "${key}" is not defined in map/region.txt`,
            });
          }
        }

        // Check _node scopes
        if (item.value.type === 'block' && key.endsWith('_node') && !ENGINE_TRADE_NODE_KEYWORDS.has(key) && !isNonScopeKey(key) && key === key.toLowerCase() && !key.includes('_best_')) {
          if (!mapSets.tradeNodes.has(key)) {
            findings.push({
              id: 'scope-tradenode-ref', level: 'warn', file: fileRel, line,
              message: `trade node "${key}" is not defined in common/tradenodes/`,
            });
          }
        }
      });
    }
  }

  return findings;
}

// ===========================================================================
// Phase 8: Manifest consistency (from build_history_english.mjs check)
// ===========================================================================

async function runManifestCheck() {
  const findings = [];
  const started = Date.now();
  try {
    const manifest = await loadManifest(MANIFEST_PATH);
    const summary = await validateManifestAgainstRoot(manifest, root);
    if (summary.stale.length) {
      const sample = summary.stale.slice(0, 5).join(', ');
      findings.push({
        id: 'manifest-stale', level: 'error',
        message: `${summary.stale.length} file(s) changed since last manifest stamp (e.g. ${sample}${summary.stale.length > 5 ? ', ...' : ''}); run: node tools/history_language_manifest.mjs stamp`,
      });
    }
  } catch (error) {
    findings.push({
      id: 'manifest-consistency', level: 'error',
      message: error.message,
    });
  }
  console.log(`Manifest check took ${((Date.now() - started) / 1000).toFixed(1)}s`);
  return findings;
}

// ===========================================================================
// Phase 9: Localisation source vs built (from localisation.mjs check)
// ===========================================================================

function sha256(buffer) {
  return createHash('sha256').update(buffer).digest('hex');
}

async function listLocalisationFiles(dirRoot) {
  const files = [];
  async function visit(directory) {
    const entries = await readdir(directory, { withFileTypes: true });
    for (const entry of entries) {
      const path = join(directory, entry.name);
      if (entry.isDirectory()) await visit(path);
      else if (entry.isFile() && entry.name.endsWith('.yml')) {
        files.push(relative(dirRoot, path).replaceAll('\\', '/'));
      }
    }
  }
  await visit(dirRoot);
  return files.sort();
}

async function runLocalisationCheck() {
  const findings = [];

  const [sourceFiles, encodedFiles] = await Promise.all([
    listLocalisationFiles(LOC_SOURCE_ROOT),
    listLocalisationFiles(LOC_ENCODED_ROOT),
  ]);

  const sourceSet = new Set(sourceFiles);
  const encodedSet = new Set(encodedFiles);

  for (const path of sourceFiles) {
    if (!encodedSet.has(path)) {
      findings.push({ id: 'loc-file-set', level: 'error', message: `missing encoded file: ${path}` });
    }
  }
  for (const path of encodedFiles) {
    if (!sourceSet.has(path)) {
      findings.push({ id: 'loc-file-set', level: 'error', message: `missing source file: ${path}` });
    }
  }

  // Check manifest currency + hash comparison
  let manifest = null;
  try {
    manifest = JSON.parse(await readFile(LOC_MANIFEST_PATH, 'utf8'));
  } catch {
    // no manifest - will fall through to re-encode check
  }

  const codecSha256 = sha256(await readFile(CODEC_PATH));
  const manifestCurrent = manifest
    && manifest.version === 1
    && manifest.profile === 'compatible'
    && manifest.codecSha256 === codecSha256;

  let outOfDate = false;

  for (const path of sourceFiles) {
    if (!encodedSet.has(path)) continue;
    const sourceBuffer = await readFile(join(LOC_SOURCE_ROOT, path));
    const encodedBuffer = await readFile(join(LOC_ENCODED_ROOT, path));

    if (!hasUtf8Bom(encodedBuffer)) {
      findings.push({ id: 'loc-bom', level: 'error', message: `missing UTF-8 BOM: ${path}` });
    }

    const sourceSha256 = sha256(sourceBuffer);
    const encodedSha256 = sha256(encodedBuffer);
    const entry = manifestCurrent ? manifest.files?.[path] : null;

    if (entry && entry.sourceSha256 === sourceSha256 && entry.encodedSha256 === encodedSha256) {
      continue; // verified via manifest
    }

    // Fall back to re-encode-and-compare
    let expected;
    try {
      expected = encodeBuffer(new TextDecoder('utf-8', { fatal: true }).decode(
        sourceBuffer.subarray(0, 3).equals(Buffer.from([0xef, 0xbb, 0xbf])) ? sourceBuffer.subarray(3) : sourceBuffer,
      ), { profile: 'compatible' });
    } catch (error) {
      findings.push({ id: 'loc-encode', level: 'error', message: `failed to encode ${path}: ${error.message}` });
      outOfDate = true;
      continue;
    }

    if (!encodedBuffer.equals(expected)) {
      findings.push({ id: 'loc-stale', level: 'error', message: `encoded localisation is out of date: ${path}` });
      outOfDate = true;
    }
  }

  if (!manifestCurrent || outOfDate) {
    findings.push({ id: 'loc-manifest', level: 'error', message: 'localisation_manifest.json is out of date; run the build command' });
  }

  return findings;
}

// ===========================================================================
// Phase 10: English overlay (from build_variants.mjs validateEnglishOverlay)
// ===========================================================================

async function listEnglishFiles(directory, englishOnly = false) {
  const files = [];
  async function visit(current) {
    for (const entry of await readdir(current, { withFileTypes: true })) {
      const path = join(current, entry.name);
      if (entry.isDirectory()) await visit(path);
      else if (entry.isFile() && entry.name.endsWith('.yml') && (!englishOnly || entry.name.endsWith('_l_english.yml'))) {
        files.push(relative(directory, path).replaceAll('\\', '/'));
      }
    }
  }
  await visit(directory);
  return files.sort();
}

function parseLocEntries(content) {
  return [...content.split(/\r?\n/)].flatMap((line) => {
    const match = line.match(/^\s*([^\s:#]+):(?:\d+)?\s+".*"/);
    return match ? [[match[1], line.trimEnd()]] : [];
  });
}

async function readKeyLineIndex(directory, rejectDuplicates = false, englishOnly = false) {
  const index = new Map();
  for (const file of await listEnglishFiles(directory, englishOnly)) {
    const content = await readFile(join(directory, file), 'utf8');
    for (const [key, line] of parseLocEntries(content)) {
      if (rejectDuplicates && index.has(key)) {
        throw new Error('duplicate localisation key ' + key + ' in ' + index.get(key).file + ' and ' + file);
      }
      index.set(key, { file, line });
    }
  }
  return index;
}

async function runEnglishOverlay() {
  const findings = [];

  if (!await exists(ENGLISH_SOURCE)) {
    findings.push({ id: 'english-overlay', level: 'error', message: 'missing localisation_english_source' });
    return findings;
  }

  let provenance;
  try {
    provenance = JSON.parse(await readFile(ENGLISH_PROVENANCE, 'utf8'));
  } catch (error) {
    findings.push({ id: 'english-overlay', level: 'error', message: `cannot read provenance: ${error.message}` });
    return findings;
  }

  let chineseKeys, vanillaKeys, customKeys;
  try {
    [chineseKeys, vanillaKeys, customKeys] = await Promise.all([
      readKeyLineIndex(CHINESE_SOURCE),
      readKeyLineIndex(GAME_LOCALISATION, false, true),
      readKeyLineIndex(ENGLISH_SOURCE, true),
    ]);
  } catch (error) {
    findings.push({ id: 'english-overlay', level: 'error', message: error.message });
    return findings;
  }

  // No vanilla override without allowVanillaOverride
  for (const [key, entry] of customKeys) {
    if (vanillaKeys.has(key)) {
      const filePolicy = provenance.files?.[entry.file];
      if (!filePolicy?.allowVanillaOverride) {
        findings.push({
          id: 'english-vanilla-override', level: 'error', file: entry.file,
          message: `English source must not override vanilla key ${key}`,
        });
      }
    }
  }

  // Every Chinese key must have English coverage
  const missing = [...chineseKeys.keys()].filter((key) => !vanillaKeys.has(key) && !customKeys.has(key));
  if (missing.length) {
    const grouped = new Map();
    for (const key of missing) {
      const file = chineseKeys.get(key).file;
      grouped.set(file, (grouped.get(file) ?? 0) + 1);
    }
    findings.push({
      id: 'english-incomplete', level: 'error',
      message: 'English source is incomplete:\n' + [...grouped].map(([file, count]) => file + ': ' + count).join('\n'),
    });
  }

  // No unused English keys
  const unused = [...customKeys.keys()].filter((key) => !chineseKeys.has(key));
  if (unused.length) {
    findings.push({
      id: 'english-unused', level: 'error',
      message: `English source contains keys absent from the Chinese base: ${unused.slice(0, 20).join(', ')}`,
    });
  }

  // Provenance files match source files
  const files = await listEnglishFiles(ENGLISH_SOURCE);
  for (const file of files) {
    if (!provenance.files?.[file]) {
      findings.push({ id: 'english-provenance', level: 'error', message: `missing provenance record: ${file}` });
    }
  }
  for (const file of Object.keys(provenance.files ?? {})) {
    if (!files.includes(file)) {
      findings.push({ id: 'english-provenance', level: 'error', message: `provenance record has no source file: ${file}` });
    }
  }

  return findings;
}

// ===========================================================================
// Output
// ===========================================================================

function printCategory(label, findings) {
  if (findings.length === 0) {
    console.log(`\n[${label}] (no findings)`);
    return;
  }
  console.log(`\n[${label}] (${findings.length})`);
  const byId = new Map();
  for (const f of findings) {
    if (!byId.has(f.id)) byId.set(f.id, []);
    byId.get(f.id).push(f);
  }
  for (const [id, list] of byId) {
    console.log(`\n  [${list[0].level}] ${id} (${list.length})`);
    for (const f of list) {
      const position = f.file ? `${f.file}:${f.line ?? '?'}:${f.col ?? '?'}: ` : '';
      console.log(`    ${position}${f.message}`);
    }
  }
}

// ===========================================================================
// Main
// ===========================================================================

async function main() {
  console.log('Loading EU4 + mod tree...');
  const eu4 = await load({ game: VANILLA_ROOT, mod: MOD_ROOT });
  const definedSets = await buildDefinedSets({ gameRoot: VANILLA_ROOT, modRoot: MOD_ROOT });
  const mapSets = await buildMapSets();
  const ctx = { definedSets };

  console.log('Running ref integrity...');
  const refFindings = await runRefs(eu4, ctx);

  console.log('Running province/country warnings...');
  const pcFindings = await runProvinceCountryWarnings(eu4, ctx);

  console.log('Running encoding checks...');
  const encodingFindings = await runEncoding();

  console.log('Running overlay ambiguity checks...');
  const ambiguityFindings = runAmbiguities(eu4);

  console.log('Running duplicate definition checks...');
  const dupFindings = await runDuplicateDefinitions();

  console.log('Running scope reference checks (events/decisions/missions)...');
  const scopeFindings = await runScopeRefs(mapSets);

  console.log('Running manifest consistency checks...');
  const manifestFindings = await runManifestCheck();

  console.log('Running localisation source vs built checks...');
  const locFindings = await runLocalisationCheck();

  console.log('Running English overlay checks...');
  const englishFindings = await runEnglishOverlay();

  const allFindings = [
    ...refFindings,
    ...pcFindings,
    ...encodingFindings,
    ...ambiguityFindings,
    ...dupFindings,
    ...scopeFindings,
    ...manifestFindings,
    ...locFindings,
    ...englishFindings,
  ];

  printCategory('Ref Integrity', refFindings);
  printCategory('Province/Country Warnings', pcFindings);
  printCategory('Encoding', encodingFindings);
  printCategory('Overlay Ambiguities', ambiguityFindings);
  printCategory('Duplicate Definitions', dupFindings);
  printCategory('Scope References', scopeFindings);
  printCategory('Manifest Consistency', manifestFindings);
  printCategory('Localisation Source vs Built', locFindings);
  printCategory('English Overlay', englishFindings);

  const summary = summarize(allFindings);
  console.log(`\n${summary.error} errors, ${summary.warn} warnings, ${summary.info} infos`);

  process.exitCode = summary.error > 0 ? 1 : 0;
}

main().catch((err) => {
  console.error(err);
  process.exitCode = 1;
});