"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.resolveOpenAICompatProxyEntrypointCandidates = exports.listOpenAICompatProxyProfileNames = exports.removeLegacyOpenAICompatProxySession = exports.removeOpenAICompatProxySession = exports.writeOpenAICompatProxySession = exports.readLegacyOpenAICompatProxySession = exports.readOpenAICompatProxySession = exports.removeLegacyOpenAICompatProxyPid = exports.removeOpenAICompatProxyPid = exports.writeOpenAICompatProxyPid = exports.getLegacyOpenAICompatProxyPid = exports.getOpenAICompatProxyPid = exports.removeOpenAICompatProxyAuthTokenFile = exports.writeOpenAICompatProxyAuthTokenFile = void 0;
const crypto = __importStar(require("crypto"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const proxy_daemon_paths_1 = require("./proxy-daemon-paths");
function ensureProxyDir() {
    const proxyDir = (0, proxy_daemon_paths_1.getOpenAICompatProxyDir)();
    fs.mkdirSync(proxyDir, { recursive: true, mode: 0o700 });
    fs.chmodSync(proxyDir, 0o700);
}
function encodeProfileFileKey(profileName) {
    return encodeURIComponent(profileName);
}
function writeOpenAICompatProxyAuthTokenFile(profileName, authToken) {
    ensureProxyDir();
    const tokenPath = path.join((0, proxy_daemon_paths_1.getOpenAICompatProxyDir)(), `.${encodeProfileFileKey(profileName)}.${crypto.randomBytes(8).toString('hex')}.token`);
    const fd = fs.openSync(tokenPath, 'wx', 0o600);
    try {
        fs.writeFileSync(fd, authToken, 'utf8');
    }
    finally {
        fs.closeSync(fd);
    }
    fs.chmodSync(tokenPath, 0o600);
    return tokenPath;
}
exports.writeOpenAICompatProxyAuthTokenFile = writeOpenAICompatProxyAuthTokenFile;
function removeOpenAICompatProxyAuthTokenFile(tokenPath) {
    try {
        fs.unlinkSync(tokenPath);
    }
    catch {
        // Best-effort cleanup.
    }
}
exports.removeOpenAICompatProxyAuthTokenFile = removeOpenAICompatProxyAuthTokenFile;
function readPid(pidPath) {
    try {
        const raw = fs.readFileSync(pidPath, 'utf8').trim();
        const pid = Number.parseInt(raw, 10);
        return Number.isInteger(pid) ? pid : null;
    }
    catch {
        return null;
    }
}
function getOpenAICompatProxyPid(profileName) {
    return readPid((0, proxy_daemon_paths_1.getOpenAICompatProxyPidPath)(profileName));
}
exports.getOpenAICompatProxyPid = getOpenAICompatProxyPid;
function getLegacyOpenAICompatProxyPid() {
    return readPid((0, proxy_daemon_paths_1.getLegacyOpenAICompatProxyPidPath)());
}
exports.getLegacyOpenAICompatProxyPid = getLegacyOpenAICompatProxyPid;
function writeOpenAICompatProxyPid(profileName, pid) {
    ensureProxyDir();
    fs.writeFileSync((0, proxy_daemon_paths_1.getOpenAICompatProxyPidPath)(profileName), String(pid), {
        encoding: 'utf8',
        mode: 0o600,
    });
    fs.chmodSync((0, proxy_daemon_paths_1.getOpenAICompatProxyPidPath)(profileName), 0o600);
}
exports.writeOpenAICompatProxyPid = writeOpenAICompatProxyPid;
function removeOpenAICompatProxyPid(profileName) {
    try {
        fs.unlinkSync((0, proxy_daemon_paths_1.getOpenAICompatProxyPidPath)(profileName));
    }
    catch {
        // Best-effort cleanup.
    }
}
exports.removeOpenAICompatProxyPid = removeOpenAICompatProxyPid;
function removeLegacyOpenAICompatProxyPid() {
    try {
        fs.unlinkSync((0, proxy_daemon_paths_1.getLegacyOpenAICompatProxyPidPath)());
    }
    catch {
        // Best-effort cleanup.
    }
}
exports.removeLegacyOpenAICompatProxyPid = removeLegacyOpenAICompatProxyPid;
function readSession(sessionPath) {
    try {
        return JSON.parse(fs.readFileSync(sessionPath, 'utf8'));
    }
    catch {
        return null;
    }
}
function readOpenAICompatProxySession(profileName) {
    return readSession((0, proxy_daemon_paths_1.getOpenAICompatProxySessionPath)(profileName));
}
exports.readOpenAICompatProxySession = readOpenAICompatProxySession;
function readLegacyOpenAICompatProxySession() {
    return readSession((0, proxy_daemon_paths_1.getLegacyOpenAICompatProxySessionPath)());
}
exports.readLegacyOpenAICompatProxySession = readLegacyOpenAICompatProxySession;
function writeOpenAICompatProxySession(session) {
    ensureProxyDir();
    const sessionPath = (0, proxy_daemon_paths_1.getOpenAICompatProxySessionPath)(session.profileName);
    fs.writeFileSync(sessionPath, JSON.stringify(session, null, 2) + '\n', {
        encoding: 'utf8',
        mode: 0o600,
    });
    fs.chmodSync(sessionPath, 0o600);
}
exports.writeOpenAICompatProxySession = writeOpenAICompatProxySession;
function removeOpenAICompatProxySession(profileName) {
    try {
        fs.unlinkSync((0, proxy_daemon_paths_1.getOpenAICompatProxySessionPath)(profileName));
    }
    catch {
        // Best-effort cleanup.
    }
}
exports.removeOpenAICompatProxySession = removeOpenAICompatProxySession;
function removeLegacyOpenAICompatProxySession() {
    try {
        fs.unlinkSync((0, proxy_daemon_paths_1.getLegacyOpenAICompatProxySessionPath)());
    }
    catch {
        // Best-effort cleanup.
    }
}
exports.removeLegacyOpenAICompatProxySession = removeLegacyOpenAICompatProxySession;
function decodeProfileKey(profileKey) {
    try {
        return [decodeURIComponent(profileKey)];
    }
    catch {
        return [];
    }
}
function listProfileNamesForSuffix(suffix, legacyName) {
    try {
        const entries = fs.readdirSync((0, proxy_daemon_paths_1.getOpenAICompatProxyDir)(), { withFileTypes: true });
        const profileKeys = new Set();
        for (const entry of entries) {
            if (!entry.isFile() || entry.name === legacyName || !entry.name.endsWith(suffix)) {
                continue;
            }
            const profileKey = entry.name.slice(0, -suffix.length);
            if (!profileKey) {
                continue;
            }
            profileKeys.add(profileKey);
        }
        return [...profileKeys].flatMap(decodeProfileKey);
    }
    catch {
        return [];
    }
}
function listOpenAICompatProxyProfileNames() {
    return [
        ...new Set([
            ...listProfileNamesForSuffix('.session.json', 'session.json'),
            ...listProfileNamesForSuffix('.daemon.pid', 'daemon.pid'),
        ]),
    ];
}
exports.listOpenAICompatProxyProfileNames = listOpenAICompatProxyProfileNames;
function resolveOpenAICompatProxyEntrypointCandidates() {
    const jsEntry = path.join(__dirname, 'proxy-daemon-entry.js');
    const tsEntry = path.join(__dirname, 'proxy-daemon-entry.ts');
    const isBunRuntime = process.execPath.toLowerCase().includes('bun');
    const runningFromDist = __filename.endsWith('.js');
    if (runningFromDist) {
        return [jsEntry];
    }
    return isBunRuntime ? [tsEntry, jsEntry] : [jsEntry];
}
exports.resolveOpenAICompatProxyEntrypointCandidates = resolveOpenAICompatProxyEntrypointCandidates;
//# sourceMappingURL=proxy-daemon-state.js.map