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
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
// The unified API over a position-preserving tree (ast.mjs). One class for
// ALL Clausewitz data — provinces, countries, cultures, events, whatever —
// because it's all the same shape: a positioned key-value tree where
// duplicate keys and duplicate date blocks are normal and must never be
// collapsed.
//
// Mutating methods (`set`/`add`/`remove`) never touch `this.items` and never
// synthesize a new tree: they compute a byte-offset splice and hand it to
// this file's EditSession (edit.mjs). Reading a Node again after mutating it
// through it will NOT reflect the edit — the source of truth after a
// mutation is the pending splice list, not the in-memory tree. This is
// deliberate: the whole point of this package is that text output is
// derived only from {original text + splices}, never from re-walking a
// tree, so the tree is not kept in sync with pending edits.

const DATE_KEY_RE = /^(\d{1,4})\.(\d{1,2})\.(\d{1,2})$/;

/**
 * Whether a string is a Clausewitz date key (e.g. "1444.11.11"). Exported so
 * callers/tests can reuse the exact same rule `at()` uses internally.
 *
 * @param {string} value
 * @returns {boolean}
 */
export function isDateKey(value) {
  return DATE_KEY_RE.test(value);
}

function parseDate(value) {
  const m = DATE_KEY_RE.exec(value);
  if (!m) return null;
  return { year: Number(m[1]), month: Number(m[2]), day: Number(m[3]) };
}

function compareDates(a, b) {
  return (a.year - b.year) || (a.month - b.month) || (a.day - b.day);
}

export class Node {
  /**
   * @param {Object} opts
   * @param {Array} [opts.items] - this scope's items (pair|bare), from ast.mjs. Absent in resolved (at()) mode.
   * @param {import('./lexer.mjs').Token[]} opts.tokens - full token array for the file
   * @param {string} opts.text - full original text for the file
   * @param {string} opts.path - absolute path of the file this node belongs to
   * @param {'vanilla'|'mod'} [opts.layer]
   * @param {import('./edit.mjs').EditSession|null} opts.session - null for read-only (at()) nodes
   * @param {boolean} [opts.readonly]
   * @param {import('./lexer.mjs').Token|null} [opts.lbraceToken] - null for the root node
   * @param {import('./lexer.mjs').Token|null} [opts.rbraceToken] - null for root, or an unclosed block
   * @param {Map|null} [opts.resolved] - resolved-view backing map, set only by at()
   * @param {{start:number,end:number}|null} [opts.baseSpan] - span to report as .raw when resolved
   */
  constructor(opts) {
    this.items = opts.items ?? null;
    this.tokens = opts.tokens;
    this.text = opts.text;
    this.path = opts.path;
    this.layer = opts.layer;
    this.session = opts.session ?? null;
    this.readonly = Boolean(opts.readonly);
    this.lbraceToken = opts.lbraceToken ?? null;
    this.rbraceToken = opts.rbraceToken ?? null;
    this._resolved = opts.resolved ?? null;

    if (this._resolved) {
      this._span = opts.baseSpan ?? { start: 0, end: this.text.length };
    } else if (this.lbraceToken) {
      const endTok = this.rbraceToken ?? this.tokens[this.tokens.length - 1];
      this._span = {
        start: this.lbraceToken.index,
        end: this.rbraceToken
          ? this.rbraceToken.index + this.rbraceToken.length
          : endTok.index + endTok.length,
      };
    } else {
      this._span = { start: 0, end: this.text.length };
    }
  }

  // ---- internal helpers -------------------------------------------------

  _matching(key) {
    return this.items.filter((it) => it.kind === 'pair' && it.keyToken.value === key);
  }

  _unwrap(valueNode) {
    if (valueNode.type === 'scalar') {
      return valueNode.token ? valueNode.token.value : undefined;
    }
    return this._wrapBlock(valueNode);
  }

  _wrapBlock(blockValue) {
    const lbraceToken = this.tokens[blockValue.startTokenIndex];
    const rbraceToken = blockValue.closed ? this.tokens[blockValue.endTokenIndex] : null;
    return new Node({
      items: blockValue.items,
      tokens: this.tokens,
      text: this.text,
      path: this.path,
      layer: this.layer,
      session: this.session,
      readonly: this.readonly,
      lbraceToken,
      rbraceToken,
    });
  }

