"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DEV_BACKFILL_DEFAULT_SINCE_DAYS = void 0;
exports.isDevelopmentEnvironment = isDevelopmentEnvironment;
exports.resolveEvalDenormBackfillScope = resolveEvalDenormBackfillScope;
exports.scopeCreatedAfterIso = scopeCreatedAfterIso;
exports.scopeCreatedBeforeIso = scopeCreatedBeforeIso;
exports.buildCreatedAtFilterSql = buildCreatedAtFilterSql;
exports.buildClickhouseCreatedAtFilterSql = buildClickhouseCreatedAtFilterSql;
/** Default lookback when backfilling in local/development (frequent re-runs). */
exports.DEV_BACKFILL_DEFAULT_SINCE_DAYS = 90;
function parsePositiveInt(value) {
    if (!value?.trim()) {
        return undefined;
    }
    const n = Number.parseInt(value, 10);
    if (!Number.isFinite(n) || n < 1) {
        return undefined;
    }
    return n;
}
function isTruthyEnv(value) {
    const v = value?.trim().toLowerCase();
    return v === '1' || v === 'true' || v === 'yes';
}
/**
 * Local/development: NODE_ENV, TRUSYS_ENV, or APP_ENV.
 * Production/staging are not treated as development unless NODE_ENV=development.
 */
function isDevelopmentEnvironment() {
    const candidates = [
        process.env.NODE_ENV,
        process.env.CLIENT_ENV,
        process.env.TRUSYS_ENV,
        process.env.APP_ENV,
        process.env.ENVIRONMENT,
    ]
        .map((v) => v?.trim().toLowerCase())
        .filter(Boolean);
    return candidates.some((v) => v === 'development' || v === 'dev' || v === 'local');
}
/**
 * Resolves how much eval_results history to backfill.
 *
 * Precedence: explicit options → env → development default (90d) → full history.
 *
 * Env:
 * - EVAL_BACKFILL_ALL_HISTORY=1 — no date filter
 * - EVAL_BACKFILL_SINCE_DAYS=N — last N days (any environment)
 * - EVAL_BACKFILL_DEV_SINCE_DAYS=N — dev default override (default 90)
 */
function resolveEvalDenormBackfillScope(options) {
    const createdBefore = parseScopeDate(options?.createdBefore);
    if (options?.allHistory || isTruthyEnv(process.env.EVAL_BACKFILL_ALL_HISTORY)) {
        return {
            createdAfter: null,
            createdBefore,
            sinceDays: null,
            allHistory: true,
            reason: createdBefore
                ? 'all history with createdBefore cutoff'
                : 'all history (explicit)',
        };
    }
    if (options?.createdAfter) {
        const d = options.createdAfter instanceof Date ? options.createdAfter : new Date(options.createdAfter);
        if (!Number.isNaN(d.getTime())) {
            return {
                createdAfter: d,
                createdBefore,
                sinceDays: null,
                allHistory: false,
                reason: createdBefore ? 'createdAfter + createdBefore' : 'createdAfter option',
            };
        }
    }
    const sinceDays = options?.sinceDays ??
        parsePositiveInt(process.env.EVAL_BACKFILL_SINCE_DAYS) ??
        (isDevelopmentEnvironment()
            ? (parsePositiveInt(process.env.EVAL_BACKFILL_DEV_SINCE_DAYS) ?? exports.DEV_BACKFILL_DEFAULT_SINCE_DAYS)
            : undefined);
    if (sinceDays === undefined) {
        return {
            createdAfter: null,
            createdBefore,
            sinceDays: null,
            allHistory: true,
            reason: createdBefore
                ? 'all history with createdBefore cutoff'
                : 'all history (non-development default)',
        };
    }
    const createdAfter = new Date();
    createdAfter.setUTCDate(createdAfter.getUTCDate() - sinceDays);
    return {
        createdAfter,
        createdBefore,
        sinceDays,
        allHistory: false,
        reason: createdBefore
            ? `last ${sinceDays} days with createdBefore cutoff`
            : isDevelopmentEnvironment()
                ? `development: last ${sinceDays} days`
                : `last ${sinceDays} days (EVAL_BACKFILL_SINCE_DAYS)`,
    };
}
function parseScopeDate(value) {
    if (!value) {
        return null;
    }
    const d = value instanceof Date ? value : new Date(value);
    return Number.isNaN(d.getTime()) ? null : d;
}
function scopeCreatedAfterIso(scope) {
    return scope.createdAfter?.toISOString() ?? null;
}
function scopeCreatedBeforeIso(scope) {
    return scope.createdBefore?.toISOString() ?? null;
}
function buildCreatedAtFilterSql(scope) {
    const parts = [];
    if (scope.createdAfter) {
        const iso = scope.createdAfter.toISOString().replace(/'/g, "''");
        parts.push(`"created_at" >= '${iso}'::timestamptz`);
    }
    if (scope.createdBefore) {
        const iso = scope.createdBefore.toISOString().replace(/'/g, "''");
        parts.push(`"created_at" < '${iso}'::timestamptz`);
    }
    return parts.join(' AND ');
}
/** ClickHouse eval_results.created_at filter (DateTime). */
function buildClickhouseCreatedAtFilterSql(scope) {
    const parts = [];
    if (scope.createdAfter) {
        const formatted = scope.createdAfter.toISOString().slice(0, 19).replace('T', ' ');
        parts.push(`created_at >= toDateTime('${formatted}')`);
    }
    if (scope.createdBefore) {
        const formatted = scope.createdBefore.toISOString().slice(0, 19).replace('T', ' ');
        parts.push(`created_at < toDateTime('${formatted}')`);
    }
    return parts.join(' AND ');
}
//# sourceMappingURL=backfillScope.js.map