"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UpdateTaskAIContextSchema = exports.CreateTaskAIContextSchema = void 0;
exports.validateContextData = validateContextData;
exports.prepareCreateTaskAIContext = prepareCreateTaskAIContext;
exports.calculateTotalTokens = calculateTotalTokens;
exports.estimateCost = estimateCost;
exports.isValidAgentType = isValidAgentType;
exports.isValidContextType = isValidContextType;
const zod_1 = require("zod");
const task_ai_context_entity_1 = require("../entities/task-ai-context.entity");
/**
 * Validation schema for AI context data based on context type
 */
const PromptContextDataSchema = zod_1.z.object({
    prompt: zod_1.z.string().min(1),
    systemPrompt: zod_1.z.string().optional(),
    parameters: zod_1.z.record(zod_1.z.any()).optional(),
    modelUsed: zod_1.z.string().optional(),
    temperature: zod_1.z.number().min(0).max(2).optional(),
    maxTokens: zod_1.z.number().positive().optional(),
    timestamp: zod_1.z.string().optional(),
    sessionId: zod_1.z.string().optional(),
    requestId: zod_1.z.string().optional(),
    metadata: zod_1.z.record(zod_1.z.any()).optional(),
});
const ResultContextDataSchema = zod_1.z.object({
    response: zod_1.z.string(),
    completionTokens: zod_1.z.number().nonnegative().optional(),
    promptTokens: zod_1.z.number().nonnegative().optional(),
    totalTokens: zod_1.z.number().nonnegative().optional(),
    modelUsed: zod_1.z.string().optional(),
    timestamp: zod_1.z.string().optional(),
    sessionId: zod_1.z.string().optional(),
    requestId: zod_1.z.string().optional(),
    metadata: zod_1.z.record(zod_1.z.any()).optional(),
});
const FeedbackContextDataSchema = zod_1.z.object({
    feedbackType: zod_1.z.enum(['positive', 'negative', 'correction']),
    feedbackMessage: zod_1.z.string(),
    userRating: zod_1.z.number().min(1).max(5).optional(),
    timestamp: zod_1.z.string().optional(),
    sessionId: zod_1.z.string().optional(),
    metadata: zod_1.z.record(zod_1.z.any()).optional(),
});
const ErrorContextDataSchema = zod_1.z.object({
    errorCode: zod_1.z.string().optional(),
    errorMessage: zod_1.z.string(),
    stackTrace: zod_1.z.string().optional(),
    retryCount: zod_1.z.number().nonnegative().optional(),
    timestamp: zod_1.z.string().optional(),
    sessionId: zod_1.z.string().optional(),
    requestId: zod_1.z.string().optional(),
    metadata: zod_1.z.record(zod_1.z.any()).optional(),
});
/**
 * Schema for creating a new task AI context
 */
exports.CreateTaskAIContextSchema = zod_1.z.object({
    task_id: zod_1.z.string().uuid('Invalid task ID format'),
    ai_agent_type: zod_1.z.nativeEnum(task_ai_context_entity_1.AIAgentType),
    context_type: zod_1.z.nativeEnum(task_ai_context_entity_1.AIContextType),
    context_data: zod_1.z.any(), // Will be validated based on context_type
    execution_timestamp: zod_1.z.date().optional(),
    success: zod_1.z.boolean().optional(),
    tokens_used: zod_1.z.number().nonnegative().nullable().optional(),
    execution_time_ms: zod_1.z.number().nonnegative().nullable().optional(),
});
/**
 * Schema for updating a task AI context
 */
exports.UpdateTaskAIContextSchema = zod_1.z.object({
    context_data: zod_1.z.any().optional(),
    success: zod_1.z.boolean().optional(),
    tokens_used: zod_1.z.number().nonnegative().nullable().optional(),
    execution_time_ms: zod_1.z.number().nonnegative().nullable().optional(),
});
/**
 * Validates context data based on context type
 * @param contextType The type of context
 * @param contextData The context data to validate
 * @returns Validated context data
 * @throws ZodError if validation fails
 */
function validateContextData(contextType, contextData) {
    switch (contextType) {
        case task_ai_context_entity_1.AIContextType.PROMPT:
            return PromptContextDataSchema.parse(contextData);
        case task_ai_context_entity_1.AIContextType.RESULT:
            return ResultContextDataSchema.parse(contextData);
        case task_ai_context_entity_1.AIContextType.FEEDBACK:
            return FeedbackContextDataSchema.parse(contextData);
        case task_ai_context_entity_1.AIContextType.ERROR:
            return ErrorContextDataSchema.parse(contextData);
        default:
            throw new Error(`Unknown context type: ${contextType}`);
    }
}
/**
 * Validates and prepares data for creating a task AI context
 * @param data Raw input data
 * @returns Validated and prepared data
 */
function prepareCreateTaskAIContext(data) {
    // First validate the basic structure
    const validated = exports.CreateTaskAIContextSchema.parse(data);
    // Then validate the context data based on context type
    if (validated.context_data) {
        validated.context_data = validateContextData(validated.context_type, validated.context_data);
    }
    // Set default values
    if (!validated.execution_timestamp) {
        validated.execution_timestamp = new Date();
    }
    if (validated.success === undefined) {
        validated.success = true;
    }
    return validated;
}
/**
 * Calculates total tokens from context data
 * @param contextData The context data
 * @returns Total token count or null
 */
function calculateTotalTokens(contextData) {
    if (contextData.totalTokens) {
        return contextData.totalTokens;
    }
    if (contextData.promptTokens && contextData.completionTokens) {
        return contextData.promptTokens + contextData.completionTokens;
    }
    return null;
}
/**
 * Estimates cost based on token usage and model
 * @param tokens Number of tokens used
 * @param model Model name
 * @returns Estimated cost in USD
 */
function estimateCost(tokens, model = 'gpt-4-turbo') {
    // Pricing as of 2024 (per 1K tokens)
    const pricing = {
        'gpt-4-turbo': { input: 0.01, output: 0.03 },
        'gpt-4': { input: 0.03, output: 0.06 },
        'gpt-3.5-turbo': { input: 0.0005, output: 0.0015 },
    };
    const modelPricing = pricing[model] || pricing['gpt-4-turbo'];
    // Using average of input and output pricing for estimation
    const avgPrice = (modelPricing.input + modelPricing.output) / 2;
    return (tokens / 1000) * avgPrice;
}
/**
 * Validates if an AI agent type is supported
 * @param agentType The agent type to check
 * @returns True if supported
 */
function isValidAgentType(agentType) {
    return Object.values(task_ai_context_entity_1.AIAgentType).includes(agentType);
}
/**
 * Validates if a context type is valid
 * @param contextType The context type to check
 * @returns True if valid
 */
function isValidContextType(contextType) {
    return Object.values(task_ai_context_entity_1.AIContextType).includes(contextType);
}
//# sourceMappingURL=task-ai-context.validator.js.map