import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import copy from "rollup-plugin-copy";
import * as path from 'path';
import * as fs from 'fs';
import Components from 'unplugin-vue-components/vite';

function replaceKucTagsPlugin() {
  return {
    name: 'vite-plugin-replace-tags',
    async load(id) {
      if (id.endsWith('.vue')) {
        const content = await fs.promises.readFile(id, 'utf-8');

        const usedComponent = {}

        let res = content
          .replace(/<\/kuc-([a-zA-Z0-9-]+)(?![0-9-])>/g, (match, p1) => `</kuc-${p1}-1-18-0>`)
          .replace(/<kuc-([a-zA-Z0-9-]+)(?![0-9-])([^>]*)>/g, (match, p1, p2) => {
            usedComponent[p1] = true;
            return `<kuc-${p1}-1-18-0${p2}>`
          });
        if (Object.keys(usedComponent).length) {
          let importScript = '<script lang="ts">'
          Object.keys(usedComponent).forEach((key) => {
            const keyPascal = key.split('-')
              .map(word => word.charAt(0).toUpperCase() + word.slice(1))
              .join('');
            if (key === 'multi-choice') {
              key = 'multichoice';
            }
            importScript += `import * as Kuc${keyPascal} from "kintone-ui-component/lib/${key}";`
          });
          importScript += '</script>';
          res = importScript + res;
        }

        return res;
      }
    }
  };
}

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue({
      template: {
        compilerOptions: {
          isCustomElement: (tag) => tag.startsWith("kuc-"),
        }
      }
    }),
    Components(),
    copy({
      targets: [
        { src: 'dist/index.html', dest: 'dist/src/html', rename: 'config.html' },
        { src: 'src/manifest.json', dest: 'dist/src' },
        { src: 'src/assets/*.js', dest: 'dist/src/js' },
        { src: 'src/assets/*.png', dest: 'dist/src/image' },
        { src: 'src/css/*', dest: 'dist/src/css' },
      ],
      hook: 'writeBundle' // 指定在何时复制文件
    }),
    replaceKucTagsPlugin()
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
  },
  build: {
    rollupOptions: {
      input: {
        config: path.resolve(__dirname, 'index.html'),
        desktop: path.resolve(__dirname, 'src/js/desktop.ts'),
        mobile: path.resolve(__dirname, 'src/js/mobile.ts'),
      },
      output: {
        entryFileNames: (chunkInfo) => {
           return 'src/js/[name].js'; // 默认处理为 JS 文件
        },
        assetFileNames: 'src/[ext]/[name].[ext]',
      },
    },
    sourcemap: 'inline',
  }
})
