import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, test } from "vitest";
import {
	emitModelAutoResolvedEvent,
	modelRoleForUnitType,
} from "../uok/model-route-evidence.js";

const tmpRoots = [];

afterEach(() => {
	for (const dir of tmpRoots.splice(0)) {
		rmSync(dir, { recursive: true, force: true });
	}
});

function makeProject() {
	const root = mkdtempSync(join(tmpdir(), "sf-model-route-evidence-"));
	tmpRoots.push(root);
	return root;
}

function readAuditEvents(project) {
	const path = join(project, ".sf", "audit", "events.jsonl");
	return readFileSync(path, "utf-8")
		.trim()
		.split("\n")
		.filter(Boolean)
		.map((line) => JSON.parse(line));
}

test("modelRoleForUnitType_when_validation_unit_returns_validator", () => {
	assert.equal(modelRoleForUnitType("validation-gate"), "validator");
	assert.equal(modelRoleForUnitType("run-verification"), "validator");
});

test("modelRoleForUnitType_when_review_unit_returns_reviewer", () => {
	assert.equal(modelRoleForUnitType("scrutiny-review"), "reviewer");
});

test("modelRoleForUnitType_when_regular_unit_returns_worker", () => {
	assert.equal(modelRoleForUnitType("execute-task"), "worker");
});

test("emitModelAutoResolvedEvent_records_auto_policy_and_resolved_route", () => {
	const project = makeProject();

	emitModelAutoResolvedEvent(project, {
		traceId: "trace-model-1",
		unitType: "execute-task",
		unitId: "M001/S01/T01",
		resolvedModel: {
			provider: "zai",
			id: "glm-5.1",
			api: "openai-chat",
			apiKey: "secret-key",
		},
		authMode: "apiKey",
		routingReason: "auto selector",
		routing: {
			tier: "heavy",
			modelDowngraded: false,
		},
		tokenUsage: 1234,
	});

	const [event] = readAuditEvents(project);
	assert.equal(event.schemaVersion, 1);
	assert.equal(event.category, "model-routing");
	assert.equal(event.type, "model-auto-resolved");
	assert.equal(event.traceId, "trace-model-1");
	assert.equal(event.turnId, "M001/S01/T01");
	assert.equal(event.payload.role, "worker");
	assert.deepEqual(event.payload.requestedPolicy, {
		mode: "auto",
		constraints: [],
	});
	assert.equal(event.payload.resolvedProvider, "zai");
	assert.equal(event.payload.resolvedModel, "glm-5.1");
	assert.equal(event.payload.authMode, "apiKey");
	assert.deepEqual(event.payload.routeSnapshot.requestedPolicy, {
		mode: "auto",
		constraints: [],
	});
	assert.equal(event.payload.routeSnapshot.route.provider, "zai");
	assert.equal(event.payload.routeSnapshot.route.model, "glm-5.1");
	assert.equal(event.payload.routeSnapshot.route.byok, true);
	assert.equal(event.payload.routeSnapshot.route.apiKey, undefined);
	assert.equal(event.payload.routingReason, "auto selector");
	assert.equal(event.payload.tokenUsage, 1234);
});
