/**
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import type { EvaluatorAction, Genkit, ModelArgument, z } from 'genkit';
import type { GenerationCommonConfigSchema } from 'genkit/model';
import { genkitPlugin, type GenkitPlugin } from 'genkit/plugin';
import type { Criteria } from 'langchain/evaluation';
import { langchainEvaluator } from './evaluators.js';

export { GenkitTracer } from './tracing.js';

interface LangchainPluginParams<
  ModelCustomOptions extends z.ZodTypeAny = typeof GenerationCommonConfigSchema,
> {
  evaluators?: {
    criteria?: Criteria[];
    labeledCriteria?: Criteria[];
    judge: ModelArgument<ModelCustomOptions>;
    judgeConfig?: z.infer<ModelCustomOptions>;
  };
}

export function langchain(params: LangchainPluginParams): GenkitPlugin {
  return genkitPlugin('langchain', async (ai: Genkit) => {
    const evaluators: EvaluatorAction[] = [];
    if (params.evaluators) {
      for (const criteria of params.evaluators.criteria ?? []) {
        evaluators.push(
          langchainEvaluator(
            ai,
            'criteria',
            criteria,
            params.evaluators.judge,
            params.evaluators?.judgeConfig
          )
        );
      }
      for (const criteria of params.evaluators.labeledCriteria ?? []) {
        evaluators.push(
          langchainEvaluator(
            ai,
            'labeled_criteria',
            criteria,
            params.evaluators.judge,
            params.evaluators?.judgeConfig
          )
        );
      }
    }
  });
}
