"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ensureCodexProfileResources = exports.SHARED_CODEX_RESOURCE_DIRS = void 0;
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const logging_1 = require("../services/logging");
const logger = (0, logging_1.createLogger)('codex-auth:resources');
exports.SHARED_CODEX_RESOURCE_DIRS = ['agents', 'skills'];
function ensureCodexProfileResources(profileDir, options = {}) {
    const sharedCodexHome = options.sharedCodexHome ?? path.join(os.homedir(), '.codex');
    fs.mkdirSync(profileDir, { recursive: true, mode: 0o700 });
    fs.mkdirSync(sharedCodexHome, { recursive: true, mode: 0o700 });
    for (const resourceName of exports.SHARED_CODEX_RESOURCE_DIRS) {
        ensureSharedResourceDir(profileDir, sharedCodexHome, resourceName);
    }
}
exports.ensureCodexProfileResources = ensureCodexProfileResources;
function ensureSharedResourceDir(profileDir, sharedCodexHome, resourceName) {
    const targetPath = path.join(sharedCodexHome, resourceName);
    const linkPath = path.join(profileDir, resourceName);
    fs.mkdirSync(targetPath, { recursive: true, mode: 0o700 });
    let existingStat = null;
    try {
        existingStat = fs.lstatSync(linkPath);
    }
    catch {
        // Missing resource path: create it below.
    }
    if (existingStat !== null) {
        if (existingStat.isSymbolicLink()) {
            const currentTarget = fs.readlinkSync(linkPath);
            if (currentTarget === targetPath) {
                return;
            }
            fs.unlinkSync(linkPath);
        }
        else if (existingStat.isDirectory()) {
            if (isDirectoryEmpty(linkPath)) {
                fs.rmSync(linkPath, { recursive: true, force: true });
            }
            else {
                copyMissingResourceEntries(targetPath, linkPath);
                return;
            }
        }
        else {
            process.stderr.write(`[!] codex-auth: preserving existing non-directory ${resourceName} at ${linkPath}\n`);
            return;
        }
    }
    try {
        fs.symlinkSync(targetPath, linkPath, 'dir');
        logger.stage('dispatch', 'codex.resource.symlink.created', 'Created shared resource symlink', {
            link: linkPath,
            target: targetPath,
            resource: resourceName,
        });
    }
    catch (err) {
        fs.mkdirSync(linkPath, { recursive: true, mode: 0o700 });
        copyMissingResourceEntries(targetPath, linkPath);
        process.stderr.write(`[!] codex-auth: symlink unavailable; copied shared ${resourceName} to ${linkPath}. ` +
            `Resource edits won't propagate automatically.\n`);
        logger.warn('codex-auth.resource-copy-fallback', 'Copied shared resource after symlink failure', {
            link: linkPath,
            target: targetPath,
            resource: resourceName,
            error: err instanceof Error ? err.message : String(err),
        });
    }
}
function isDirectoryEmpty(dirPath) {
    try {
        return fs.readdirSync(dirPath).length === 0;
    }
    catch {
        return false;
    }
}
function copyMissingResourceEntries(sourceDir, targetDir) {
    for (const entry of fs.readdirSync(sourceDir, { withFileTypes: true })) {
        const sourcePath = path.join(sourceDir, entry.name);
        const targetPath = path.join(targetDir, entry.name);
        if (fs.existsSync(targetPath)) {
            continue;
        }
        fs.cpSync(sourcePath, targetPath, {
            recursive: true,
            force: false,
            errorOnExist: false,
            preserveTimestamps: true,
        });
    }
}
//# sourceMappingURL=codex-profile-resources.js.map