/**
 * Smoke test for the memoryInjection section in headless-query
 * output (sf-mp723yl9-rcxoeh).
 *
 * Source-level regex checks: the snapshot type carries the memoryInjection
 * block; the query handler conditionally reads from runtime_counters via
 * getRuntimeCounter; the write side in memory-store.js increments
 * memory_inject_count and accumulates memory_inject_chars_total.
 *
 * A full integration test would require bootstrapping a project
 * DB with runtime_counters and rendering a real prompt — covered
 * by the manual dogfood in the commit message rather than here.
 */

import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { test } from "vitest";

const __dirname = dirname(fileURLToPath(import.meta.url));
const querySrc = readFileSync(
	join(__dirname, "..", "headless-query.ts"),
	"utf-8",
);
const memoryStoreSrc = readFileSync(
	join(__dirname, "..", "resources", "extensions", "sf", "memory-store.js"),
	"utf-8",
);

test("QuerySnapshot type declares memoryInjection section", () => {
	assert.match(querySrc, /memoryInjection\?:/);
	assert.match(querySrc, /total_chars:\s*number/);
	assert.match(querySrc, /count:\s*number/);
	assert.match(querySrc, /avg_chars:\s*number/);
	assert.match(querySrc, /estimated_total_tokens:\s*number/);
});

test("buildQuerySnapshot reads memory_inject counters", () => {
	assert.match(querySrc, /getRuntimeCounter\("memory_inject_chars_total"\)/);
	assert.match(querySrc, /getRuntimeCounter\("memory_inject_count"\)/);
});

test("buildQuerySnapshot omits memoryInjection when count is 0", () => {
	// The conditional spread `...(memoryInjection ? { memoryInjection } : {})`
	// keeps the section out of the snapshot entirely on a fresh project.
	assert.match(
		querySrc,
		/\.\.\.\(memoryInjection \? \{ memoryInjection \} : \{\}\)/,
	);
});

test("formatMemoriesForPrompt records memory injection telemetry", () => {
	assert.match(memoryStoreSrc, /recordMemoryPromptTelemetry/);
	assert.match(memoryStoreSrc, /memory_inject_chars_total/);
	assert.match(memoryStoreSrc, /memory_inject_count/);
	assert.match(memoryStoreSrc, /incrementRuntimeCounterBy/);
});

test("counter writes are best-effort and never block prompt formatting", () => {
	const section = memoryStoreSrc.split("memory_inject_chars_total")[1];
	assert.ok(section, "counter write section not found");
	assert.match(section, /catch/);
});
