import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'

export interface PandaConfigResult {
	configPath: string
	cleanup: () => void
}

/**
 * Generates a temporary PandaCSS config that scans both the preview app
 * and the customer's workflow files for utility class usage.
 *
 * Uses installRoot (the parent of node_modules) as cwd so PandaCSS can
 * resolve presets by name from the correct node_modules, regardless of
 * how bun/npm hoists dependencies.
 */
export function generatePandaConfig(opts: {
	appDir: string
	workflowsDir: string
	packageRoot: string
}): PandaConfigResult {
	const tmpDir = path.join(os.tmpdir(), `pyck-preview-${process.pid}`)
	fs.mkdirSync(tmpDir, { recursive: true })

	const pandaConfigPath = path.join(tmpDir, 'panda.config.cjs')

	// installRoot is where node_modules actually lives.
	// packageRoot = /tmp/.../node_modules/@pyck/workflow-preview
	// installRoot = /tmp/.../  (or /workspace when installed as devDep)
	const installRoot = opts.packageRoot.replace(/\/node_modules\/.*$/, '')

	const pandaContent = `module.exports = {
  cwd: ${JSON.stringify(installRoot)},
  preflight: true,
  include: [
    ${JSON.stringify(`${opts.appDir}/**/*.{ts,tsx}`)},
    ${JSON.stringify(`${opts.workflowsDir}/*/web/*/*.{ts,tsx}`)},
  ],
  importMap: '@pyck/styled-system',
  jsxFramework: 'react',
  presets: ['@pandacss/preset-base', '@pandacss/preset-panda', '@pyck/panda-preset'],
}
`

	fs.writeFileSync(pandaConfigPath, pandaContent, 'utf-8')

	return {
		configPath: pandaConfigPath,
		cleanup: () => {
			fs.rmSync(tmpDir, { recursive: true, force: true })
		},
	}
}
