import { TYPE_MS_STREAM, TYPE_SHAREPOINT, TYPE_TEAMS, TYPE_ZOOM } from '@/modules/feeds/constants';
import { MEETINGS_SOURCES_ENABLED_BY_DEFAULT, SOURCES_DISABLED_BY_DEFAULT } from '@/modules/feeds/Editor/constants';

import { MetadataFeedPlatformModelType, PlatformModel } from '@/modules/feeds/Editor/types';
import type { FeedType } from '@/modules/feeds/types';

export type ConvertedModel = {
  id: string;
  displayName: string;
  features: string[];
  platform: string;
  model: string;
  category: string;
  enabled: boolean;
  description: string;
  parameters: string[];
  example: string;
};

export const uidGenerator = (): string => Math.random().toString(36).split('.').pop() ?? '';

const compareCategories = (a: string, b: string): number => {
  const a1 = a === '' ? 'ZZZZ' : a;
  const b1 = b === '' ? 'ZZZZ' : b;
  return a1.localeCompare(b1);
};

const sortArrayByFields = (
  array: ConvertedModel[],
  primaryField: 'category',
  secondaryField: 'displayName',
): ConvertedModel[] =>
  array.sort((a, b) => {
    if (a[primaryField] !== b[primaryField]) {
      return compareCategories(a[primaryField], b[primaryField]);
    }
    return a[secondaryField].localeCompare(b[secondaryField]);
  });

const sortPlatformModels = (platformModels: ConvertedModel[]): ConvertedModel[] =>
  sortArrayByFields(platformModels, 'category', 'displayName');

const parseModelDescription = (fullDescription: string): string => {
  const mainPart = fullDescription?.split('Parameters:')[0];
  if (!mainPart) return '';
  const colonIndex = mainPart.indexOf(':');
  return colonIndex !== -1 ? mainPart.substring(colonIndex + 1).trim() : mainPart.trim();
};

const parseModelParameters = (fullDescription: string): string[] => {
  const paramsPart = fullDescription?.split('Parameters:')[1]?.split('Example:')[0]?.trim() ?? '';
  if (!paramsPart) return [];

  return paramsPart
    .split(';')
    .map((param) => param.trim())
    .filter((param) => param.length > 0);
};

const parseModelExample = (fullDescription: string): string => {
  const examplePart = fullDescription?.split('Example:')[1]?.trim();
  if (!examplePart) return '';

  const validJsonPart = examplePart.endsWith('}')
    ? examplePart
    : examplePart.substring(0, examplePart.lastIndexOf('}') + 1);

  try {
    const parsed = JSON.parse(validJsonPart);
    return JSON.stringify(parsed, null, 2);
  } catch {
    return '';
  }
};

// logic transfer from old isEnabledPlatformModel function
// const isEnabledPlatformModel = (provider, model, type) => {
//   const isMeetingSource = [
//     CONSTANTS.FEEDS.TYPES.TEAMS.value,
//     CONSTANTS.FEEDS.TYPES.SHAREPOINT.value,
//     CONSTANTS.FEEDS.TYPES.ZOOM.value, CONSTANTS.FEEDS.TYPES.MS_STREAM.value].includes(type);
//   let isEnabled;
//   if (isMeetingSource) {
//     isEnabled = !!(CONSTANTS.FEEDS.PLATFORMS.DEFAULTS.MEETINGS_SOURCE.ENABLED_BY_DEFAULT
//       .filter((m) => m.model === model.name && m.provider === provider.provider)
//       .length);
//   } else {
//     isEnabled = !CONSTANTS.FEEDS.PLATFORMS.DEFAULTS.FEED.DISABLED_BY_DEFAULT
//       .filter((m) => m.model === model.name && m.provider === provider.provider)
//       .length;
//   }
//   return isEnabled;
// };
function setDefault(model: { name: string }, provider: { provider: string }, type: FeedType) {
  if (!type) return false;

  const isMeetingSource = [TYPE_ZOOM, TYPE_SHAREPOINT, TYPE_TEAMS, TYPE_MS_STREAM].includes(type);

  let isEnabled;
  if (isMeetingSource) {
    isEnabled = !!MEETINGS_SOURCES_ENABLED_BY_DEFAULT.filter(
      (m) => m.model === model.name && m.provider === provider.provider,
    ).length;
  } else {
    isEnabled = !SOURCES_DISABLED_BY_DEFAULT.filter((m) => m.model === model.name && m.provider === provider.provider)
      .length;
  }
  return isEnabled;
}

export const createModelsListFromMetadataPlatform = (
  platforms: MetadataFeedPlatformModelType[] | null,
  type: FeedType,
): ConvertedModel[] => {
  if (!platforms) return [];

  const converted: ConvertedModel[] = platforms.flatMap((provider) =>
    provider.models.map((model) => ({
      id: uidGenerator(),
      displayName: provider.providerDisplayName.toUpperCase(),
      features: model.features,
      platform: provider.provider,
      model: model.name,
      category: model.category || '',
      enabled: setDefault(model, provider, type),
      description: parseModelDescription(model.description),
      parameters: parseModelParameters(model.description),
      example: parseModelExample(model.description),
    })),
  );

  return sortPlatformModels(converted);
};

export const getModelEnabled = (model: string, platformModels: PlatformModel[]): boolean =>
  platformModels.find((platformModel) => platformModel.model === model)?.enabled ?? false;

export const getModelConfig = (model: string, platformModels: PlatformModel[]): string =>
  platformModels.find((platformModel) => platformModel.model === model)?.config || '{}';

export const createDefaultPlatformModels = (
  models: ConvertedModel[],
  platformModels: PlatformModel[],
  isCreateNewForm: boolean,
): PlatformModel[] =>
  models.map((model) => ({
    config: !isCreateNewForm ? getModelConfig(model.model, platformModels) : '{}',
    enabled: !isCreateNewForm ? getModelEnabled(model.model, platformModels) : model.enabled,
    model: model.model,
    platform: model.platform,
  }));

export const getDefaultPlatformModelsWhenCreate = (
  metadataPlatform: MetadataFeedPlatformModelType[],
  type: FeedType,
) => {
  const models = createModelsListFromMetadataPlatform(metadataPlatform, type);
  const defaultPlatformModels = createDefaultPlatformModels(models, [], true);
  return defaultPlatformModels;
};
