import assert from "node:assert/strict";
import { test } from "vitest";

import {
	checkJsonPolicy,
	hasValidSchemaVersion,
	isSfOwnedJsonContract,
} from "./check-versioned-json.mjs";

test("check-versioned-json: parses every JSON file", () => {
	const files = {
		"package.json": '{"version":"1.0.0"}',
		"src/resources/extensions/sf/learning/data/model-benchmarks.json": "{bad",
	};

	const result = checkJsonPolicy(Object.keys(files), (path) => files[path]);

	assert.equal(result.failures.length, 1);
	assert.match(
		result.failures[0],
		/^src\/resources\/extensions\/sf\/learning\/data\/model-benchmarks\.json: invalid JSON/,
	);
	assert.equal(result.filesParsed, 2);
});

test("check-versioned-json: skips deleted tracked files", () => {
	const result = checkJsonPolicy(["deleted.json", "package.json"], (path) => {
		if (path === "deleted.json") {
			const error = new Error("ENOENT");
			error.code = "ENOENT";
			throw error;
		}
		return '{"version":"1.0.0"}';
	});

	assert.deepEqual(result.failures, []);
	assert.equal(result.filesParsed, 1);
});

test("check-versioned-json: requires numeric schemaVersion for SF contracts", () => {
	const files = {
		"src/resources/extensions/sf/learning/data/unit-weights.json":
			'{"_meta":{"schemaVersion":1}}',
		"src/resources/extensions/sf/workflow-templates/registry.json":
			'{"schemaVersion":1,"templates":{}}',
		"src/resources/extensions/sf/learning/data/model-benchmarks.json":
			'{"_meta":{"version":"1"}}',
		"src/resources/extensions/sf/extension-manifest.json":
			'{"version":"1.0.0"}',
	};

	const result = checkJsonPolicy(Object.keys(files), (path) => files[path]);

	assert.deepEqual(result.failures, [
		"src/resources/extensions/sf/learning/data/model-benchmarks.json: missing numeric schemaVersion marker (top-level or _meta)",
	]);
	assert.equal(result.contractsChecked, 3);
});

test("check-versioned-json: treats extension version as component version", () => {
	assert.equal(
		isSfOwnedJsonContract(
			"src/resources/extensions/sf/extension-manifest.json",
		),
		false,
	);
	assert.equal(hasValidSchemaVersion({ version: "1.0.0" }), false);
	assert.equal(hasValidSchemaVersion({ schemaVersion: 1 }), true);
	assert.equal(hasValidSchemaVersion({ _meta: { schemaVersion: 1 } }), true);
});
