import { generateOpenAiImageObjectQuery } from '@/platforms/openai';
import {
  AiAutoGeneratedField,
  getAiImageQuerySchema,
  getAiTextFieldsToGenerate,
} from '.';
import { AI_TEXT_AUTO_GENERATED_FIELDS } from '@/app/config';
import { PhotoFormData } from '../form';
import { Tags } from '@/tag';

export const generateAiImageQueries = async ({
  imageBase64,
  textFieldsToGenerate = [],
  existingTitle,
  uniqueTags,
  isBatch,
}: {
  imageBase64?: string
  textFieldsToGenerate: AiAutoGeneratedField[]
  existingTitle?: string
  uniqueTags: Tags
  isBatch?: boolean
}): Promise<{
  title?: string
  caption?: string
  tags?: string
  semantic?: string
  error?: string
}> => {
  if (imageBase64) {
    try {
      const { query, schema } = getAiImageQuerySchema(
        textFieldsToGenerate,
        existingTitle,
        uniqueTags,
      );
      return generateOpenAiImageObjectQuery(
        imageBase64,
        query,
        schema,
        isBatch,
      );
    } catch (e: any) {
      return {
        error: e.message,
      };
    }
  } else {
    return {
      error: 'No image provided',
    };
  }
};

export const addAiTextToFormData = async ({
  formData = {},
  imageBase64,
  existingTitle,
  existingTags,
  uniqueTags,
}: {
  formData?: Partial<PhotoFormData>
  imageBase64?: string
  existingTitle?: string
  existingTags?: string
  uniqueTags: Tags
}): Promise<Partial<PhotoFormData>> => {
  const {
    title: aiTitle,
    caption: aiCaption,
    tags: aiTags,
    semantic,
  } = await generateAiImageQueries({
    imageBase64,
    textFieldsToGenerate: getAiTextFieldsToGenerate(
      AI_TEXT_AUTO_GENERATED_FIELDS,
      Boolean(existingTitle || formData?.title),
      Boolean(formData?.caption),
      Boolean(existingTags || formData?.tags),
    ),
    existingTitle: existingTitle || formData?.title,
    uniqueTags,
  });

  return {
    ...formData,
    title: formData?.title || aiTitle,
    caption: formData?.caption || aiCaption,
    tags: formData?.tags || aiTags,
    semanticDescription: semantic,
  };
};
