"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.redteamReferenceTablesSchemaHint = exports.CLICKHOUSE_REDTEAM_STRATEGIES_TABLE = exports.CLICKHOUSE_REDTEAM_PLUGINS_TABLE = void 0;
exports.ensureRedteamPluginsAndStrategiesTables = ensureRedteamPluginsAndStrategiesTables;
const logger_1 = __importDefault(require("../../../../logger"));
const metadata_1 = require("../../../../redteam/constants/metadata");
const plugins_1 = require("../../../../redteam/constants/plugins");
const strategies_1 = require("../../../../redteam/constants/strategies");
const clickhouseService_1 = require("../../clickhouseService");
/** ClickHouse reference dimension table for red team plugins (Argus text-to-SQL). */
exports.CLICKHOUSE_REDTEAM_PLUGINS_TABLE = 'plugins';
/** ClickHouse reference dimension table for red team strategies (Argus text-to-SQL). */
exports.CLICKHOUSE_REDTEAM_STRATEGIES_TABLE = 'strategies';
const PLUGINS_DDL = `
CREATE TABLE IF NOT EXISTS ${exports.CLICKHOUSE_REDTEAM_PLUGINS_TABLE} (
  id String,
  name String,
  description String,
  category String
) ENGINE = MergeTree()
ORDER BY id
`;
const STRATEGIES_DDL = `
CREATE TABLE IF NOT EXISTS ${exports.CLICKHOUSE_REDTEAM_STRATEGIES_TABLE} (
  id String,
  name String,
  description String
) ENGINE = MergeTree()
ORDER BY id
`;
exports.redteamReferenceTablesSchemaHint = `
Reference tables:
- ${exports.CLICKHOUSE_REDTEAM_PLUGINS_TABLE}(id, name, description, category)
- ${exports.CLICKHOUSE_REDTEAM_STRATEGIES_TABLE}(id, name, description)

Join keys (from eval_results componentResults alias j):
- plugin_id: replaceRegexpOne(JSONExtractString(j, 'metadata', 'pluginId'), '^trusys:redteam:', '')
- strategy_id: coalesce(nullIf(JSONExtractString(j, 'metadata', 'strategyId'), ''), 'basic')

Matching guidance:
- PLuginId and StrategyId are PascalCase mostly.
- Plugin filter: p.id = '<value>' OR p.name = '<value>' OR p.name ILIKE '%<value>%'
- Strategy filter: s.id = '<value>' OR s.name = '<value>' OR s.name ILIKE '%<value>%'
`;
async function clickHouseTableExists(tableName) {
    const rows = await clickhouseService_1.clickHouseService.query(`SELECT count() AS c FROM system.tables WHERE database = currentDatabase() AND name = '${tableName}'`);
    const c = Number(rows[0]?.c ?? 0);
    return c > 0;
}
async function tableRowCount(tableName) {
    const rows = await clickhouseService_1.clickHouseService.query(`SELECT count() AS c FROM ${tableName}`);
    return Number(rows[0]?.c ?? 0);
}
function buildPluginSeedRows() {
    return plugins_1.ALL_PLUGINS.map((pluginId) => {
        const name = metadata_1.displayNameOverrides[pluginId] ?? String(pluginId);
        const description = metadata_1.subCategoryDescriptions[pluginId] ?? '';
        const category = metadata_1.categoryMapReverse[pluginId] ?? 'Uncategorized';
        return {
            id: String(pluginId),
            name: String(name),
            description: String(description),
            category: String(category),
        };
    });
}
function buildStrategySeedRows() {
    return strategies_1.ALL_STRATEGIES.map((strategyId) => {
        const name = metadata_1.displayNameOverrides[strategyId] ?? String(strategyId);
        const description = metadata_1.strategyDescriptions[strategyId] ??
            metadata_1.subCategoryDescriptions[strategyId] ??
            '';
        return {
            id: String(strategyId),
            name: String(name),
            description: String(description),
        };
    });
}
/**
 * Ensures ClickHouse dimension tables `plugins` and `strategies` exist and are seeded
 * from red team constants. Safe to call repeatedly: seeds only when a table is empty.
 */
async function ensureRedteamPluginsAndStrategiesTables() {
    const pluginsExist = await clickHouseTableExists(exports.CLICKHOUSE_REDTEAM_PLUGINS_TABLE);
    if (!pluginsExist) {
        await clickhouseService_1.clickHouseService.command(PLUGINS_DDL);
    }
    const pluginsCount = await tableRowCount(exports.CLICKHOUSE_REDTEAM_PLUGINS_TABLE);
    if (pluginsCount === 0) {
        const pluginRows = buildPluginSeedRows();
        if (pluginRows.length > 0) {
            await clickhouseService_1.clickHouseService.insert(exports.CLICKHOUSE_REDTEAM_PLUGINS_TABLE, pluginRows);
            logger_1.default.info(`Seeded ClickHouse ${exports.CLICKHOUSE_REDTEAM_PLUGINS_TABLE} with ${pluginRows.length} rows`);
        }
    }
    const strategiesExist = await clickHouseTableExists(exports.CLICKHOUSE_REDTEAM_STRATEGIES_TABLE);
    if (!strategiesExist) {
        await clickhouseService_1.clickHouseService.command(STRATEGIES_DDL);
    }
    const strategiesCount = await tableRowCount(exports.CLICKHOUSE_REDTEAM_STRATEGIES_TABLE);
    if (strategiesCount === 0) {
        const strategyRows = buildStrategySeedRows();
        if (strategyRows.length > 0) {
            await clickhouseService_1.clickHouseService.insert(exports.CLICKHOUSE_REDTEAM_STRATEGIES_TABLE, strategyRows);
            logger_1.default.info(`Seeded ClickHouse ${exports.CLICKHOUSE_REDTEAM_STRATEGIES_TABLE} with ${strategyRows.length} rows`);
        }
    }
}
//# sourceMappingURL=redteamReferenceTablesClickhouse.js.map