#!/usr/bin/env node
/**
 * sync-fixture.js <fixture-path>
 *
 * Re-copies a single fixture file from its syntax-test source and updates
 * the sourceHash in .manifest.json.
 *
 * Usage:
 *   node scripts/sync-fixture.js included-files/include-behaviour.TXT
 *
 * The fixture path is relative to test/unit/fixtures/.
 * The script resolves the source path from the manifest entry.
 *
 * After syncing, re-run the test suite to confirm unit tests still pass:
 *   npx jest test/unit/fixture-integrity
 *   npx jest                              (full suite)
 */

import * as crypto from "crypto";
import * as fs from "fs";
import * as path from "path";

import { fileURLToPath } from "url";
import { dirname } from "path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const fixturePath = process.argv[2];
if (!fixturePath) {
  console.error("Usage: node scripts/sync-fixture.js <fixture-path>");
  console.error("  e.g. node scripts/sync-fixture.js included-files/include-behaviour.TXT");
  process.exit(1);
}

const testBase = path.resolve(__dirname, "../test");
const fixtureBase = path.join(testBase, "unit", "fixtures");
const manifestPath = path.join(fixtureBase, ".manifest.json");

const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));

const normFixture = fixturePath.replace(/\\/g, "/");
const entryIndex = manifest.fixtures.findIndex((e) => e.fixture === normFixture);

if (entryIndex === -1) {
  console.error(`No manifest entry found for: ${normFixture}`);
  console.error("Check the fixture path is correct and exists in .manifest.json.");
  process.exit(1);
}

const entry = manifest.fixtures[entryIndex];
const sourcePath = path.join(testBase, entry.source.replace(/\//g, path.sep));
const destPath = path.join(fixtureBase, normFixture.replace(/\//g, path.sep));

if (!fs.existsSync(sourcePath)) {
  console.error(`Source file does not exist: ${sourcePath}`);
  console.error("The source may have been moved or deleted (ORPHAN condition).");
  console.error("Update the manifest entry manually to reflect the new source location.");
  process.exit(1);
}

const sourceContent = fs.readFileSync(sourcePath);
const newHash = crypto.createHash("sha256").update(sourceContent).digest("hex").toUpperCase();

fs.mkdirSync(path.dirname(destPath), { recursive: true });
fs.writeFileSync(destPath, sourceContent);

manifest.fixtures[entryIndex].sourceHash = newHash;
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + "\n", "utf8");

console.log(`Synced  : ${normFixture}`);
console.log(`Source  : ${entry.source}`);
console.log(`Hash    : ${newHash}`);
if (entry.note) {
  console.log(`Note    : ${entry.note}`);
}
console.log("\nRun tests to confirm the unit tests still pass:");
console.log("  npx jest test/unit/fixture-integrity");
