"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isCurrentSlotActive = isCurrentSlotActive;
exports.parseDeployRole = parseDeployRole;
exports.parseDeploySlot = parseDeploySlot;
exports.parsePublicSurface = parsePublicSurface;
exports.resolveDeployRole = resolveDeployRole;
exports.resolveDeploySlot = resolveDeploySlot;
exports.resolvePublicSurface = resolvePublicSurface;
exports.resolveEnvironmentName = resolveEnvironmentName;
exports.isBackgroundWorkEnabled = isBackgroundWorkEnabled;
exports.resolveSeoIndexingMode = resolveSeoIndexingMode;
exports.resolveWebOrigin = resolveWebOrigin;
exports.resolveApiOrigin = resolveApiOrigin;
exports.resolveRealtimeOrigin = resolveRealtimeOrigin;
exports.resolveAiOrigin = resolveAiOrigin;
exports.resolveStructuredLogFields = resolveStructuredLogFields;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const DEPLOY_ROLE_VALUES = new Set(['prod', 'preview']);
const DEPLOY_SLOT_VALUES = new Set(['blue', 'green']);
const PUBLIC_SURFACE_VALUES = new Set(['prod', 'preview', 'blue', 'green']);
let cachedClientMeta = null;
function resolveMetaPath() {
    const candidates = Array.from(new Set([
        path_1.default.resolve(process.cwd(), 'config', 'client-meta.json'),
        path_1.default.resolve(process.cwd(), '..', 'config', 'client-meta.json'),
        path_1.default.resolve(process.cwd(), '..', '..', 'config', 'client-meta.json'),
        path_1.default.resolve(process.cwd(), '..', '..', '..', 'config', 'client-meta.json'),
        path_1.default.resolve(__dirname, '../../..', 'config', 'client-meta.json'),
        path_1.default.resolve(__dirname, '../../../..', 'config', 'client-meta.json'),
    ]));
    for (const candidate of candidates) {
        if (fs_1.default.existsSync(candidate)) {
            return candidate;
        }
    }
    throw new Error(`missing_client_meta_json:${candidates.join('|')}`);
}
function loadReleaseMeta() {
    if (!cachedClientMeta) {
        const raw = fs_1.default.readFileSync(resolveMetaPath(), 'utf8');
        const parsed = JSON.parse(raw);
        const version = typeof parsed.version === 'string' ? parsed.version.trim() : '';
        const build = Number(parsed.build);
        if (!/^\d+\.\d+\.\d+$/.test(version) || !Number.isInteger(build) || build < 1) {
            throw new Error('invalid_client_meta_for_deploy_helpers');
        }
        cachedClientMeta = { version, build };
    }
    return cachedClientMeta;
}
function normalizeValue(value) {
    if (typeof value !== 'string') {
        return null;
    }
    const normalized = value.trim().toLowerCase();
    return normalized.length > 0 ? normalized : null;
}
function normalizeOrigin(value) {
    return value.trim().replace(/\/+$/, '');
}
function buildDefaultOrigin(params) {
    const { servicePrefix, surface, websocket = false } = params;
    const protocol = websocket ? 'wss' : 'https';
    const host = surface === 'prod'
        ? servicePrefix ? `${servicePrefix}.playdrop.ai` : 'www.playdrop.ai'
        : servicePrefix
            ? `${servicePrefix}.${surface}.playdrop.ai`
            : `${surface}.playdrop.ai`;
    return `${protocol}://${host}`;
}
function parseBoolean(value) {
    const normalized = normalizeValue(value);
    if (!normalized) {
        return null;
    }
    if (normalized === '1' || normalized === 'true' || normalized === 'yes' || normalized === 'on') {
        return true;
    }
    if (normalized === '0' || normalized === 'false' || normalized === 'no' || normalized === 'off') {
        return false;
    }
    return null;
}
function resolveSlotStatePath(env = process.env) {
    const raw = typeof env['PLAYDROP_SLOT_STATE_PATH'] === 'string' ? env['PLAYDROP_SLOT_STATE_PATH'].trim() : '';
    return raw.length > 0 ? raw : null;
}
function readActiveSlotFromStateFile(env = process.env) {
    const slotStatePath = resolveSlotStatePath(env);
    if (!slotStatePath) {
        return null;
    }
    try {
        const raw = fs_1.default.readFileSync(slotStatePath, 'utf8');
        const parsed = JSON.parse(raw);
        return parseDeploySlot(parsed?.activeSlot);
    }
    catch {
        return null;
    }
}
function isCurrentSlotActive(env = process.env) {
    const slot = resolveDeploySlot(env);
    const activeSlot = readActiveSlotFromStateFile(env);
    if (!slot || !activeSlot) {
        return null;
    }
    return slot === activeSlot;
}
function parseDeployRole(value) {
    const normalized = normalizeValue(value);
    if (!normalized || !DEPLOY_ROLE_VALUES.has(normalized)) {
        return null;
    }
    return normalized;
}
function parseDeploySlot(value) {
    const normalized = normalizeValue(value);
    if (!normalized || !DEPLOY_SLOT_VALUES.has(normalized)) {
        return null;
    }
    return normalized;
}
function parsePublicSurface(value) {
    const normalized = normalizeValue(value);
    if (!normalized || !PUBLIC_SURFACE_VALUES.has(normalized)) {
        return null;
    }
    return normalized;
}
function resolveDeployRole(env = process.env) {
    return parseDeployRole(env['PLAYDROP_DEPLOY_ROLE'])
        ?? (env['NODE_ENV'] === 'production' ? 'prod' : 'preview');
}
function resolveDeploySlot(env = process.env) {
    return parseDeploySlot(env['PLAYDROP_SLOT']);
}
function resolvePublicSurface(env = process.env) {
    const explicit = parsePublicSurface(env['PLAYDROP_PUBLIC_SURFACE']);
    if (explicit) {
        return explicit;
    }
    const role = resolveDeployRole(env);
    if (role === 'preview') {
        return 'preview';
    }
    return 'prod';
}
function resolveEnvironmentName(env = process.env) {
    const explicit = typeof env['PLAYDROP_ENVIRONMENT'] === 'string' ? env['PLAYDROP_ENVIRONMENT'].trim() : '';
    if (explicit.length > 0) {
        return explicit;
    }
    const nodeEnv = typeof env['NODE_ENV'] === 'string' ? env['NODE_ENV'].trim() : '';
    return nodeEnv.length > 0 ? nodeEnv : 'development';
}
function isBackgroundWorkEnabled(env = process.env) {
    const explicit = parseBoolean(env['PLAYDROP_BACKGROUND_WORKERS_ENABLED']);
    if (explicit !== null) {
        return explicit;
    }
    const currentSlotActive = isCurrentSlotActive(env);
    if (currentSlotActive !== null) {
        return currentSlotActive;
    }
    return resolveDeployRole(env) === 'prod';
}
function resolveSeoIndexingMode(env = process.env) {
    const explicit = normalizeValue(env['PLAYDROP_SEO_INDEXING']);
    if (explicit === 'public') {
        return 'public';
    }
    if (explicit === 'private') {
        return 'private';
    }
    if (explicit === 'noindex') {
        return 'noindex';
    }
    return resolveDeployRole(env) === 'prod' ? 'public' : 'noindex';
}
function resolveWebOrigin(env = process.env) {
    const explicit = typeof env['PLAYDROP_PUBLIC_ORIGIN'] === 'string' ? env['PLAYDROP_PUBLIC_ORIGIN'].trim() : '';
    if (explicit.length > 0) {
        return normalizeOrigin(explicit);
    }
    const legacy = typeof env['PLAYDROP_WEB_BASE_URL'] === 'string' ? env['PLAYDROP_WEB_BASE_URL'].trim() : '';
    if (legacy.length > 0) {
        return normalizeOrigin(legacy);
    }
    return buildDefaultOrigin({ surface: resolvePublicSurface(env) });
}
function resolveApiOrigin(env = process.env) {
    const explicit = typeof env['PLAYDROP_API_BASE_URL'] === 'string' ? env['PLAYDROP_API_BASE_URL'].trim() : '';
    if (explicit.length > 0) {
        return normalizeOrigin(explicit);
    }
    return buildDefaultOrigin({ servicePrefix: 'api', surface: resolvePublicSurface(env) });
}
function resolveRealtimeOrigin(env = process.env) {
    const explicit = typeof env['PLAYDROP_REALTIME_BASE_URL'] === 'string' ? env['PLAYDROP_REALTIME_BASE_URL'].trim() : '';
    if (explicit.length > 0) {
        return normalizeOrigin(explicit);
    }
    return buildDefaultOrigin({ servicePrefix: 'play', surface: resolvePublicSurface(env), websocket: true });
}
function resolveAiOrigin(env = process.env) {
    const explicit = typeof env['PLAYDROP_AI_BASE_URL'] === 'string' ? env['PLAYDROP_AI_BASE_URL'].trim() : '';
    if (explicit.length > 0) {
        return normalizeOrigin(explicit);
    }
    return buildDefaultOrigin({ servicePrefix: 'ai', surface: resolvePublicSurface(env) });
}
function resolveStructuredLogFields(service, env = process.env) {
    const slot = resolveDeploySlot(env);
    const release = loadReleaseMeta();
    return {
        environment: resolveEnvironmentName(env),
        slot: slot ?? 'none',
        service,
        release_version: release.version,
        build_number: release.build,
        deploy_role: resolveDeployRole(env),
        public_surface: resolvePublicSurface(env),
    };
}
