// 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 os from "node:os";
import * as path from "node:path";

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 configuredDir = process.env.PI_CODING_AGENT_DIR;
	const candidate = configuredDir
		? path.resolve(configuredDir, "sessions")
		: path.resolve(os.homedir(), ".pi", "agent", "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}`);
}
