/**
 * Bootstrap + workflow MEDIUM-severity bug fix contract tests.
 *
 * Purpose: prevent regression on MEDIUM bugs in the bootstrap+workflow cluster.
 * Consumer: CI gate via `npx vitest run bootstrap-workflow-medium`.
 */

import {
	chmodSync,
	mkdirSync,
	mkdtempSync,
	rmSync,
	writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, test } from "vitest";

// ─── Helpers ───────────────────────────────────────────────────────────────

function makeTempDir(prefix) {
	return mkdtempSync(join(tmpdir(), prefix));
}

function cleanup(dir) {
	try {
		rmSync(dir, { recursive: true, force: true });
	} catch {}
}

// ─── Bug 1: workflow-logger audit divergence ───────────────────────────────

describe("workflow-logger audit divergence", () => {
	test("getAuditEmitFailureCount returns zero when no failures", async () => {
		const { getAuditEmitFailureCount, _resetLogs } = await import(
			"../workflow-logger.js"
		);
		_resetLogs();
		expect(getAuditEmitFailureCount()).toBe(0);
	});

	test("getAuditEmitFailureCount is exported for doctor/status consumption", async () => {
		const mod = await import("../workflow-logger.js");
		expect(typeof mod.getAuditEmitFailureCount).toBe("function");
	});
});

// ─── Bug 2: write-gate depth regex (stale — function removed) ──────────────

describe("write-gate depth regex", () => {
	test("extractDepthVerificationMilestoneId does not exist in current codebase", async () => {
		const mod = await import("../write-intercept.js");
		expect(mod.extractDepthVerificationMilestoneId).toBeUndefined();
	});
});

// ─── Bug 3: workflow-manifest snapshotState schema validation ───────────────

describe("workflow-manifest snapshotState schema validation", () => {
	test("parseStringArray rejects non-string array elements", async () => {
		// parseStringArray is private; test via toNumeric which is exported
		const { toNumeric } = await import("../workflow-manifest.js");
		expect(toNumeric("123")).toBe(123);
		expect(toNumeric("abc")).toBeNull();
		expect(toNumeric(null, 42)).toBe(42);
	});

	test("readManifest validates required array fields", async () => {
		const dir = makeTempDir("sf-manifest-");
		mkdirSync(join(dir, ".sf"), { recursive: true });
		// Write a manifest with missing arrays
		writeFileSync(
			join(dir, ".sf", "state-manifest.json"),
			JSON.stringify({ version: 1, milestones: "not-array" }),
		);

		const { readManifest } = await import("../workflow-manifest.js");
		expect(() => readManifest(dir)).toThrow(
			"missing or invalid required arrays",
		);
		cleanup(dir);
	});
});

// ─── Bug 4: notification-store appendNotification failure tracking ──────────

describe("notification-store appendNotification failure tracking", () => {
	test("tracks append failure when write is impossible", async () => {
		const {
			initNotificationStore,
			appendNotification,
			getAppendFailureCount,
			getLastAppendFailure,
			_resetNotificationStore,
		} = await import("../notification-store.js");

		_resetNotificationStore();
		const dir = makeTempDir("sf-notif-");
		mkdirSync(join(dir, ".sf"), { recursive: true });

		// Make the directory read-only so appendFileSync will fail
		initNotificationStore(dir);
		chmodSync(join(dir, ".sf"), 0o555);

		appendNotification("test message", "warn");

		expect(getAppendFailureCount()).toBe(1);
		expect(getLastAppendFailure()).not.toBeNull();
		expect(getLastAppendFailure().correlationId).toBeDefined();
		expect(getLastAppendFailure().error).toBeDefined();

		// Restore permissions for cleanup
		chmodSync(join(dir, ".sf"), 0o755);
		cleanup(dir);
		_resetNotificationStore();
	});

	test("getAppendFailureCount returns zero after reset", async () => {
		const {
			getAppendFailureCount,
			getLastAppendFailure,
			_resetNotificationStore,
		} = await import("../notification-store.js");
		_resetNotificationStore();
		expect(getAppendFailureCount()).toBe(0);
		expect(getLastAppendFailure()).toBeNull();
	});

	test("successful append does not increment failure count", async () => {
		const {
			initNotificationStore,
			appendNotification,
			getAppendFailureCount,
			_resetNotificationStore,
		} = await import("../notification-store.js");

		_resetNotificationStore();
		const dir = makeTempDir("sf-notif-");
		mkdirSync(join(dir, ".sf"), { recursive: true });

		initNotificationStore(dir);
		appendNotification("test message", "warn");

		expect(getAppendFailureCount()).toBe(0);

		cleanup(dir);
		_resetNotificationStore();
	});
});

// ─── Bug 5: system-context buildCarryForwardLines (stale — removed) ─────────

describe("system-context buildCarryForwardLines", () => {
	test("buildCarryForwardLines does not exist in current codebase", async () => {
		const mod = await import("../context-injector.js");
		expect(mod.buildCarryForwardLines).toBeUndefined();
	});

	test("injectContext skips missing files gracefully", async () => {
		const { injectContext } = await import("../context-injector.js");
		const dir = makeTempDir("sf-ctx-");
		// No DEFINITION.yaml exists — should throw for missing definition
		expect(() => injectContext(dir, "step1", "prompt")).toThrow();
		cleanup(dir);
	});
});
