import fs from 'node:fs'
import type { Plugin } from 'vite'
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 描述文件，对组件进行高亮展示
 */
async function generateUniComponentsTypes() {
    const components = Object.keys(tags).map((key) => `'${key}': UniComponent`)
    const content = `
        // generated by @dcloudio/uni-helper-json/dist/tags.json

        declare module 'vue' {
            // shime-uni.d.ts
            type Hooks = App.AppInstance & Page.PageInstance;
            type ComponentCustomOptions = Hooks

            // uni-app components
            interface UniComponent {
                [key in string]: any
            }
            export interface GlobalComponents {
                ${components.join(',\n\t')}
            }
        }
        export {}
    `

    const formatted = await prettier.format(content, {
        parser: 'typescript',
        // eslint-disable-next-line @typescript-eslint/no-require-imports
        ...require('../../prettier.config'),
    })
    fs.writeFileSync('./types/uni.d.ts', formatted, 'utf8')
}

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