"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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.features = exports.isTest = exports.isProduction = exports.isDevelopment = exports.env = void 0;
exports.parseEnv = parseEnv;
exports.validateRequiredEnv = validateRequiredEnv;
exports.getSafeEnvForLogging = getSafeEnvForLogging;
const zod_1 = require("zod");
const dotenv = __importStar(require("dotenv"));
const path_1 = __importDefault(require("path"));
try {
    const envPath = path_1.default.resolve(process.cwd(), 'infra', '.env');
    dotenv.config({ path: envPath });
}
catch (error) {
}
const envSchema = zod_1.z.object({
    NODE_ENV: zod_1.z.enum(['development', 'production', 'test']).default('development'),
    PORT: zod_1.z.string().transform(Number).default('3001'),
    HOST: zod_1.z.string().default('127.0.0.1'),
    DATABASE_URL: zod_1.z.string().url().optional(),
    REDIS_URL: zod_1.z.string().url().optional(),
    JWT_SECRET: zod_1.z.preprocess((val) => (val === '' || val === undefined ? undefined : val), zod_1.z.string().min(32).optional()),
    JWT_ALG: zod_1.z.enum(['HS256', 'HS384', 'HS512']).default('HS256'),
    ENCRYPTION_KEY: zod_1.z.preprocess((val) => (val === '' || val === undefined ? undefined : val), zod_1.z.string().min(32).optional()),
    AUTH_MODE: zod_1.z.enum(['api_key', 'jwt', 'mixed']).default('api_key'),
    SENTINEL_STORE_PLAIN: zod_1.z.string().transform(val => val === 'true').default('true'),
    SENTINEL_MODE: zod_1.z.enum(['live', 'mock']).default('live'),
    SENTINEL_SHIELD_MODE: zod_1.z.enum(['enforce', 'monitor', 'off']).default('enforce'),
    LOG_LEVEL: zod_1.z.enum(['error', 'warn', 'info', 'debug']).default('info'),
    DEV_MODE: zod_1.z.string().transform(val => val === 'true').default('false'),
    DEVKIT_ENABLED: zod_1.z.string().transform(val => val === 'true').default('false'),
    ALLOW_LOCALHOST_ONLY: zod_1.z.string().transform(val => val === 'true').default('true'),
    GATEWAY_PERSISTENCE: zod_1.z.enum(['memory', 'file', 'postgres', 'auto']).default('auto'),
    AUTH_ENABLED: zod_1.z.preprocess((val) => (val === '' || val === undefined ? 'true' : val), zod_1.z.string().transform(val => val === 'true').default('true')),
    RATE_LIMIT_ENABLED: zod_1.z.preprocess((val) => (val === '' || val === undefined ? 'true' : val), zod_1.z.string().transform(val => val === 'true').default('true')),
    RATE_LIMIT_WINDOW_MS: zod_1.z.string().transform(Number).default('60000'),
    RATE_LIMIT_MAX: zod_1.z.string().transform(Number).default('60'),
    SENTINEL_ENABLED: zod_1.z.string().transform(val => val === 'true').default('true'),
    SHIELD_TOKEN_CAP: zod_1.z.string().transform(Number).optional(),
    RUN_MAX_TOKENS: zod_1.z.string().transform(Number).optional(),
    CORS_ENABLED: zod_1.z.string().transform(val => val === 'true').default('false'),
    CORS_ORIGIN: zod_1.z.string().default('*'),
    IDEMPOTENCY_ENABLED: zod_1.z.string().transform(val => val === 'true').default('false'),
    IDEMPOTENCY_TTL_SECONDS: zod_1.z.string().transform(Number).default('3600'),
    CACHE_ENABLED: zod_1.z.string().transform(val => val === 'true').default('false'),
    CACHE_TTL_SECONDS: zod_1.z.string().transform(Number).default('300'),
    METRICS_ENABLED: zod_1.z.string().transform(val => val === 'true').default('true'),
    METRICS_PORT: zod_1.z.string().transform(Number).default('9090'),
    METRICS_PATH: zod_1.z.string().default('/metrics'),
    LOG_FORMAT: zod_1.z.enum(['json', 'pretty']).default('json'),
    LOG_REQUESTS: zod_1.z.string().transform(val => val === 'true').default('false'),
    LOG_RESPONSES: zod_1.z.string().transform(val => val === 'true').default('false'),
    LOG_ENCRYPTION_ENABLED: zod_1.z.string().transform(val => val === 'true').default('false'),
    LOG_ENCRYPTION_KEY: zod_1.z.string().optional(),
}).superRefine((data, ctx) => {
    if (data.NODE_ENV === 'production' && data.GATEWAY_PERSISTENCE !== 'memory') {
        if (!data.DATABASE_URL) {
            ctx.addIssue({
                code: zod_1.z.ZodIssueCode.custom,
                path: ['DATABASE_URL'],
                message: 'DATABASE_URL is required in production (unless GATEWAY_PERSISTENCE=memory)'
            });
        }
        if (!data.ENCRYPTION_KEY) {
            ctx.addIssue({
                code: zod_1.z.ZodIssueCode.custom,
                path: ['ENCRYPTION_KEY'],
                message: 'ENCRYPTION_KEY is required in production (unless GATEWAY_PERSISTENCE=memory)'
            });
        }
    }
    if ((data.AUTH_MODE === 'jwt' || data.AUTH_MODE === 'mixed') && !data.JWT_SECRET) {
        ctx.addIssue({
            code: zod_1.z.ZodIssueCode.custom,
            path: ['JWT_SECRET'],
            message: `JWT_SECRET is required when AUTH_MODE is ${data.AUTH_MODE}`
        });
    }
});
function parseEnv() {
    try {
        const parsed = envSchema.parse(process.env);
        const result = {
            NODE_ENV: parsed.NODE_ENV,
            PORT: parsed.PORT,
            HOST: parsed.HOST,
            DATABASE_URL: parsed.DATABASE_URL,
            REDIS_URL: parsed.REDIS_URL,
            JWT_SECRET: parsed.JWT_SECRET,
            JWT_ALG: parsed.JWT_ALG,
            ENCRYPTION_KEY: parsed.ENCRYPTION_KEY,
            AUTH_MODE: parsed.AUTH_MODE,
            AUTH_ENABLED: parsed.AUTH_ENABLED,
            SENTINEL_STORE_PLAIN: parsed.SENTINEL_STORE_PLAIN,
            SENTINEL_MODE: parsed.SENTINEL_MODE,
            SENTINEL_SHIELD_MODE: parsed.SENTINEL_SHIELD_MODE,
            SENTINEL_ENABLED: parsed.SENTINEL_ENABLED,
            SHIELD_TOKEN_CAP: parsed.SHIELD_TOKEN_CAP,
            RUN_MAX_TOKENS: parsed.RUN_MAX_TOKENS,
            LOG_LEVEL: parsed.LOG_LEVEL,
            LOG_FORMAT: parsed.LOG_FORMAT,
            LOG_REQUESTS: parsed.LOG_REQUESTS,
            LOG_RESPONSES: parsed.LOG_RESPONSES,
            LOG_ENCRYPTION_ENABLED: parsed.LOG_ENCRYPTION_ENABLED,
            LOG_ENCRYPTION_KEY: parsed.LOG_ENCRYPTION_KEY,
            DEV_MODE: parsed.DEV_MODE,
            DEVKIT_ENABLED: parsed.DEVKIT_ENABLED,
            ALLOW_LOCALHOST_ONLY: parsed.ALLOW_LOCALHOST_ONLY,
            GATEWAY_PERSISTENCE: parsed.GATEWAY_PERSISTENCE,
            RATE_LIMIT_ENABLED: parsed.RATE_LIMIT_ENABLED,
            RATE_LIMIT_WINDOW_MS: parsed.RATE_LIMIT_WINDOW_MS,
            RATE_LIMIT_MAX: parsed.RATE_LIMIT_MAX,
            CORS_ENABLED: parsed.CORS_ENABLED,
            CORS_ORIGIN: parsed.CORS_ORIGIN,
            IDEMPOTENCY_ENABLED: parsed.IDEMPOTENCY_ENABLED,
            IDEMPOTENCY_TTL_SECONDS: parsed.IDEMPOTENCY_TTL_SECONDS,
            CACHE_ENABLED: parsed.CACHE_ENABLED,
            CACHE_TTL_SECONDS: parsed.CACHE_TTL_SECONDS,
            METRICS_ENABLED: parsed.METRICS_ENABLED,
            METRICS_PORT: parsed.METRICS_PORT,
            METRICS_PATH: parsed.METRICS_PATH,
        };
        return result;
    }
    catch (error) {
        if (error instanceof zod_1.z.ZodError) {
            console.error('❌ Environment validation failed:');
            error.errors.forEach(err => {
                console.error(`   ${err.path.join('.')}: ${err.message}`);
            });
            console.error(`\n📝 Please check infra/.env.example and create infra/.env`);
            process.exit(1);
        }
        throw error;
    }
}
exports.env = parseEnv();
exports.isDevelopment = exports.env.NODE_ENV === 'development';
exports.isProduction = exports.env.NODE_ENV === 'production';
exports.isTest = exports.env.NODE_ENV === 'test';
exports.features = {
    sentinel: {
        enabled: exports.env.SENTINEL_MODE === 'live',
        storePlain: exports.env.SENTINEL_STORE_PLAIN,
        shieldMode: exports.env.SENTINEL_SHIELD_MODE,
    },
    development: {
        devMode: exports.env.DEV_MODE,
        devkitEnabled: exports.env.DEVKIT_ENABLED,
        localhostOnly: exports.env.ALLOW_LOCALHOST_ONLY,
    },
    persistence: {
        mode: exports.env.GATEWAY_PERSISTENCE,
        isMemoryMode: exports.env.GATEWAY_PERSISTENCE === 'memory',
        isFileMode: exports.env.GATEWAY_PERSISTENCE === 'file',
        isPostgresMode: exports.env.GATEWAY_PERSISTENCE === 'postgres',
        isAutoMode: exports.env.GATEWAY_PERSISTENCE === 'auto',
    }
};
function validateRequiredEnv(required) {
    const missing = required.filter(key => !process.env[key]);
    if (missing.length > 0) {
        throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
    }
}
function getSafeEnvForLogging() {
    return {
        NODE_ENV: exports.env.NODE_ENV,
        PORT: exports.env.PORT,
        HOST: exports.env.HOST,
        GATEWAY_PERSISTENCE: exports.env.GATEWAY_PERSISTENCE,
        AUTH_ENABLED: exports.env.AUTH_ENABLED,
        AUTH_MODE: exports.env.AUTH_MODE,
        JWT_ALG: exports.env.JWT_ALG,
        RATE_LIMIT_ENABLED: exports.env.RATE_LIMIT_ENABLED,
        RATE_LIMIT_WINDOW_MS: exports.env.RATE_LIMIT_WINDOW_MS,
        RATE_LIMIT_MAX: exports.env.RATE_LIMIT_MAX,
        DATABASE_URL: exports.env.DATABASE_URL ? '***configured***' : '***missing***',
        REDIS_URL: exports.env.REDIS_URL ? '***configured***' : '***missing***',
        JWT_SECRET: exports.env.JWT_SECRET ? '***configured***' : '***missing***',
        SENTINEL_MODE: exports.env.SENTINEL_MODE,
        SENTINEL_SHIELD_MODE: exports.env.SENTINEL_SHIELD_MODE,
        LOG_LEVEL: exports.env.LOG_LEVEL,
        DEV_MODE: exports.env.DEV_MODE,
        DEVKIT_ENABLED: exports.env.DEVKIT_ENABLED,
    };
}
//# sourceMappingURL=env.js.map