/**
 * Knowledge compounding — distills high-confidence judgment-log entries from a
 * milestone window into the DB memories table after milestone close.
 *
 * Called by postUnitPostVerification after complete-milestone, alongside
 * scaffold-keeper and record-promoter. Failure is always non-fatal.
 *
 * Strategy:
 *   - Read judgment-log.jsonl entries with confidence=high for the given milestone
 *   - Deduplicate against existing memories rows (content match, DB-first)
 *   - Insert new entries into the memories table with a numeric confidence score
 */
import { randomUUID } from "node:crypto";
import { readJudgmentLog } from "./judgment-log.js";
import { getActiveMemories, insertMemoryRow, isDbAvailable } from "./sf-db.js";

/** Map judgment-log string confidence to a numeric score for the REAL column. */
function confidenceScore(s) {
	if (s === "high") return 0.9;
	if (s === "medium") return 0.6;
	return 0.3;
}

/**
 * Compound high-confidence judgment-log entries into the DB memories table.
 *
 * Purpose: persist reusable lessons from a milestone into the knowledge base so
 * future agents benefit from them via system-context injection.
 *
 * @param basePath - project root (cwd)
 * @param milestoneId - milestone just completed (e.g. "M001")
 */
export function compoundLearningsIntoKnowledge(basePath, milestoneId) {
	// Read high-confidence entries for this milestone
	const entries = readJudgmentLog(basePath, milestoneId).filter(
		(e) => e.confidence === "high",
	);
	if (entries.length === 0) return { added: 0, skipped: 0 };

	// Dedup against existing DB memories (content-exact match)
	const existingContent = new Set();
	if (isDbAvailable()) {
		for (const m of getActiveMemories({ category: "knowledge" })) {
			existingContent.add(m.content);
		}
	}

	let added = 0;
	let skipped = 0;

	if (!isDbAvailable()) return { added: 0, skipped: entries.length };

	const now = new Date().toISOString();
	for (const entry of entries) {
		const content = `[${milestoneId}] ${entry.decision}: ${entry.reasoning}`;
		if (existingContent.has(content)) {
			skipped++;
			continue;
		}
		try {
			insertMemoryRow({
				id: `K-${randomUUID()}`,
				category: "knowledge",
				content,
				confidence: confidenceScore(entry.confidence),
				sourceUnitType: "complete-milestone",
				sourceUnitId: milestoneId,
				createdAt: now,
				updatedAt: now,
				tags: ["judgment-log", milestoneId],
			});
			added++;
		} catch {
			// non-fatal
		}
	}
	return { added, skipped };
}