  _toResolvedEntry(valueNode) {
    if (valueNode.type === 'scalar') {
      return { kind: 'scalar', value: valueNode.token ? valueNode.token.value : undefined };
    }
    return { kind: 'block', value: this._wrapBlock(valueNode) };
  }

  // For add_X/remove_X verbs, the operand is expected to be a plain scalar
  // (a tag, a culture id, etc.) in every real case measured. If some future
  // data ever puts a block there, fall back to its raw source slice rather
  // than throw — at() must never crash on unexpected-but-real shapes.
  _scalarOf(valueNode) {
    if (valueNode.type === 'scalar') {
      return valueNode.token ? valueNode.token.value : '';
    }
    const start = this.tokens[valueNode.startTokenIndex];
    const end = this.tokens[valueNode.endTokenIndex];
    return this.text.slice(start.index, end.index + end.length);
  }

  _assertWritable() {
    if (this.readonly) {
      throw new Error(
        'cannot mutate a node produced by at() — it is a read-only resolved view; '
        + 'edit the underlying block via node.blocks() instead',
      );
    }
  }

  _quoteIfNeeded(value, wasQuoted) {
    const needsQuote = wasQuoted || /\s/.test(value);
    if (!needsQuote) return value;
    if (value.includes('"')) {
      throw new Error(`cannot quote value containing a double-quote character: ${JSON.stringify(value)}`);
    }
    return `"${value}"`;
  }

  _locate(index) {
    let line = 1;
    let col = 1;
    for (let i = 0; i < index && i < this.text.length; i += 1) {
      if (this.text[i] === '\n') {
        line += 1;
        col = 1;
      } else {
        col += 1;
      }
    }
    return { line, col };
  }

  // ---- the 12-method API (+ bareValues, see below) -----------------------

  get(key) {
    if (this._resolved) {
      const entry = this._resolved.get(key);
      if (!entry) return undefined;
      if (entry.kind === 'accum') {
        throw new Error(`get(): "${key}" is a date-accumulated set with ${entry.set.size} value(s); use all()`);
      }
      return entry.value;
    }
    const matches = this._matching(key);
    if (matches.length > 1) {
      throw new Error(`get(): key "${key}" occurs ${matches.length} times; use all()`);
    }
    if (matches.length === 0) return undefined;
    return this._unwrap(matches[0].value);
  }

  all(key) {
    if (this._resolved) {
      const entry = this._resolved.get(key);
      if (!entry) return [];
      if (entry.kind === 'accum') return [...entry.set];
      return [entry.value];
    }
    return this._matching(key).map((m) => this._unwrap(m.value));
  }

  has(key) {
    if (this._resolved) {
      const entry = this._resolved.get(key);
      if (!entry) return false;
      if (entry.kind === 'accum') return entry.set.size > 0;
      return true;
    }
    return this._matching(key).length > 0;
  }

  keys() {
    if (this._resolved) {
      return [...this._resolved.keys()].filter((k) => this.has(k));
    }
    return this.items.filter((it) => it.kind === 'pair').map((it) => it.keyToken.value);
  }

  // Not one of the spec's headline 12 methods, but necessary: a block whose
  // contents are a bare-value list (`historical_idea_groups = { economic_ideas
  // offensive_ideas }`) or an RGB triple (`color = { 20 50 210 }`) has no
  // keys at all — `keys()` on it is correctly `[]`. This is the reader for
  // that shape. Not meaningful on an at() view (date blocks never hold bare
  // lists in real data), so it returns [] there rather than throwing.
  bareValues() {
    if (this._resolved) return [];
    return this.items.filter((it) => it.kind === 'bare').map((it) => it.token.value);
  }

