"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteEvalDenormByTraceOrSession = deleteEvalDenormByTraceOrSession;
exports.deleteEvalDenormByEvalResultIds = deleteEvalDenormByEvalResultIds;
const logger_1 = __importDefault(require("../../../logger"));
const clickhouseService_1 = require("../clickhouseService");
const types_1 = require("./types");
function escapeLiteral(value) {
    return value.replace(/'/g, "''");
}
/**
 * Mirror ClickHouse eval_results delete before trace/session re-insert (R1: CH-only denorm reads).
 */
async function deleteEvalDenormByTraceOrSession(scope) {
    let wherePrefix = '';
    if (scope.traceId) {
        const traceLit = escapeLiteral(scope.traceId);
        wherePrefix = `(trace_id = '${traceLit}' OR has(trace_ids, '${traceLit}'))`;
    }
    else if (scope.sessionId) {
        wherePrefix = `session_id = '${escapeLiteral(scope.sessionId)}'`;
    }
    else {
        return;
    }
    const errorClause = scope.errorsOnly ? ` AND error IS NOT NULL AND failure_reason = 2` : '';
    const whereClause = `${wherePrefix}${errorClause}`;
    try {
        await clickhouseService_1.clickHouseService.delete(types_1.EVAL_RESULTS_ANALYTICS_TABLE, whereClause);
        await clickhouseService_1.clickHouseService.delete(types_1.EVAL_RESULT_COMPONENTS_TABLE, whereClause);
    }
    catch (error) {
        logger_1.default.warn(`deleteEvalDenormByTraceOrSession failed: ${error}`);
    }
}
/** Delete denorm rows for specific eval_result ids (repair / re-insert). */
async function deleteEvalDenormByEvalResultIds(evalResultIds) {
    if (evalResultIds.length === 0) {
        return;
    }
    const list = evalResultIds.map((id) => `'${escapeLiteral(id)}'`).join(',');
    const whereClause = `eval_result_id IN (${list})`;
    try {
        await clickhouseService_1.clickHouseService.delete(types_1.EVAL_RESULTS_ANALYTICS_TABLE, whereClause);
        await clickhouseService_1.clickHouseService.delete(types_1.EVAL_RESULT_COMPONENTS_TABLE, whereClause);
    }
    catch (error) {
        logger_1.default.warn(`deleteEvalDenormByEvalResultIds failed: ${error}`);
    }
}
//# sourceMappingURL=deleteEvalDenorm.js.map