import assert from "node:assert/strict";
import { describe, test } from "vitest";
import { parseStreamingJson } from "../json-parse.js";

describe("parseStreamingJson — XML parameter recovery (#3751)", () => {
	test("promotes XML parameters trapped inside valid JSON string values", () => {
		const malformed =
			'{"narrative":"text.</narrative>\\n<parameter name=\\"verification\\">all tests pass</parameter>\\n<parameter name=\\"verificationEvidence\\">[\\"npm test\\"]</parameter>","oneLiner":"done"}';

		const parsed = parseStreamingJson<Record<string, unknown>>(malformed);

		assert.equal(parsed.narrative, "text.");
		assert.equal(parsed.verification, "all tests pass");
		assert.deepEqual(parsed.verificationEvidence, ["npm test"]);
		assert.equal(parsed.oneLiner, "done");
	});
});

describe("parseStreamingJson — generic malformed tool argument recovery", () => {
	test("repairs complete JSON-ish objects with unquoted keys", () => {
		const parsed = parseStreamingJson<Record<string, unknown>>(
			"{title: 'Done', verificationPassed: true,}",
		);

		assert.equal(parsed.title, "Done");
		assert.equal(parsed.verificationPassed, true);
	});

	test("repairs full YAML-shaped object arguments", () => {
		const parsed = parseStreamingJson<Record<string, unknown>>(
			"title: Done\nverificationPassed: true\n",
		);

		assert.equal(parsed.title, "Done");
		assert.equal(parsed.verificationPassed, true);
	});

	test("does not repair incomplete streaming chunks into fabricated values", () => {
		const parsed = parseStreamingJson<Record<string, unknown>>('{"title":');

		assert.deepEqual(parsed, {});
	});
});
