import { existsSync } from "node:fs";
import { basename, dirname, join } from "node:path";
import { readFile } from "node:fs/promises";
//#region src/memory-host-sdk/consolidation-userid.ts
/**
* Resolve a feishu userId (ou_xxx) from a session file path.
*
* The session store maps sessionKey → { sessionId, ... }.
* Session keys for feishu follow the pattern:
*   agent:main:feishu:direct:ou_xxx
*   agent:main:feishu:group:oc_xxx:...:sender:ou_xxx
*
* This module loads sessions.json, finds the sessionKey for the file's
* sessionId, and extracts the userId.
*/
const storeCache = /* @__PURE__ */ new Map();
const CACHE_TTL_MS = 6e4;
/**
* Extract the bare sessionId from a session filename.
*
* Handles:
*   abc-123.jsonl                        → abc-123
*   abc-123.jsonl.reset.2026-04-02...    → abc-123
*   abc-123.jsonl.deleted.2026-04-02...  → abc-123
*/
function extractSessionIdFromFileName(fileName) {
	let name = fileName;
	const jsonlIdx = name.indexOf(".jsonl");
	if (jsonlIdx >= 0) name = name.slice(0, jsonlIdx);
	return name;
}
/**
* Extract a feishu userId (ou_xxx) from a session key.
*
* Pattern:
*   agent:main:feishu:direct:ou_xxx → ou_xxx
*   agent:main:feishu:group:oc_xxx:...:sender:ou_xxx → ou_xxx
*   agent:ou_xxx:rest → ou_xxx (fallback)
*/
function extractUserIdFromSessionKey(sessionKey) {
	const parts = sessionKey.split(":");
	const tail = parts[parts.length - 1];
	if (tail && tail !== "main" && tail.startsWith("ou_")) return tail;
	if (parts.length >= 3 && parts[1] && parts[1] !== "main") return parts[1];
	return null;
}
async function loadSessionStore(sessionsDir) {
	const cached = storeCache.get(sessionsDir);
	if (cached && Date.now() - cached.loadedAt < CACHE_TTL_MS) return cached.store;
	const storePath = join(sessionsDir, "sessions.json");
	if (!existsSync(storePath)) return {};
	try {
		const raw = await readFile(storePath, "utf-8");
		const parsed = JSON.parse(raw);
		if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
			const store = parsed;
			storeCache.set(sessionsDir, {
				store,
				loadedAt: Date.now()
			});
			return store;
		}
	} catch {}
	return {};
}
/**
* Resolve the feishu userId (ou_xxx) for a session file.
*
* @param filePath - Absolute path to a .jsonl session transcript file.
* @returns The userId string (e.g. "ou_xxx"), or null if it cannot be resolved.
*/
async function resolveUserIdForSessionFile(filePath) {
	const sessionsDir = dirname(filePath);
	const targetSessionId = extractSessionIdFromFileName(basename(filePath));
	if (!targetSessionId) return null;
	const store = await loadSessionStore(sessionsDir);
	for (const [sessionKey, entry] of Object.entries(store)) if (entry.sessionId === targetSessionId) return extractUserIdFromSessionKey(sessionKey);
	for (const [sessionKey, entry] of Object.entries(store)) {
		const entryFile = entry.sessionFile?.trim();
		if (!entryFile) continue;
		if (extractSessionIdFromFileName(basename(entryFile)) === targetSessionId) return extractUserIdFromSessionKey(sessionKey);
	}
	return null;
}
//#endregion
export { resolveUserIdForSessionFile };
