'use strict';

var chunkKD3YOO6V_cjs = require('./chunk-KD3YOO6V.cjs');
var chunkAWQJBTJ4_cjs = require('./chunk-AWQJBTJ4.cjs');
var chunkDAKDYSX2_cjs = require('./chunk-DAKDYSX2.cjs');
var chunkSUKFO7UM_cjs = require('./chunk-SUKFO7UM.cjs');
var chunk4LVJBXI2_cjs = require('./chunk-4LVJBXI2.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');
var z = require('zod');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var z__default = /*#__PURE__*/_interopDefault(z);

var listScorerVersionsQuerySchema = chunkKD3YOO6V_cjs.listVersionsQuerySchema;
var compareScorerVersionsQuerySchema = chunkKD3YOO6V_cjs.compareVersionsQuerySchema;
var createScorerVersionBodySchema = chunkKD3YOO6V_cjs.createVersionBodySchema;
var scorerVersionPathParams = z__default.default.object({
  scorerId: z__default.default.string().describe("Unique identifier for the stored scorer definition")
});
var scorerVersionIdPathParams = z__default.default.object({
  scorerId: z__default.default.string().describe("Unique identifier for the stored scorer definition"),
  versionId: z__default.default.string().describe("Unique identifier for the version (UUID)")
});
var samplingConfigSchema = z__default.default.union([
  z__default.default.object({ type: z__default.default.literal("none") }),
  z__default.default.object({ type: z__default.default.literal("ratio"), rate: z__default.default.number().min(0).max(1) })
]);
var scorerTypeEnum = z__default.default.enum([
  "llm-judge",
  "answer-relevancy",
  "answer-similarity",
  "bias",
  "context-precision",
  "context-relevance",
  "faithfulness",
  "hallucination",
  "noise-sensitivity",
  "prompt-alignment",
  "tool-call-accuracy",
  "toxicity"
]);
var scorerVersionSchema = z__default.default.object({
  id: z__default.default.string().describe("Unique identifier for the version (UUID)"),
  scorerDefinitionId: z__default.default.string().describe("ID of the scorer this version belongs to"),
  versionNumber: z__default.default.number().describe("Sequential version number (1, 2, 3, ...)"),
  // Snapshot config fields
  name: z__default.default.string().describe("Name of the scorer"),
  description: z__default.default.string().optional().describe("Description of the scorer"),
  type: scorerTypeEnum,
  model: chunkDAKDYSX2_cjs.modelConfigSchema.optional(),
  instructions: z__default.default.string().optional(),
  scoreRange: z__default.default.object({
    min: z__default.default.number().optional(),
    max: z__default.default.number().optional()
  }).optional(),
  presetConfig: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional(),
  defaultSampling: samplingConfigSchema.optional(),
  // Version metadata
  changedFields: z__default.default.array(z__default.default.string()).optional().describe("Array of field names that changed from the previous version"),
  changeMessage: z__default.default.string().optional().describe("Optional message describing the changes"),
  createdAt: z__default.default.coerce.date().describe("When this version was created")
});
var listScorerVersionsResponseSchema = chunkKD3YOO6V_cjs.createListVersionsResponseSchema(scorerVersionSchema);
var getScorerVersionResponseSchema = scorerVersionSchema;
var createScorerVersionResponseSchema = scorerVersionSchema.partial().merge(
  z__default.default.object({
    id: z__default.default.string(),
    scorerDefinitionId: z__default.default.string(),
    versionNumber: z__default.default.number(),
    createdAt: z__default.default.coerce.date()
  })
);
var activateScorerVersionResponseSchema = chunkKD3YOO6V_cjs.activateVersionResponseSchema;
var restoreScorerVersionResponseSchema = scorerVersionSchema;
var deleteScorerVersionResponseSchema = chunkKD3YOO6V_cjs.deleteVersionResponseSchema;
var compareScorerVersionsResponseSchema = chunkKD3YOO6V_cjs.createCompareVersionsResponseSchema(scorerVersionSchema);

