// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
// SPDX-FileCopyrightText: Petr Baudis <pasky@ucw.cz>
//
// SPDX-License-Identifier: MIT

import * as fs from "node:fs";
import * as path from "node:path";
import { getAgentDir } from "@earendil-works/pi-coding-agent";

export function getSessionsRoot(sessionFile: string | undefined): string | undefined {
	if (!sessionFile) return undefined;
	const normalized = sessionFile.replace(/\\/g, "/");
	const marker = "/sessions/";
	const idx = normalized.indexOf(marker);
	if (idx === -1) {
		return path.dirname(path.resolve(sessionFile));
	}
	return normalized.slice(0, idx + marker.length - 1);
}

export function getFallbackSessionsRoot(): string | undefined {
	const candidate = path.resolve(getAgentDir(), "sessions");
	return fs.existsSync(candidate) ? candidate : undefined;
}

export function normalizeSessionPath(sessionPath: string, sessionsRoot: string | undefined): string {
	if (path.isAbsolute(sessionPath)) return path.resolve(sessionPath);
	if (sessionsRoot) return path.resolve(sessionsRoot, sessionPath);
	return path.resolve(sessionPath);
}

export function sessionPathAllowed(candidate: string, sessionsRoot: string | undefined): boolean {
	if (!sessionsRoot) return false; // fail closed when root unknown
	const root = path.resolve(sessionsRoot);
	const resolved = path.resolve(candidate);
	return resolved === root || resolved.startsWith(`${root}${path.sep}`);
}
