"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CLICKHOUSE_GUARDRAIL_ACTIONS_TABLE = exports.CLICKHOUSE_GUARDRAIL_VALIDATOR_CATEGORIES_TABLE = exports.CLICKHOUSE_GUARDRAIL_VALIDATORS_TABLE = void 0;
exports.ensureGuardrailReferenceTables = ensureGuardrailReferenceTables;
exports.syncGuardrailReferenceTablesFromSeed = syncGuardrailReferenceTablesFromSeed;
exports.buildGuardrailReferenceTablesSchemaHint = buildGuardrailReferenceTablesSchemaHint;
const guardRailActions_json_1 = __importDefault(require("../../../../guardrails/guardRailActions.json"));
const validatorCategories_json_1 = __importDefault(require("../../../../guardrails/validatorCategories.json"));
const validators_json_1 = __importDefault(require("../../../../guardrails/validators.json"));
const logger_1 = __importDefault(require("../../../../logger"));
const clickhouseService_1 = require("../../clickhouseService");
/** ClickHouse reference: functional guardrail validator catalog (Argus text-to-SQL). */
exports.CLICKHOUSE_GUARDRAIL_VALIDATORS_TABLE = 'guardrail_validators';
/** ClickHouse reference: validator / harm taxonomy categories. */
exports.CLICKHOUSE_GUARDRAIL_VALIDATOR_CATEGORIES_TABLE = 'guardrail_validator_categories';
/** ClickHouse reference: guardrail actions (mask, fail, …) and allowed validators. */
exports.CLICKHOUSE_GUARDRAIL_ACTIONS_TABLE = 'guardrail_actions';
const VALIDATORS_DDL = `
CREATE TABLE IF NOT EXISTS ${exports.CLICKHOUSE_GUARDRAIL_VALIDATORS_TABLE} (
  id String,
  name String,
  description String,
  input UInt8,
  output UInt8
) ENGINE = MergeTree()
ORDER BY id
`;
const CATEGORIES_DDL = `
CREATE TABLE IF NOT EXISTS ${exports.CLICKHOUSE_GUARDRAIL_VALIDATOR_CATEGORIES_TABLE} (
  id String,
  name String,
  description String
) ENGINE = MergeTree()
ORDER BY id
`;
const ACTIONS_DDL = `
CREATE TABLE IF NOT EXISTS ${exports.CLICKHOUSE_GUARDRAIL_ACTIONS_TABLE} (
  id String,
  name String,
  description String,
  validators_json String
) ENGINE = MergeTree()
ORDER BY id
`;
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 buildValidatorRows() {
    const list = Array.isArray(validators_json_1.default.validators)
        ? validators_json_1.default.validators
        : [];
    return list.map((v) => ({
        id: String(v.id),
        name: String(v.name ?? ''),
        description: String(v.description ?? ''),
        input: v.input ? 1 : 0,
        output: v.output ? 1 : 0,
    }));
}
function buildCategoryRows() {
    const list = Array.isArray(validatorCategories_json_1.default.categories)
        ? validatorCategories_json_1.default.categories
        : [];
    return list.map((c) => ({
        id: String(c.id),
        name: String(c.name ?? ''),
        description: String(c.description ?? ''),
    }));
}
function buildActionRows() {
    const list = Array.isArray(guardRailActions_json_1.default) ? guardRailActions_json_1.default : [];
    return list.map((a) => ({
        id: String(a.id),
        name: String(a.name ?? ''),
        description: String(a.description ?? ''),
        validators_json: JSON.stringify(Array.isArray(a.validators) ? a.validators : []),
    }));
}
async function ensureTablesCreated() {
    if (!(await clickHouseTableExists(exports.CLICKHOUSE_GUARDRAIL_VALIDATORS_TABLE))) {
        await clickhouseService_1.clickHouseService.command(VALIDATORS_DDL);
    }
    if (!(await clickHouseTableExists(exports.CLICKHOUSE_GUARDRAIL_VALIDATOR_CATEGORIES_TABLE))) {
        await clickhouseService_1.clickHouseService.command(CATEGORIES_DDL);
    }
    if (!(await clickHouseTableExists(exports.CLICKHOUSE_GUARDRAIL_ACTIONS_TABLE))) {
        await clickhouseService_1.clickHouseService.command(ACTIONS_DDL);
    }
}
/**
 * Ensures guardrail catalog tables exist and are seeded from repo JSON when empty.
 * Safe to call repeatedly (same pattern as red team plugins/strategies).
 */
async function ensureGuardrailReferenceTables() {
    await ensureTablesCreated();
    const validatorsCount = await tableRowCount(exports.CLICKHOUSE_GUARDRAIL_VALIDATORS_TABLE);
    if (validatorsCount > 0) {
        return;
    }
    const vRows = buildValidatorRows();
    const cRows = buildCategoryRows();
    const aRows = buildActionRows();
    if (vRows.length > 0) {
        await clickhouseService_1.clickHouseService.insert(exports.CLICKHOUSE_GUARDRAIL_VALIDATORS_TABLE, vRows);
        logger_1.default.info(`Seeded ClickHouse ${exports.CLICKHOUSE_GUARDRAIL_VALIDATORS_TABLE} with ${vRows.length} rows`);
    }
    if (cRows.length > 0) {
        await clickhouseService_1.clickHouseService.insert(exports.CLICKHOUSE_GUARDRAIL_VALIDATOR_CATEGORIES_TABLE, cRows);
        logger_1.default.info(`Seeded ClickHouse ${exports.CLICKHOUSE_GUARDRAIL_VALIDATOR_CATEGORIES_TABLE} with ${cRows.length} rows`);
    }
    if (aRows.length > 0) {
        await clickhouseService_1.clickHouseService.insert(exports.CLICKHOUSE_GUARDRAIL_ACTIONS_TABLE, aRows);
        logger_1.default.info(`Seeded ClickHouse ${exports.CLICKHOUSE_GUARDRAIL_ACTIONS_TABLE} with ${aRows.length} rows`);
    }
}
/**
 * Truncates and reloads guardrail catalog tables from repo JSON (admin / migration API).
 */
