import { readFile, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import yaml from 'yaml'

const dataDir = join(process.cwd(), 'data')

const cache = new Map<string, { data: unknown; mtime: number }>()

export async function readYaml<T = unknown>(relativePath: string): Promise<T> {
  const filePath = join(dataDir, relativePath)
  const cached = cache.get(filePath)

  if (cached && Date.now() - cached.mtime < 5000) {
    return cached.data as T
  }

  const raw = await readFile(filePath, 'utf-8')
  const data = yaml.parse(raw) as T
  cache.set(filePath, { data, mtime: Date.now() })
  return data
}

export async function writeYaml(relativePath: string, data: unknown): Promise<void> {
  const filePath = join(dataDir, relativePath)
  const raw = yaml.stringify(data, { lineWidth: 120 })
  await writeFile(filePath, raw, 'utf-8')
  cache.delete(filePath)
}

export function invalidateCache(relativePath?: string): void {
  if (relativePath) {
    cache.delete(join(dataDir, relativePath))
  }
  else {
    cache.clear()
  }
}
