"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GLOBAL_SETTINGS_FILENAME = void 0;
exports.getControlPlaneSettingsPath = getControlPlaneSettingsPath;
exports.normalizeUserEventHookDirectory = normalizeUserEventHookDirectory;
exports.loadControlPlaneGlobalSettings = loadControlPlaneGlobalSettings;
exports.writeControlPlaneGlobalSettings = writeControlPlaneGlobalSettings;
exports.createDefaultControlPlaneGlobalSettings = createDefaultControlPlaneGlobalSettings;
exports.getControlPlaneEvidenceRootPath = getControlPlaneEvidenceRootPath;
exports.getIssueLogRootPath = getIssueLogRootPath;
exports.getServiceLogPath = getServiceLogPath;
exports.resolveIssueLogDirectory = resolveIssueLogDirectory;
exports.resolveIssueLogPath = resolveIssueLogPath;
const node_fs_1 = require("node:fs");
const node_os_1 = __importDefault(require("node:os"));
const node_path_1 = __importDefault(require("node:path"));
const node_crypto_1 = require("node:crypto");
const zod_1 = require("zod");
const fs_errors_1 = require("./fs-errors");
const control_plane_home_1 = require("./control-plane-home");
exports.GLOBAL_SETTINGS_FILENAME = "settings.json";
const GLOBAL_SETTINGS_VERSION = 1;
const globalSettingsSchema = zod_1.z.object({
    version: zod_1.z.literal(GLOBAL_SETTINGS_VERSION),
    workerId: zod_1.z.string().min(1),
    evidenceRoot: zod_1.z.string().min(1).optional(),
    eventHooks: zod_1.z
        .object({
        userDirectory: zod_1.z
            .string()
            .min(1)
            .refine((value) => node_path_1.default.isAbsolute(value), {
            message: "eventHooks.userDirectory must be an absolute path.",
        })
            .optional(),
    })
        .strict()
        .optional(),
});
const settingsCache = new Map();
function getControlPlaneSettingsPath(homeDirectory = node_os_1.default.homedir()) {
    return node_path_1.default.join((0, control_plane_home_1.getControlPlaneHomePath)(homeDirectory), exports.GLOBAL_SETTINGS_FILENAME);
}
function normalizeUserEventHookDirectory(value, homeDirectory = node_os_1.default.homedir()) {
    const normalized = node_path_1.default.normalize(value);
    if (!node_path_1.default.isAbsolute(normalized)) {
        throw new Error("eventHooks.userDirectory must be an absolute path.");
    }
    const eventHooksRoot = node_path_1.default.join((0, control_plane_home_1.getControlPlaneHomePath)(homeDirectory), "event-hooks");
    const relativePath = node_path_1.default.relative(eventHooksRoot, normalized);
    if (relativePath === "" ||
        (!relativePath.startsWith("..") && !node_path_1.default.isAbsolute(relativePath))) {
        throw new Error("eventHooks.userDirectory must not be inside ~/.alpaca/event-hooks.");
    }
    return normalized;
}
function loadControlPlaneGlobalSettings(homeDirectory = node_os_1.default.homedir()) {
    const cached = settingsCache.get(homeDirectory);
    if (cached) {
        return cached;
    }
    const settingsPath = getControlPlaneSettingsPath(homeDirectory);
    try {
        const normalized = parseAndNormalizeSettings((0, node_fs_1.readFileSync)(settingsPath, "utf8"), homeDirectory);
        settingsCache.set(homeDirectory, normalized);
        return normalized;
    }
    catch (error) {
        if (!(0, fs_errors_1.isMissingFileError)(error)) {
            throw error;
        }
        const settings = createDefaultControlPlaneGlobalSettings();
        try {
            (0, node_fs_1.mkdirSync)(node_path_1.default.dirname(settingsPath), { recursive: true });
            (0, node_fs_1.writeFileSync)(settingsPath, `${JSON.stringify(settings, null, 2)}\n`, {
                encoding: "utf8",
                flag: "wx",
            });
        }
        catch (writeError) {
            if (!(0, fs_errors_1.isAlreadyExistsError)(writeError)) {
                throw writeError;
            }
            const normalized = parseAndNormalizeSettings((0, node_fs_1.readFileSync)(settingsPath, "utf8"), homeDirectory);
            settingsCache.set(homeDirectory, normalized);
            return normalized;
        }
        settingsCache.set(homeDirectory, settings);
        return settings;
    }
}
function writeControlPlaneGlobalSettings(settings, homeDirectory = node_os_1.default.homedir()) {
    const normalized = normalizeSettings(settings, homeDirectory);
    const settingsPath = getControlPlaneSettingsPath(homeDirectory);
    (0, node_fs_1.mkdirSync)(node_path_1.default.dirname(settingsPath), { recursive: true });
    (0, node_fs_1.writeFileSync)(settingsPath, `${JSON.stringify(normalized, null, 2)}\n`, "utf8");
    settingsCache.set(homeDirectory, normalized);
    return settingsPath;
}
function createDefaultControlPlaneGlobalSettings() {
    return {
        version: GLOBAL_SETTINGS_VERSION,
        workerId: (0, node_crypto_1.randomUUID)(),
    };
}
function getControlPlaneEvidenceRootPath(homeDirectory = node_os_1.default.homedir()) {
    const settings = loadControlPlaneGlobalSettings(homeDirectory);
    return settings.evidenceRoot
        ? resolveRelativeToControlPlaneHome(settings.evidenceRoot, homeDirectory)
        : (0, control_plane_home_1.getControlPlaneHomePath)(homeDirectory);
}
function getIssueLogRootPath(homeDirectory = node_os_1.default.homedir()) {
    return node_path_1.default.join(getControlPlaneEvidenceRootPath(homeDirectory), "logs");
}
function getServiceLogPath(homeDirectory = node_os_1.default.homedir()) {
    return node_path_1.default.join(getIssueLogRootPath(homeDirectory), "service.log");
}
function resolveIssueLogDirectory(trackedProjectStorageSegments, homeDirectory = node_os_1.default.homedir()) {
    return node_path_1.default.join(getIssueLogRootPath(homeDirectory), ...trackedProjectStorageSegments, "issues");
}
function resolveIssueLogPath(trackedProjectStorageSegments, issueId, homeDirectory = node_os_1.default.homedir()) {
    return node_path_1.default.join(resolveIssueLogDirectory(trackedProjectStorageSegments, homeDirectory), `${issueId}.log`);
}
function normalizeSettings(settings, homeDirectory) {
    return {
        version: settings.version,
        workerId: settings.workerId,
        ...(settings.evidenceRoot
            ? {
                evidenceRoot: resolveRelativeToControlPlaneHome(settings.evidenceRoot, homeDirectory),
            }
            : {}),
        ...(settings.eventHooks?.userDirectory
            ? {
                eventHooks: {
                    userDirectory: normalizeUserEventHookDirectory(settings.eventHooks.userDirectory, homeDirectory),
                },
            }
            : {}),
    };
}
function parseAndNormalizeSettings(text, homeDirectory) {
    const parsed = JSON.parse(text);
    return normalizeSettings(globalSettingsSchema.parse(parsed), homeDirectory);
}
function resolveRelativeToControlPlaneHome(value, homeDirectory) {
    return node_path_1.default.isAbsolute(value)
        ? value
        : node_path_1.default.resolve((0, control_plane_home_1.getControlPlaneHomePath)(homeDirectory), value);
}
