import { Router } from "express";
import type { AppServices } from "../serverContext";
import { ok } from "../utils/http";
import type { EvalRunMode, NormalizeRequestPayload } from "../types/normalizer";
import type { EvalTarget } from "../types/assistantEval";

export function buildEvalRouter(services: AppServices): Router {
  const router = Router();

  router.post("/api/eval/run", async (req, res, next) => {
    try {
      const body = (req.body ?? {}) as Record<string, unknown>;
      const report = await services.evalService.run({
        normalizeConfig: (body.normalizeConfig ?? {}) as Omit<NormalizeRequestPayload, "userQuestion" | "context">,
        caseIds: Array.isArray(body.caseIds) ? (body.caseIds as string[]) : undefined,
        useMock: Boolean(body.useMock),
        mode: (body.mode as EvalRunMode | undefined) ?? "standard",
        caseSetFile: typeof body.caseSetFile === "string" ? body.caseSetFile : undefined,
        rawQuestions: typeof body.rawQuestions === "string" ? body.rawQuestions : undefined,
        evalTarget: (body.eval_target as EvalTarget | undefined) ?? "normalizer",
        compareWithReportFile:
          typeof body.compare_with_report_file === "string"
            ? body.compare_with_report_file
            : typeof body.comparisonBaselineReportFile === "string"
              ? body.comparisonBaselineReportFile
              : undefined
      });
      ok(res, {
        ok: true,
        report
      });
    } catch (error) {
      next(error);
    }
  });

  return router;
}
