import path from "node:path";
const SCOPE = "remote:project-binding";
export class RemoteProjectBinding {
    state;
    config;
    constructor(state, config) {
        this.state = state;
        this.config = config;
    }
    current(chatId) {
        const stored = this.state.getUiState(SCOPE, chatId);
        if (stored && this.isAllowed(stored))
            return path.resolve(stored);
        return path.resolve(this.config.defaultProjectPath);
    }
    bind(chatId, requestedPath) {
        const resolved = path.resolve(requestedPath);
        if (!this.isAllowed(resolved)) {
            throw new Error(`project path is outside allowed roots: ${resolved}`);
        }
        this.state.setUiState(SCOPE, chatId, resolved);
        return resolved;
    }
    isAllowed(projectPath) {
        const resolved = path.resolve(projectPath);
        const roots = this.allowedRoots();
        return roots.some((root) => isInside(root, resolved));
    }
    allowedRoots() {
        const configured = this.config.allowedRoots.length
            ? this.config.allowedRoots
            : [this.config.defaultProjectPath];
        return configured.map((root) => path.resolve(root));
    }
}
function isInside(root, candidate) {
    const relative = path.relative(path.resolve(root), path.resolve(candidate));
    return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
}