async function syncGuardrailReferenceTablesFromSeed() {
    await ensureTablesCreated();
    await clickhouseService_1.clickHouseService.command(`TRUNCATE TABLE ${exports.CLICKHOUSE_GUARDRAIL_ACTIONS_TABLE}`);
    await clickhouseService_1.clickHouseService.command(`TRUNCATE TABLE ${exports.CLICKHOUSE_GUARDRAIL_VALIDATOR_CATEGORIES_TABLE}`);
    await clickhouseService_1.clickHouseService.command(`TRUNCATE TABLE ${exports.CLICKHOUSE_GUARDRAIL_VALIDATORS_TABLE}`);
    const vRows = buildValidatorRows();
    const cRows = buildCategoryRows();
    const aRows = buildActionRows();
    if (vRows.length > 0) {
        await clickhouseService_1.clickHouseService.insert(exports.CLICKHOUSE_GUARDRAIL_VALIDATORS_TABLE, vRows);
    }
    if (cRows.length > 0) {
        await clickhouseService_1.clickHouseService.insert(exports.CLICKHOUSE_GUARDRAIL_VALIDATOR_CATEGORIES_TABLE, cRows);
    }
    if (aRows.length > 0) {
        await clickhouseService_1.clickHouseService.insert(exports.CLICKHOUSE_GUARDRAIL_ACTIONS_TABLE, aRows);
    }
    logger_1.default.info(`Synced ClickHouse guardrail catalog: validators=${vRows.length}, categories=${cRows.length}, actions=${aRows.length}`);
    return {
        validatorsInserted: vRows.length,
        categoriesInserted: cRows.length,
        actionsInserted: aRows.length,
    };
}
/**
 * Prompt fragment: reference tables + JOIN hints (no inline validator/action/category lists).
 */
function buildGuardrailReferenceTablesSchemaHint(guardrailResultsTableName) {
    return `
  Guardrail catalog reference tables (ClickHouse — use SCHEMA for exact column types):
  - ${exports.CLICKHOUSE_GUARDRAIL_VALIDATORS_TABLE}: **static catalog** of validator *types* (id, name, description, input, output). The \`id\` column holds **slug** identifiers (e.g. regex, blocklist, content-safety) from product seed data — **not** the per-deployment UUID strings that appear in live execution payloads.
  - ${exports.CLICKHOUSE_GUARDRAIL_VALIDATOR_CATEGORIES_TABLE}: taxonomy / harm categories (id, name, description). Use when the user asks about category names or descriptions; join to ${guardrailResultsTableName} only when the question implies a link.
  - ${exports.CLICKHOUSE_GUARDRAIL_ACTIONS_TABLE}: response actions (id, name, description, validators_json). validators_json stores a JSON array of validator ids allowed for that action.

  **Identifier shape (guardrail "validator id" / details questions):**
  - **UUID** (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx): treat as **${guardrailResultsTableName} row id** — filter \`WHERE <alias>.id = '<uuid>'\` (or \`WHERE ${guardrailResultsTableName}.id = '<uuid>'\`). That is the guardrail **execution** record, not \`JSONExtractString(cr, 'action', 'type')\` (that path is the **action** id on a component, not the result row id).
  - **Non-UUID** string (e.g. blocklist, regex): filter validator **type** on components with ARRAY JOIN and \`JSONExtractString(cr, 'assertion', 'type') = '<slug>'\`.
  - Do **not** answer UUID questions with only \`SELECT ... FROM ${exports.CLICKHOUSE_GUARDRAIL_VALIDATORS_TABLE} WHERE id = '<uuid>'\` — catalog \`id\` values are slugs. Optional \`LEFT JOIN ${exports.CLICKHOUSE_GUARDRAIL_VALIDATORS_TABLE} v ON v.id = JSONExtractString(cr, 'assertion', 'type')\` when the joined slug exists.

  Do not rely on hardcoded validator, category, or action lists in older prompts — discover names and descriptions from these tables (SELECT / JOIN).

  Typical joins from ${guardrailResultsTableName} after ARRAY JOIN JSONExtractArrayRaw(CAST(component_results AS String)) AS cr:
  - Validator metadata:
      INNER JOIN ${exports.CLICKHOUSE_GUARDRAIL_VALIDATORS_TABLE} AS v ON v.id = JSONExtractString(cr, 'assertion', 'type')
  - Action metadata:
      INNER JOIN ${exports.CLICKHOUSE_GUARDRAIL_ACTIONS_TABLE} AS act ON act.id = JSONExtractString(cr, 'action', 'type')
  - Optional: compare validator id to allowed list in act.validators_json using JSONExtractArrayRaw(act.validators_json) and arrayExists / has / IN patterns appropriate to SCHEMA.

  Prefer JOIN filters on id or name (e.g. v.name ILIKE, act.name ILIKE) using these reference tables.
`;
}
//# sourceMappingURL=guardrailReferenceTablesClickhouse.js.map