import { statSync } from "node:fs"
import { stat } from "node:fs/promises"

const transpiler = new Bun.Transpiler({ loader: 'tsx' })

export function css(strings: TemplateStringsArray, ...values: any[]) {
    return <style dangerouslySetInnerHTML={{
        __html: strings.reduce((result, str, i) => {
            return result + str + (values[i] || '')
        }, '')
    }} />
}

export function js(strings: TemplateStringsArray, ...values: any[]) {
    return <script dangerouslySetInnerHTML={{
        __html: strings.reduce((result, str, i) => {
            return transpiler.transformSync(result + str + (values[i] || ''))
        }, '')
    }} />
}

export function isFile(path: string): boolean {
    try {
        const stats = statSync(path)
        return stats.isFile()
    } catch {
        return false
    }
}

export function isDir(path: string): boolean {
    try {
        const stats = statSync(path)
        return stats.isDirectory()
    } catch {
        return false
    }
}

export function randomID(): string {
    return Math.random().toString(36).slice(2)
}

const transpileCache: Record<string, string> = {}
export async function transpile(path: string): Promise<string> {
    const code = await Bun.file(path).text()

    const { mtime } = await stat(path)
    const key = `${path}?${mtime}`

    let cached = transpileCache[key]
    if (!cached) {
        cached = transpiler.transformSync(code)
        transpileCache[key] = cached
    }

    return cached
}
