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

const dataDir = join(process.cwd(), 'site')
const runtimeDataDir = 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()
  }
}

// Runtime data — stored in data/ (Docker volume, never overwritten by deploys)

export async function readDataYaml<T = unknown>(relativePath: string, defaultValue: T): Promise<T> {
  const filePath = join(runtimeDataDir, relativePath)
  if (!existsSync(filePath)) return defaultValue
  const raw = await readFile(filePath, 'utf-8')
  return yaml.parse(raw) as T
}

export async function writeDataYaml(relativePath: string, data: unknown): Promise<void> {
  await mkdir(runtimeDataDir, { recursive: true })
  const filePath = join(runtimeDataDir, relativePath)
  const raw = yaml.stringify(data, { lineWidth: 120 })
  await writeFile(filePath, raw, 'utf-8')
}