// src/server/handlers/scorer-versions.ts
var SNAPSHOT_CONFIG_FIELDS = [
  "name",
  "description",
  "type",
  "model",
  "instructions",
  "scoreRange",
  "presetConfig",
  "defaultSampling"
];
var LIST_SCORER_VERSIONS_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "GET",
  path: "/stored/scorers/:scorerId/versions",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: scorerVersionPathParams,
  queryParamSchema: listScorerVersionsQuerySchema,
  responseSchema: listScorerVersionsResponseSchema,
  summary: "List scorer versions",
  description: "Returns a paginated list of all versions for a stored scorer",
  tags: ["Scorer Versions"],
  handler: async ({ mastra, scorerId, page, perPage, orderBy }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const scorer = await scorerStore.getById(scorerId);
      if (!scorer) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Scorer with id ${scorerId} not found` });
      }
      const result = await scorerStore.listVersions({
        scorerDefinitionId: scorerId,
        page,
        perPage,
        orderBy
      });
      return result;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error listing scorer versions");
    }
  }
});
var CREATE_SCORER_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "POST",
  path: "/stored/scorers/:scorerId/versions",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: scorerVersionPathParams,
  bodySchema: createScorerVersionBodySchema,
  responseSchema: createScorerVersionResponseSchema,
  summary: "Create scorer version",
  description: "Creates a new version snapshot of the current scorer configuration",
  tags: ["Scorer Versions"],
  handler: async ({ mastra, scorerId, changeMessage }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const scorer = await scorerStore.getById(scorerId);
      if (!scorer) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Scorer with id ${scorerId} not found` });
      }
      let currentConfig = {};
      if (scorer.activeVersionId) {
        const activeVersion = await scorerStore.getVersion(scorer.activeVersionId);
        if (activeVersion) {
          currentConfig = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
            activeVersion,
            SNAPSHOT_CONFIG_FIELDS
          );
        }
      }
      const latestVersion = await scorerStore.getLatestVersion(scorerId);
      if (!scorer.activeVersionId && latestVersion) {
        currentConfig = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
          latestVersion,
          SNAPSHOT_CONFIG_FIELDS
        );
      }
      const previousConfig = latestVersion ? chunkAWQJBTJ4_cjs.extractConfigFromVersion(latestVersion, SNAPSHOT_CONFIG_FIELDS) : null;
      const changedFields = chunkAWQJBTJ4_cjs.calculateChangedFields(previousConfig, currentConfig);
      const { versionId } = await chunkAWQJBTJ4_cjs.createVersionWithRetry(
        scorerStore,
        scorerId,
        "scorerDefinitionId",
        currentConfig,
        changedFields,
        { changeMessage }
      );
      const version = await scorerStore.getVersion(versionId);
      if (!version) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to retrieve created version" });
      }
      await chunkAWQJBTJ4_cjs.enforceRetentionLimit(
        scorerStore,
        scorerId,
        "scorerDefinitionId",
        scorer.activeVersionId
      );
      return version;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error creating scorer version");
    }
  }
});
var GET_SCORER_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "GET",
  path: "/stored/scorers/:scorerId/versions/:versionId",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: scorerVersionIdPathParams,
  responseSchema: getScorerVersionResponseSchema,
  summary: "Get scorer version",
  description: "Returns a specific version of a scorer by its version ID",
  tags: ["Scorer Versions"],
  handler: async ({ mastra, scorerId, versionId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const version = await scorerStore.getVersion(versionId);
      if (!version) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found` });
      }
      if (version.scorerDefinitionId !== scorerId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, {
          message: `Version with id ${versionId} not found for scorer ${scorerId}`
        });
      }
      return version;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error getting scorer version");
    }
  }
});
var ACTIVATE_SCORER_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "POST",
  path: "/stored/scorers/:scorerId/versions/:versionId/activate",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: scorerVersionIdPathParams,
  responseSchema: activateScorerVersionResponseSchema,
  summary: "Activate scorer version",
  description: "Sets a specific version as the active version for the scorer",
  tags: ["Scorer Versions"],
  handler: async ({ mastra, scorerId, versionId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const scorer = await scorerStore.getById(scorerId);
      if (!scorer) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Scorer with id ${scorerId} not found` });
      }
      const version = await scorerStore.getVersion(versionId);
      if (!version) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found` });
      }
      if (version.scorerDefinitionId !== scorerId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, {
          message: `Version with id ${versionId} not found for scorer ${scorerId}`
        });
      }
      await scorerStore.update({
        id: scorerId,
        activeVersionId: versionId,
        status: "published"
      });
      mastra.getEditor()?.scorer.clearCache(scorerId);
      return {
        success: true,
        message: `Version ${version.versionNumber} is now active`,
        activeVersionId: versionId
      };
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error activating scorer version");
    }
  }
});
var RESTORE_SCORER_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "POST",
  path: "/stored/scorers/:scorerId/versions/:versionId/restore",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: scorerVersionIdPathParams,
  responseSchema: restoreScorerVersionResponseSchema,
  summary: "Restore scorer version",
  description: "Restores the scorer configuration from a version, creating a new version",
  tags: ["Scorer Versions"],
  handler: async ({ mastra, scorerId, versionId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const scorer = await scorerStore.getById(scorerId);
      if (!scorer) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Scorer with id ${scorerId} not found` });
      }
      const versionToRestore = await scorerStore.getVersion(versionId);
      if (!versionToRestore) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found` });
      }
      if (versionToRestore.scorerDefinitionId !== scorerId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, {
          message: `Version with id ${versionId} not found for scorer ${scorerId}`
        });
      }
      const restoredConfig = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
        versionToRestore,
        SNAPSHOT_CONFIG_FIELDS
      );
      await scorerStore.update({
        id: scorerId,
        ...restoredConfig
      });
      const latestVersion = await scorerStore.getLatestVersion(scorerId);
      const previousConfig = latestVersion ? chunkAWQJBTJ4_cjs.extractConfigFromVersion(latestVersion, SNAPSHOT_CONFIG_FIELDS) : null;
      const changedFields = chunkAWQJBTJ4_cjs.calculateChangedFields(previousConfig, restoredConfig);
      const { versionId: newVersionId } = await chunkAWQJBTJ4_cjs.createVersionWithRetry(
        scorerStore,
        scorerId,
        "scorerDefinitionId",
        restoredConfig,
        changedFields,
        {
          changeMessage: `Restored from version ${versionToRestore.versionNumber}`
        }
      );
      const newVersion = await scorerStore.getVersion(newVersionId);
      if (!newVersion) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to retrieve created version" });
      }
      await chunkAWQJBTJ4_cjs.enforceRetentionLimit(
        scorerStore,
        scorerId,
        "scorerDefinitionId",
        scorer.activeVersionId
      );
      mastra.getEditor()?.scorer.clearCache(scorerId);
      return newVersion;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error restoring scorer version");
    }
  }
});
var DELETE_SCORER_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "DELETE",
  path: "/stored/scorers/:scorerId/versions/:versionId",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: scorerVersionIdPathParams,
  responseSchema: deleteScorerVersionResponseSchema,
  summary: "Delete scorer version",
  description: "Deletes a specific version (cannot delete the active version)",
  tags: ["Scorer Versions"],
  handler: async ({ mastra, scorerId, versionId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const scorer = await scorerStore.getById(scorerId);
      if (!scorer) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Scorer with id ${scorerId} not found` });
      }
      const version = await scorerStore.getVersion(versionId);
      if (!version) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found` });
      }
      if (version.scorerDefinitionId !== scorerId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, {
          message: `Version with id ${versionId} not found for scorer ${scorerId}`
        });
      }
      if (scorer.activeVersionId === versionId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, {
          message: "Cannot delete the active version. Activate a different version first."
        });
      }
      await scorerStore.deleteVersion(versionId);
      mastra.getEditor()?.scorer.clearCache(scorerId);
      return {
        success: true,
        message: `Version ${version.versionNumber} deleted successfully`
      };
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error deleting scorer version");
    }
  }
});
var COMPARE_SCORER_VERSIONS_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "GET",
  path: "/stored/scorers/:scorerId/versions/compare",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: scorerVersionPathParams,
  queryParamSchema: compareScorerVersionsQuerySchema,
  responseSchema: compareScorerVersionsResponseSchema,
  summary: "Compare scorer versions",
  description: "Compares two versions and returns the differences between them",
  tags: ["Scorer Versions"],
  handler: async ({ mastra, scorerId, from, to }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const fromVersion = await scorerStore.getVersion(from);
      if (!fromVersion) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${from} not found` });
      }
      if (fromVersion.scorerDefinitionId !== scorerId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, {
          message: `Version with id ${from} not found for scorer ${scorerId}`
        });
      }
      const toVersion = await scorerStore.getVersion(to);
      if (!toVersion) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${to} not found` });
      }
      if (toVersion.scorerDefinitionId !== scorerId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, {
          message: `Version with id ${to} not found for scorer ${scorerId}`
        });
      }
      const fromConfig = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
        fromVersion,
        SNAPSHOT_CONFIG_FIELDS
      );
      const toConfig = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
        toVersion,
        SNAPSHOT_CONFIG_FIELDS
      );
      const diffs = chunkAWQJBTJ4_cjs.computeVersionDiffs(fromConfig, toConfig);
      return {
        diffs,
        fromVersion,
        toVersion
      };
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error comparing scorer versions");
    }
  }
});

exports.ACTIVATE_SCORER_VERSION_ROUTE = ACTIVATE_SCORER_VERSION_ROUTE;
exports.COMPARE_SCORER_VERSIONS_ROUTE = COMPARE_SCORER_VERSIONS_ROUTE;
exports.CREATE_SCORER_VERSION_ROUTE = CREATE_SCORER_VERSION_ROUTE;
exports.DELETE_SCORER_VERSION_ROUTE = DELETE_SCORER_VERSION_ROUTE;
exports.GET_SCORER_VERSION_ROUTE = GET_SCORER_VERSION_ROUTE;
exports.LIST_SCORER_VERSIONS_ROUTE = LIST_SCORER_VERSIONS_ROUTE;
exports.RESTORE_SCORER_VERSION_ROUTE = RESTORE_SCORER_VERSION_ROUTE;
//# sourceMappingURL=chunk-7NRYKBNJ.cjs.map
//# sourceMappingURL=chunk-7NRYKBNJ.cjs.map