  block(key) {
    if (this._resolved) {
      const entry = this._resolved.get(key);
      if (!entry) return undefined;
      if (entry.kind === 'accum') {
        throw new Error(`block(): "${key}" is a date-accumulated set, not a block`);
      }
      if (entry.kind !== 'block') {
        throw new TypeError(`block(): value for key "${key}" is not a block`);
      }
      return entry.value;
    }
    const matches = this._matching(key);
    if (matches.length > 1) {
      throw new Error(`block(): key "${key}" occurs ${matches.length} times; use blocks()`);
    }
    if (matches.length === 0) return undefined;
    const value = matches[0].value;
    if (value.type !== 'block') {
      throw new TypeError(`block(): value for key "${key}" is not a block`);
    }
    return this._wrapBlock(value);
  }

  blocks(key) {
    if (this._resolved) {
      if (key === undefined) {
        const out = [];
        for (const entry of this._resolved.values()) {
          if (entry.kind === 'block') out.push(entry.value);
        }
        return out;
      }
      const entry = this._resolved.get(key);
      if (!entry) return [];
      if (entry.kind !== 'block') {
        throw new TypeError(`blocks(): value for key "${key}" is not a block`);
      }
      return [entry.value];
    }
    if (key === undefined) {
      return this.items
        .filter((it) => it.kind === 'pair' && it.value.type === 'block')
        .map((it) => this._wrapBlock(it.value));
    }
    return this._matching(key).map((m) => {
      if (m.value.type !== 'block') {
        throw new TypeError(`blocks(): value for key "${key}" is not a block (found a scalar)`);
      }
      return this._wrapBlock(m.value);
    });
  }

  set(key, value) {
    this._assertWritable();
    if (typeof value !== 'string') throw new TypeError('set(): value must be a string');
    const matches = this._matching(key);
    if (matches.length !== 1) {
      throw new Error(
        `set(): requires exactly one existing entry for key "${key}"; found ${matches.length} `
        + '(use add() to create one)',
      );
    }
    const valueNode = matches[0].value;
    if (valueNode.type !== 'scalar') {
      throw new Error(`set(): value for key "${key}" is a block; edit its contents via block() instead`);
    }
    const token = valueNode.token;
    if (!token) throw new Error(`set(): key "${key}" has no value token to replace (malformed entry)`);
    const raw = this._quoteIfNeeded(value, token.kind === 'string');
    this.session.splice(token.index, token.length, raw);
  }

  add(key, value) {
    this._assertWritable();
    if (typeof value !== 'string') throw new TypeError('add(): value must be a string');
    const raw = this._quoteIfNeeded(value, false);
    const entryText = `${key} = ${raw}`;

    if (this.items.length > 0) {
      const lastItem = this.items[this.items.length - 1];
      const lastToken = this.tokens[lastItem.endTokenIndex];
      const insertAt = lastToken.index + lastToken.length;
      const beforeTok = this.tokens[lastItem.startTokenIndex - 1];
      const leading = (beforeTok && beforeTok.kind === 'whitespace') ? beforeTok.raw : '\n';
      this.session.splice(insertAt, 0, leading + entryText);
      return;
    }

    // Empty scope: no existing entry to copy indentation style from. This
    // path has no real-data precedent to match, so it's a documented
    // heuristic rather than a derived rule.
    if (this.lbraceToken) {
      const insertAt = this.lbraceToken.index + this.lbraceToken.length;
      this.session.splice(insertAt, 0, ` ${entryText} `);
    } else {
      this.session.splice(this.text.length, 0, `${entryText}\n`);
    }
  }

  remove(key, value) {
    this._assertWritable();
    const matches = this.items.filter((it) => it.kind === 'pair' && it.keyToken.value === key
      && (value === undefined || this._unwrap(it.value) === value));

    for (const m of matches) {
      const startTok = this.tokens[m.startTokenIndex];
      const endTok = this.tokens[m.endTokenIndex];
      let spanStart = startTok.index;
      let spanEnd = endTok.index + endTok.length;

      // Consume one adjacent whitespace run so deletion doesn't leave a
      // blank line: prefer the run right after (up to and including its
      // first newline, so an intentional blank line further down survives),
      // falling back to the run right before when this is the last entry
      // in the scope (nothing whitespace-shaped follows it).
      const afterTok = this.tokens[m.endTokenIndex + 1];
      if (afterTok && afterTok.kind === 'whitespace') {
        const nl = afterTok.raw.indexOf('\n');
        spanEnd += nl !== -1 ? nl + 1 : afterTok.length;
      } else {
        const beforeTok = this.tokens[m.startTokenIndex - 1];
        if (beforeTok && beforeTok.kind === 'whitespace') {
          spanStart -= beforeTok.length;
        }
      }

      this.session.splice(spanStart, spanEnd - spanStart, '');
    }

    return matches.length;
  }

