// Copyright 2017-2025 @pezkuwi/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0

import type { Metadata } from '@pezkuwi/types/metadata/Metadata';
import type { Definitions } from '@pezkuwi/types/types';
import type { HexString } from '@pezkuwi/util/types';

import Handlebars from 'handlebars';

import * as defaultDefs from '@pezkuwi/types/interfaces/definitions';
import lookupDefinitions from '@pezkuwi/types-augment/lookup/definitions';
import { stringCamelCase } from '@pezkuwi/util';

import { compareName, createImports, formatType, initMeta, readTemplate, rebrandTypeName, setImports, writeFile } from '../util/index.js';
import { ignoreUnusedLookups } from './lookup.js';
import { type ExtraTypes, getDeprecationNotice } from './types.js';

const generateForMetaTemplate = Handlebars.compile(readTemplate('consts'));

/** @internal */
function generateForMeta (meta: Metadata, dest: string, extraTypes: ExtraTypes, isStrict: boolean, customLookupDefinitions?: Definitions): void {
  writeFile(dest, (): string => {
    const allTypes = {
      '@pezkuwi/types-augment': {
        lookup: {
          ...lookupDefinitions,
          ...customLookupDefinitions
        }
      },
      '@pezkuwi/types/interfaces': defaultDefs,
      ...extraTypes
    };
    const imports = createImports(allTypes);
    const allDefs = Object.entries(allTypes).reduce((defs, [path, obj]) => {
      return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [`${path}/${key}`]: value }), defs);
    }, {});
    const { lookup, pallets, registry } = meta.asLatest;
    const usedTypes = new Set<string>([]);

    const modules = pallets
      .filter(({ constants }) => constants.length > 0)
      .map(({ constants, name }) => {
        if (!isStrict) {
          setImports(allDefs, imports, ['Codec']);
        }

        const items = constants
          .map(({ deprecationInfo, docs, name, type }) => {
            const typeDef = lookup.getTypeDef(type);
            const returnType = rebrandTypeName(typeDef.lookupName || '') || formatType(registry, allDefs, typeDef, imports);

            if (!deprecationInfo.isNotDeprecated) {
              const deprecationNotice = getDeprecationNotice(deprecationInfo, stringCamelCase(name), 'Constant');

              const items = docs.length
                ? ['', deprecationNotice]
                : [deprecationNotice];

              docs.push(...items.map((text) => registry.createType('Text', text)));
            }

            // Add the type to the list of used types
            if (!(imports.primitiveTypes[returnType])) {
              usedTypes.add(returnType);
            }

            setImports(allDefs, imports, [returnType]);

            return {
              docs,
              name: stringCamelCase(name),
              type: returnType
            };
          })
          .sort(compareName);

        return {
          items,
          name: stringCamelCase(name)
        };
      })
      .sort(compareName);

    // filter out the unused lookup types from imports
    ignoreUnusedLookups([...usedTypes], imports);

    return generateForMetaTemplate({
      headerType: 'chain',
      imports,
      isStrict,
      modules,
      types: [
        ...Object.keys(imports.localTypes).sort().map<{ file: string; types: string[] }>((packagePath) => ({
          file: packagePath.replace('@pezkuwi/types-augment', '@pezkuwi/types'),
          types: Object.keys(imports.localTypes[packagePath])
        })),
        {
          file: '@pezkuwi/api-base/types',
          types: ['ApiTypes', 'AugmentedConst']
        }
      ]
    });
  });
}

// Call `generateForMeta()` with current static metadata
/** @internal */
export function generateDefaultConsts (dest: string, data: HexString, extraTypes: ExtraTypes = {}, isStrict = false, customLookupDefinitions?: Definitions): void {
  const { metadata } = initMeta(data, extraTypes);

  return generateForMeta(metadata, dest, extraTypes, isStrict, customLookupDefinitions);
}
