"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isToolProposeChangeSuccessResult = exports.isToolProposeChangeResult = exports.toolProposeChangeOutputSchema = exports.toolProposeChangeArgsSchema = exports.TOOL_PROPOSE_CHANGE_DESCRIPTION = void 0;
const zod_1 = require("zod");
const customMetrics_1 = require("../customMetrics");
const fieldId_1 = require("../fieldId");
const toolSchemaBuilder_1 = require("../toolSchemaBuilder");
// ============================================================================
// Tool Description
// ============================================================================
exports.TOOL_PROPOSE_CHANGE_DESCRIPTION = `
Creates a change proposal for tables, metrics, and dimensions. Changes are applied immediately but can be reviewed and rejected afterward.

**Supported Operations:**
- Update table descriptions and labels
- Update metric/dimension descriptions and labels
- Create new metrics

**Technical Requirements:**
- When updating descriptions or labels, must preserve as much original content as possible
- Descriptions should maintain their original format (preserve complete value and formatting)
- Must provide entity table name, rationale, and change details
- Changes are tracked with proposer information and timestamp
- For updates: use "replace" operation with complete updated value (not partial)
- For adding new properties: use "add" operation (creates property if it does not exist)
- For new metrics: use "create" operation with full metric definition
`;
const getPatchDescription = (type) => `Patch to apply to the ${type}. You can omit/set-to-null any fields you don't want to change.`;
// ============================================================================
// Operation Schemas
// ============================================================================
/**
 * Op schema can be configured on per-field basis to have a appropriate type and allow applicable operations
 */
const getOpSchema = (type) => zod_1.z.discriminatedUnion('op', [
    zod_1.z
        .object({ op: zod_1.z.literal('replace'), value: type })
        .describe([
        'Replace (overwrite) the value of the field.',
        'Updates the **entire** value of the field to reflect the necessary changes, replacing the current value entirely.',
        'Even if only the part is being changed, make sure to pass the entire value with changes included so that no part is lost.',
    ].join('\n')),
    zod_1.z
        .object({ op: zod_1.z.literal('add'), value: type })
        .describe('Add a new value to the field. (Creates a new property if it does not exist)'),
    // z.object({
    //   op: z.literal("push"),
    //   value: z.any(),
    //   index: z.number().nullable() // add later to support `"path": "/tags/-"` / "path": "/tags/0" if no index, default to ops on array
    // }),
    // z.object({ op: z.literal("remove") }),
]);
const stringOpSchema = getOpSchema(zod_1.z.string());
// ============================================================================
// Entity Change Schemas
// ============================================================================
const TableChangeSchema = zod_1.z.discriminatedUnion('type', [
    zod_1.z.object({
        type: zod_1.z.literal('update'),
        patch: zod_1.z
            .object({
            description: stringOpSchema.nullable(),
            label: stringOpSchema.nullable(),
        })
            .describe(getPatchDescription('table')),
    }),
]);
const DimensionChangeSchema = zod_1.z.discriminatedUnion('type', [
    zod_1.z.object({
        type: zod_1.z.literal('update'),
        patch: zod_1.z
            .object({
            label: stringOpSchema.nullable(),
            description: stringOpSchema.nullable(),
        })
            .describe(getPatchDescription('dimension')),
    }),
    // z.object({
    //   type: z.literal('delete'),
    // })
]);
const MetricChangeSchema = zod_1.z.discriminatedUnion('type', [
    zod_1.z.object({
        type: zod_1.z.literal('create'),
        value: zod_1.z.discriminatedUnion('entityType', [
            zod_1.z
                .object({
                entityType: zod_1.z.literal('metric'),
                metric: customMetrics_1.customMetricBaseSchema,
            })
                .describe('Create a new metric'),
        ]),
    }),
    zod_1.z.object({
        type: zod_1.z.literal('update'),
        patch: zod_1.z
            .object({
            label: stringOpSchema.nullable(),
            description: stringOpSchema.nullable(),
            // aiHint: OpSchema,
        })
            .describe(getPatchDescription('metric')),
    }),
]);
// ============================================================================
// Main Change Schema
// ============================================================================
const changeSchema = zod_1.z.discriminatedUnion('entityType', [
    zod_1.z.object({
        entityType: zod_1.z.literal('table'),
        value: TableChangeSchema,
    }),
    zod_1.z.object({
        entityType: zod_1.z.literal('dimension'),
        fieldId: (0, fieldId_1.getFieldIdSchema)({ additionalDescription: '' }),
        value: DimensionChangeSchema,
    }),
    zod_1.z.object({
        entityType: zod_1.z.literal('metric'),
        fieldId: (0, fieldId_1.getFieldIdSchema)({
            additionalDescription: 'if you are creating a new metric, this is the field id of the new metric not the dimension id',
        }),
        value: MetricChangeSchema,
    }),
]);
// ============================================================================
// Tool Schema Export
// ============================================================================
exports.toolProposeChangeArgsSchema = (0, toolSchemaBuilder_1.createToolSchema)({
    description: exports.TOOL_PROPOSE_CHANGE_DESCRIPTION,
})
    .extend({
    entityTableName: zod_1.z
        .string()
        .describe('The name of the table/explore being modified'),
    rationale: zod_1.z
        .string()
        .describe('Brief explanation of why this change is being proposed and what it improves'),
    change: changeSchema,
})
    .build();
exports.toolProposeChangeOutputSchema = zod_1.z.object({
    result: zod_1.z.string(),
    metadata: zod_1.z.discriminatedUnion('status', [
        zod_1.z.object({
            status: zod_1.z.literal('success'),
            changeUuid: zod_1.z.string(),
            userFeedback: zod_1.z
                .enum(['accepted', 'rejected'])
                .default('accepted')
                .optional(),
        }),
        zod_1.z.object({
            status: zod_1.z.literal('error'),
        }),
    ]),
});
const isToolProposeChangeSuccessMetadata = (metadata) => exports.toolProposeChangeOutputSchema.shape.metadata.safeParse(metadata).success;
const isToolProposeChangeResult = (result) => result.toolType === 'built-in' && result.toolName === 'proposeChange';
exports.isToolProposeChangeResult = isToolProposeChangeResult;
const isToolProposeChangeSuccessResult = (result) => (0, exports.isToolProposeChangeResult)(result) &&
    isToolProposeChangeSuccessMetadata(result.metadata);
exports.isToolProposeChangeSuccessResult = isToolProposeChangeSuccessResult;
//# sourceMappingURL=toolProposeChangeArgs.js.map