'use strict';

var chunkMJ5QWRI2_cjs = require('./chunk-MJ5QWRI2.cjs');
var chunkEFJCOPJ3_cjs = require('./chunk-EFJCOPJ3.cjs');
var chunkDIG2K5CV_cjs = require('./chunk-DIG2K5CV.cjs');
var chunkZ7LCIYK7_cjs = require('./chunk-Z7LCIYK7.cjs');
var chunkN54Q3AQR_cjs = require('./chunk-N54Q3AQR.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');
var chunkO7I5CWRX_cjs = require('./chunk-O7I5CWRX.cjs');

// src/server/handlers/scores.ts
var scores_exports = {};
chunkO7I5CWRX_cjs.__export(scores_exports, {
  GET_SCORER_ROUTE: () => GET_SCORER_ROUTE,
  LIST_SCORERS_ROUTE: () => LIST_SCORERS_ROUTE,
  LIST_SCORES_BY_ENTITY_ID_ROUTE: () => LIST_SCORES_BY_ENTITY_ID_ROUTE,
  LIST_SCORES_BY_RUN_ID_ROUTE: () => LIST_SCORES_BY_RUN_ID_ROUTE,
  LIST_SCORES_BY_SCORER_ID_ROUTE: () => LIST_SCORES_BY_SCORER_ID_ROUTE,
  SAVE_SCORE_ROUTE: () => SAVE_SCORE_ROUTE
});
async function listScorersFromSystem({
  mastra,
  requestContext
}) {
  const agents = mastra.listAgents();
  const workflows = mastra.listWorkflows();
  const scorersMap = /* @__PURE__ */ new Map();
  const processAgentScorers = async (agent) => {
    const scorers = await agent.listScorers({
      requestContext
    }) || {};
    if (Object.keys(scorers).length > 0) {
      for (const [_scorerId, scorer] of Object.entries(scorers)) {
        const scorerId = scorer.scorer.id;
        if (scorersMap.has(scorerId)) {
          scorersMap.get(scorerId)?.agentIds.push(agent.id);
          scorersMap.get(scorerId)?.agentNames.push(agent.name);
        } else {
          scorersMap.set(scorerId, {
            workflowIds: [],
            ...scorer,
            agentNames: [agent.name],
            agentIds: [agent.id],
            isRegistered: false,
            source: scorer.scorer.source ?? "code"
          });
        }
      }
    }
  };
  for (const [_, agent] of Object.entries(agents)) {
    await processAgentScorers(agent);
  }
  try {
    const editor = mastra.getEditor();
    const storedAgentsResult = await editor?.agent.list();
    if (storedAgentsResult?.agents) {
      for (const storedAgentConfig of storedAgentsResult.agents) {
        try {
          const agent = await editor?.agent.getById(storedAgentConfig.id);
          if (agent) {
            await processAgentScorers(agent);
          }
        } catch {
        }
      }
    }
  } catch {
  }
  try {
    const editor = mastra.getEditor();
    const storedScorersResult = await editor?.scorer.list();
    if (storedScorersResult?.scorerDefinitions) {
      for (const storedScorerConfig of storedScorersResult.scorerDefinitions) {
        try {
          await editor?.scorer.getById(storedScorerConfig.id);
        } catch {
        }
      }
    }
  } catch {
  }
  for (const [workflowId, workflow] of Object.entries(workflows)) {
    const scorers = await workflow.listScorers({
      requestContext
    }) || {};
    if (Object.keys(scorers).length > 0) {
      for (const [_scorerId, scorer] of Object.entries(scorers)) {
        const scorerName = scorer.scorer.name;
        if (scorersMap.has(scorerName)) {
          scorersMap.get(scorerName)?.workflowIds.push(workflowId);
        } else {
          scorersMap.set(scorerName, {
            agentIds: [],
            agentNames: [],
            ...scorer,
            workflowIds: [workflowId],
            isRegistered: false,
            source: scorer.scorer.source ?? "code"
          });
        }
      }
    }
  }
  const registeredScorers = await mastra.listScorers();
  for (const [_scorerId, scorer] of Object.entries(registeredScorers || {})) {
    const scorerId = scorer.id;
    if (scorersMap.has(scorerId)) {
      scorersMap.get(scorerId).isRegistered = true;
    } else {
      scorersMap.set(scorerId, {
        scorer,
        agentIds: [],
        agentNames: [],
        workflowIds: [],
        isRegistered: true,
        source: scorer.source ?? "code"
      });
    }
  }
  return Object.fromEntries(scorersMap.entries());
}
function getTraceDetails(traceIdWithSpanId) {
  if (!traceIdWithSpanId) {
    return {};
  }
  const [traceId, spanId] = traceIdWithSpanId.split("-");
  return {
    ...traceId ? { traceId } : {},
    ...spanId ? { spanId } : {}
  };
}
var LIST_SCORERS_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/scores/scorers",
  responseType: "json",
  responseSchema: chunkMJ5QWRI2_cjs.listScorersResponseSchema,
  summary: "List all scorers",
  description: "Returns a list of all registered scorers with their configuration and associated agents and workflows",
  tags: ["Scoring"],
  requiresAuth: true,
  handler: (async ({ mastra, requestContext }) => {
    const scorers = await listScorersFromSystem({
      mastra,
      requestContext
    });
    return scorers;
  })
});
var GET_SCORER_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/scores/scorers/:scorerId",
  responseType: "json",
  pathParamSchema: chunkMJ5QWRI2_cjs.scorerIdPathParams,
  responseSchema: chunkMJ5QWRI2_cjs.scorerEntrySchema.nullable(),
  summary: "Get scorer by ID",
  description: "Returns details for a specific scorer including its configuration and associations",
  tags: ["Scoring"],
  requiresAuth: true,
  handler: (async ({ mastra, scorerId, requestContext }) => {
    const scorers = await listScorersFromSystem({
      mastra,
      requestContext
    });
    const scorer = scorers[scorerId];
    if (!scorer) {
      return null;
    }
    return scorer;
  })
});
var LIST_SCORES_BY_RUN_ID_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/scores/run/:runId",
  responseType: "json",
  pathParamSchema: chunkDIG2K5CV_cjs.runIdSchema,
  queryParamSchema: chunkMJ5QWRI2_cjs.listScoresByRunIdQuerySchema,
  responseSchema: chunkMJ5QWRI2_cjs.scoresWithPaginationResponseSchema,
  summary: "List scores by run ID",
  description: "Returns all scores for a specific execution run",
  tags: ["Scoring"],
  requiresAuth: true,
  handler: async ({ mastra, runId, ...params }) => {
    try {
      const { page, perPage } = params;
      const pagination = {
        page: page ?? 0,
        perPage: perPage ?? 10
      };
      const scores = await mastra.getStorage()?.getStore("scores");
      const scoreResults = await scores?.listScoresByRunId?.({
        runId,
        pagination
      }) || { pagination: { total: 0, page: 0, perPage: 0, hasMore: false }, scores: [] };
      return {
        pagination: scoreResults.pagination,
        scores: scoreResults.scores.map((score) => ({ ...score, ...getTraceDetails(score.traceId) }))
      };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error getting scores by run id");
    }
  }
});
var LIST_SCORES_BY_SCORER_ID_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/scores/scorer/:scorerId",
  responseType: "json",
  pathParamSchema: chunkMJ5QWRI2_cjs.scorerIdPathParams,
  queryParamSchema: chunkMJ5QWRI2_cjs.listScoresByScorerIdQuerySchema,
  responseSchema: chunkMJ5QWRI2_cjs.scoresWithPaginationResponseSchema,
  summary: "List scores by scorer ID",
  description: "Returns all scores generated by a specific scorer",
  tags: ["Scoring"],
  requiresAuth: true,
  handler: async ({ mastra, scorerId, ...params }) => {
    try {
      const { page, perPage, entityId, entityType } = params;
      const filters = Object.fromEntries(Object.entries({ entityId, entityType }).filter(([_, v]) => v !== void 0));
      const scores = await mastra.getStorage()?.getStore("scores");
      const scoreResults = await scores?.listScoresByScorerId?.({
        scorerId,
        pagination: { page: page ?? 0, perPage: perPage ?? 10 },
        ...filters
      }) || { pagination: { total: 0, page: 0, perPage: 0, hasMore: false }, scores: [] };
      return {
        pagination: scoreResults.pagination,
        scores: scoreResults.scores.map((score) => ({ ...score, ...getTraceDetails(score.traceId) }))
      };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error getting scores by scorer id");
    }
  }
});
var LIST_SCORES_BY_ENTITY_ID_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/scores/entity/:entityType/:entityId",
  responseType: "json",
  pathParamSchema: chunkMJ5QWRI2_cjs.entityPathParams,
  queryParamSchema: chunkMJ5QWRI2_cjs.listScoresByEntityIdQuerySchema,
  responseSchema: chunkMJ5QWRI2_cjs.scoresWithPaginationResponseSchema,
  summary: "List scores by entity ID",
  description: "Returns all scores for a specific entity (agent or workflow)",
  tags: ["Scoring"],
  requiresAuth: true,
  handler: async ({ mastra, entityId, entityType, ...params }) => {
    try {
      const { page, perPage } = params;
      let entityIdToUse = entityId;
      if (entityType === "AGENT") {
        const agent = await chunkEFJCOPJ3_cjs.getAgentFromSystem({ mastra, agentId: entityId });
        entityIdToUse = agent.id;
      } else if (entityType === "WORKFLOW") {
        const workflow = mastra.getWorkflowById(entityId);
        entityIdToUse = workflow.id;
      }
      const pagination = {
        page: page ?? 0,
        perPage: perPage ?? 10
      };
      const scoresStore = await mastra.getStorage()?.getStore("scores");
      const scoreResults = await scoresStore?.listScoresByEntityId?.({
        entityId: entityIdToUse,
        entityType,
        pagination
      }) || { pagination: { total: 0, page: 0, perPage: 0, hasMore: false }, scores: [] };
      return {
        pagination: scoreResults.pagination,
        scores: scoreResults.scores.map((score) => ({ ...score, ...getTraceDetails(score.traceId) }))
      };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error getting scores by entity id");
    }
  }
});
var SAVE_SCORE_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/scores",
  responseType: "json",
  bodySchema: chunkMJ5QWRI2_cjs.saveScoreBodySchema,
  responseSchema: chunkMJ5QWRI2_cjs.saveScoreResponseSchema,
  summary: "Save score",
  description: "Saves a new score record to storage",
  tags: ["Scoring"],
  requiresAuth: true,
  handler: async ({ mastra, ...params }) => {
    try {
      const { score } = params;
      const scoresStore = await mastra.getStorage()?.getStore("scores");
      const result = await scoresStore?.saveScore?.(score);
      if (!result) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage not configured" });
      }
      return result;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error saving score");
    }
  }
});

exports.GET_SCORER_ROUTE = GET_SCORER_ROUTE;
exports.LIST_SCORERS_ROUTE = LIST_SCORERS_ROUTE;
exports.LIST_SCORES_BY_ENTITY_ID_ROUTE = LIST_SCORES_BY_ENTITY_ID_ROUTE;
exports.LIST_SCORES_BY_RUN_ID_ROUTE = LIST_SCORES_BY_RUN_ID_ROUTE;
exports.LIST_SCORES_BY_SCORER_ID_ROUTE = LIST_SCORES_BY_SCORER_ID_ROUTE;
exports.SAVE_SCORE_ROUTE = SAVE_SCORE_ROUTE;
exports.scores_exports = scores_exports;
//# sourceMappingURL=chunk-IRMEODX4.cjs.map
//# sourceMappingURL=chunk-IRMEODX4.cjs.map