import type { Plugin } from 'vite'
import fs from 'fs'
import prettier from 'prettier'

// uni-app
import uni from '@dcloudio/vite-plugin-uni'
// @dcloudio/uni-helper-json
import tags from '@dcloudio/uni-helper-json/dist/tags.json'

/**
 * 根据 @dcloudio/uni-helper-json 生成组件 .d.ts 描述文件，对组件进行高亮展示
 */
function generateUniComponentsTypes() {
    const components = Object.keys(tags).map((key) => `'${key}': typeof HTMLElement`)
    const content = `
        // generated by @dcloudio/uni-helper-json/dist/tags.json

        declare module 'vue' {
            // uni-app 内置组件高亮
            export interface GlobalComponents {
                ${components.join(',\n\t')}
            }
        }
        export {}
    `

    const formatted = prettier.format(content, {
        parser: 'typescript',
        ...require('../../prettier.config'),
    })
    fs.writeFileSync('./types/uni-components.d.ts', formatted, 'utf8')
}

/**
 * uni-app
 * @returns Plugin[]
 */
export function configUniPlugin(): Plugin[] {
    // 生成 uni-components.d.ts
    generateUniComponentsTypes()
    return uni()
}
