"use strict";

const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");

const root = path.resolve(__dirname, "../..");
const app = fs.readFileSync(path.join(root, "Web/app.js"), "utf8");
const index = fs.readFileSync(path.join(root, "Web/index.html"), "utf8");
const bridge = fs.readFileSync(path.join(root, "MainWindow.NamedComparisonRestore.cs"), "utf8");
const namedBridge = fs.readFileSync(path.join(root, "MainWindow.NamedPlaylists.cs"), "utf8");
const core = fs.readFileSync(
  path.join(root, "src/MBN_STOCK_WEBVIEW.Core/Data/LegacyNamedComparisonRestore.cs"),
  "utf8");

test("named loads perform one correlated native comparison identity pass", () => {
  assert.match(index, /<script src="named-comparison-restore-workflow\.js"><\/script>/u);
  assert.match(app, /MbnNamedComparisonRestoreWorkflow/u);
  assert.match(app, /namedComparisonRestoreWorkflow\.classify/u);
  assert.match(app, /namedComparisonRestoreWorkflow\.normalizeResponse/u);
  assert.match(app, /namedComparisonRestoreWorkflow\.materialize/u);
  assert.match(app, /case "named-comparison-restore-results"/u);
  assert.match(app, /case "named-comparison-restore-error"/u);
  assert.match(namedBridge, /await PostNamedComparisonRestoreAsync\(/u);
  assert.match(bridge, /PostMessage\("named-comparison-restore-results"/u);
  assert.match(bridge, /PostMessage\("named-comparison-restore-error"/u);
});

test("the old fake KOSPI and fabricated R-code restore path is gone", () => {
  assert.doesNotMatch(app, /function namedComparisonTarget/u);
  assert.doesNotMatch(app, /R\$\{itemIndex\}\$\{tokenIndex\}/u);
  assert.doesNotMatch(app, /addComparisonNamedCandidates/u);
  assert.match(core, /MissingMarketIdentity/u);
  assert.match(core, /row\.GroupCode == "종목"/u);
});

test("generic catalog and stored-entry paths cannot create name-only comparison graphs", () => {
  assert.match(app, /operatorInputBuilderKeys[\s\S]*"s5026"[\s\S]*"s5029"[\s\S]*"s5087"/u);
  assert.match(app,
    /if \(\["s5026", "s5029", "s5087"\]\.includes\(item\.builderKey\)\)[\s\S]*전용 입력 화면/u);
  assert.match(app,
    /if \(definition\.reachable === false \|\| operatorInputBuilderKeys\.has\(definition\.builderKey\)\) continue/u);
  assert.match(app,
    /if \(operatorInputBuilderKeys\.has\(String\(item\.builderKey \|\| ""\)\) \|\| item\.operator !== undefined\)[\s\S]*return \[\]/u);
});

test("identity restoration is read-only, bound, playout-priority aware, and never reaches Tornado", () => {
  assert.match(core, /new DataQueryParameter\("stock_name"/u);
  assert.doesNotMatch(core, /\b(?:INSERT\s+INTO|UPDATE\s+[A-Z_]|DELETE\s+FROM|MERGE\s+INTO)\b/iu);
  assert.match(bridge, /Volatile\.Read\(ref _playoutCommandInFlight\)/u);
  assert.match(bridge, /자동 재시도하지 않습니다/u);
  assert.doesNotMatch(bridge, /Tornado|TakeIn|PrepareAsync|ExecuteNonQuery/iu);
});
