import * as os from "node:os";
import * as path from "node:path";

function configuredPiAgentDir(): string | null {
	const value = process.env.PI_CODING_AGENT_DIR?.trim();
	return value ? path.resolve(value) : null;
}

export function getPiAgentDir(): string {
	return configuredPiAgentDir() ?? path.join(os.homedir(), ".pi", "agent");
}

export function getPiUserRoot(): string {
	const configured = configuredPiAgentDir();
	return configured ? path.dirname(configured) : os.homedir();
}

export function getUserAgentsDir(): string {
	const configured = configuredPiAgentDir();
	return configured ? path.join(path.dirname(configured), ".agents") : path.join(os.homedir(), ".agents");
}

export function expandUserHomePath(value: string): string {
	if (value === "~") return getPiUserRoot();
	if (value.startsWith("~/")) return path.join(getPiUserRoot(), value.slice(2));
	return value;
}
