import { readdirSync } from 'fs';
import summary from 'rollup-plugin-summary';
import { terser } from 'rollup-plugin-terser';
import resolve from '@rollup/plugin-node-resolve';
import replace from '@rollup/plugin-replace';
import typescript from '@rollup/plugin-typescript';
import { getBabelOutputPlugin } from '@rollup/plugin-babel';
import glob from 'glob';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
import commonjs from '@rollup/plugin-commonjs';
import styles from 'rollup-plugin-styles';

const require = createRequire(import.meta.url);
const pkg = require('./package.json');

const { LERNA_PACKAGE_NAME } = process.env;
const PACKAGE_ROOT_PATH = process.cwd();

export default [
  // ------------------------------------------------------------------------
  // 1) Monorepo build: glob all .ts under /src → per-file ESM + legacy SystemJS
  // ------------------------------------------------------------------------
  {
    input: Object.fromEntries(
      glob.sync('src/**/*.ts', {
        ignore: [
          '**/*.test.ts',
          '**/*.spec.ts',
          '**/__tests__/**'
        ]
      }).map(file => [
        path
          .relative('src', file)
          .slice(0, -path.extname(file).length),
        fileURLToPath(new URL(file, import.meta.url)),
      ])
    ),
    external: ['tslib', 'lit', /^lit\/.*/],
    output: [
      {
        format: 'es',
        chunkFileNames: '[name]-[hash].esm.js',
        entryFileNames: '[name].esm.js',
        dir: 'dist',
        sourcemap: false,
      },
      {
        format: 'esm',
        chunkFileNames: '[name]-[hash].cjs.js',
        entryFileNames: '[name].cjs.js',
        dir: 'dist',
        sourcemap: true,
        plugins: [
          getBabelOutputPlugin({
            compact: true,
            presets: [
              [
                '@babel/preset-env',
                { modules: 'systemjs' },
              ],
            ],
          }),
        ],
      },
    ],
    preserveEntrySignatures: false,
    onwarn(warning) {
      if (warning.code !== 'THIS_IS_UNDEFINED') {
        console.error(`(!) ${warning.message}`);
      }
    },
    plugins: [
      typescript(),
      replace({
        'Reflect.decorate': 'undefined',
        'process.env.NODE_ENV': JSON.stringify('production'),
        'process.env.LIT_DEV_MODE': JSON.stringify('false'),
      }),
      resolve(),
      commonjs(),
      terser({
        ecma: 2017,
        module: true,
        warnings: true,
        mangle: { properties: { regex: /^__/ } },
      }),
      styles(),
      summary(),
    ],
  },

  // ------------------------------------------------------------------------
  // 2) Single-entry build: src/index.ts → dist/index.js + types
  // ------------------------------------------------------------------------
  {
    input: 'src/index.ts',
    output: {
      file: 'dist/index.js',
      format: 'es',
      sourcemap: false,
      inlineDynamicImports: true,
    },
    external: [],
    plugins: [
      replace({
        preventAssignment: true,
        __NILE_ELEMENTS_VERSION__: JSON.stringify(pkg.version),
      }),
      resolve(),
      commonjs(),
      typescript({
        tsconfig: './tsconfig.json',
        declaration: true,
        declarationDir: 'dist/types',
      }),
      terser(),
    ],
  },
];
