import fs from 'fs'
import path from 'node:path'
import { colorSchemesConfig } from './color-schemes-config.ts'

const targetFile = path.resolve(__dirname, './color-schemes-config.ts')

function createStyl() {
  const stylusFile = path.resolve(__dirname, '../src/assets/stylus/color.styl')
  console.log('正在生成文件：', stylusFile)
  let colorSchemes = []
  for (let k1 in colorSchemesConfig) {
    let colors = []
    // @ts-ignore
    for (let k2 in colorSchemesConfig[k1]) {
      // @ts-ignore
      colors.push(`${k2}: ${colorSchemesConfig[k1][k2]}`)
    }
    colorSchemes.push(`  ${k1}: {\n    ${colors.join(',\n    ')}\n  }`)
  }
  const stylContent = `colorSchemes = {\n${colorSchemes.join(',\n')}\n}

`
  fs.writeFileSync(stylusFile, stylContent, {encoding: 'utf-8'})
}

function createTs() {
  const tsFile = path.resolve(__dirname, '../src/common/utils/color-schemes.ts')
  console.log('正在生成文件：', tsFile)
  let colorSchemes = []
  for (let k1 in colorSchemesConfig) {
    let colors = []
    // @ts-ignore
    for (let k2 in colorSchemesConfig[k1]) {
      // @ts-ignore
      colors.push(`${k2}: '${colorSchemesConfig[k1][k2]}'`)
    }
    colorSchemes.push(`  ${k1}: {\n    ${colors.join(',\n    ')}\n  }`)
  }
  const tsContent = `export const colorSchemes = {\n${colorSchemes.join(',\n')}\n} as const

export type ColorSchemeType = keyof typeof colorSchemes

`
  fs.writeFileSync(tsFile, tsContent, {encoding: 'utf-8'})
}

/**
 * 色系处理器
 */
export default {
  process(_: VitePluginTypes.FileWatcherProcessParam) {
    createTs()
    createStyl()
  },
  isAccept(data: VitePluginTypes.FileWatcherAcceptParam) {
    return data.event === 'change' && !data.isDir && data.filePath === targetFile
  },
} as VitePluginTypes.FileWatcherOptions
