import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'

import { emitRootTokensCss } from '../packages/shared/src/design-tokens.ts'

const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const outputPath = resolve(repoRoot, 'apps/desktop/src/renderer/styles/generated/design-tokens.css')

function generatedCss() {
  return [
    '/* Generated by scripts/generate-design-token-css.ts from packages/shared/src/design-tokens.ts. Do not edit. */',
    emitRootTokensCss(),
    '',
  ].join('\n')
}

const next = generatedCss()

if (process.argv.includes('--check')) {
  const current = existsSync(outputPath) ? readFileSync(outputPath, 'utf8') : ''
  if (current !== next) {
    throw new Error(`Generated design token CSS is stale. Run "pnpm design-tokens:build" to update ${outputPath}.`)
  }
} else {
  mkdirSync(dirname(outputPath), { recursive: true })
  writeFileSync(outputPath, next)
}
