import bundledCollection from "./definitions/default.json";
import type { DefinitionCollection, Settings, SiteDefinition } from "../shared/types";

export const BUNDLED_COLLECTION = bundledCollection as DefinitionCollection;
export const BUILTIN_DEFINITIONS: SiteDefinition[] = BUNDLED_COLLECTION.definitions;

export function effectiveDefinitions(settings: Pick<Settings, "customDefinitions" | "disabledDefinitionIds" | "subscriptions" | "subscriptionCollections"> | SiteDefinition[], legacyDisabledDefinitionIds?: string[]): SiteDefinition[] {
  if (Array.isArray(settings)) settings = { customDefinitions: settings, disabledDefinitionIds: legacyDisabledDefinitionIds ?? [], subscriptions: [], subscriptionCollections: [] };
  const byId = new Map<string, SiteDefinition>();
  const orderedSubscriptions = [...settings.subscriptions]
    .filter((subscription) => subscription.enabled)
    .sort((a, b) => a.priority - b.priority || a.id.localeCompare(b.id));
  const collections = new Map(settings.subscriptionCollections.map((collection) => [collection.collectionId, collection]));
  for (const subscription of orderedSubscriptions) {
    for (const definition of collections.get(subscription.id)?.definitions ?? []) {
      if (!byId.has(definition.id)) byId.set(definition.id, definition);
    }
  }
  for (const definition of BUILTIN_DEFINITIONS) if (!byId.has(definition.id)) byId.set(definition.id, definition);
  for (const definition of settings.customDefinitions) byId.set(definition.id, definition);
  const disabled = new Set(settings.disabledDefinitionIds);
  return [...byId.values()].filter((definition) => !disabled.has(definition.id));
}