  at(dateStr) {
    if (this._resolved) {
      throw new Error('at(): cannot call at() on a node that is already an at() view');
    }
    const target = parseDate(dateStr);
    if (!target) {
      throw new Error(`at(): "${dateStr}" is not a valid date key (expected e.g. "1444.11.11")`);
    }

    const resolved = new Map();

    // Applies one pair item's verb semantics (plain overwrite, or add_X /
    // remove_X accumulation into bucket X) into `resolved`. Used for BOTH
    // this node's own bare (pre-date) top-level fields and every date
    // block's inner items — `add_core = FRI` sitting bare at the top of a
    // province file is exactly as much an accumulation into bucket `core`
    // as a later `add_core` inside a date block is; there is nothing
    // date-block-specific about the verb, only about which entries qualify
    // by date. This is what makes duplicate top-level `add_core`/`add_core`
    // entries (confirmed normal in real data, e.g. Toledo's TLD+CAS cores)
    // resolve correctly through at() instead of colliding as if plain
    // overwrites of the same key.
    //
    // None of this affects `node.get('add_core')`/`node.get('owner')` on
    // THIS node (no at()) — those never call this method at all, so the
    // literal bare fields stay reachable through the normal read path
    // completely unaffected by at()'s bucket renaming or overwrite
    // resolution.
    const applyItem = (inner) => {
      if (inner.kind !== 'pair') return;
      const k = inner.keyToken.value;

      if (k.startsWith('add_')) {
        const bucket = k.slice(4);
        let entry = resolved.get(bucket);
        if (!entry || entry.kind !== 'accum') entry = { kind: 'accum', set: new Set() };
        entry.set.add(this._scalarOf(inner.value));
        resolved.set(bucket, entry);
      } else if (k.startsWith('remove_')) {
        const bucket = k.slice(7);
        const entry = resolved.get(bucket);
        if (entry && entry.kind === 'accum') entry.set.delete(this._scalarOf(inner.value));
        // Removing something never added: no-op, per spec.
      } else {
        resolved.set(k, this._toResolvedEntry(inner.value));
      }
    };

    for (const it of this.items) {
      if (it.kind !== 'pair' || isDateKey(it.keyToken.value)) continue;
      applyItem(it);
    }

    const dateBlocks = this.items
      .map((it, idx) => ({ it, idx }))
      .filter(({ it }) => it.kind === 'pair' && isDateKey(it.keyToken.value) && it.value.type === 'block');

    // Chronological order; original file order breaks ties (duplicate date
    // blocks are normal in real data — see history/countries/FRA - France.txt).
    dateBlocks.sort((a, b) => {
      const cmp = compareDates(parseDate(a.it.keyToken.value), parseDate(b.it.keyToken.value));
      return cmp !== 0 ? cmp : a.idx - b.idx;
    });

    for (const { it } of dateBlocks) {
      const blockDate = parseDate(it.keyToken.value);
      if (compareDates(blockDate, target) > 0) continue;

      for (const inner of it.value.items) applyItem(inner);
    }

    return new Node({
      tokens: this.tokens,
      text: this.text,
      path: this.path,
      layer: this.layer,
      session: null,
      readonly: true,
      resolved,
      baseSpan: this._span,
    });
  }

  get raw() {
    const { line, col } = this._locate(this._span.start);
    return {
      text: this.text.slice(this._span.start, this._span.end),
      index: this._span.start,
      line,
      col,
      length: this._span.end - this._span.start,
    };
  }

  get file() {
    return { path: this.path, layer: this.layer };
  }
}