////
// Server state, shared by all sessions.

import { join } from "path"
import { readFileSync } from "fs"
import { NOSE_DATA } from "./config"
import { Mutex } from "./mutex"

const statePath = join(NOSE_DATA, "state.json")
const mutex = new Mutex()

export function getState(key?: string): any {
  return key ? readState()?.[key] : readState()
}

export async function setState(key: string, value: any) {
  const state = readState()
  state[key] = value
  await saveState(state)
}

export async function clearState(key: string) {
  await setState(key, undefined)
}

async function saveState(newState: any) {
  const unlock = await mutex.lock()
  try {
    await Bun.write(statePath, JSON.stringify(newState, null, 2))
  } finally {
    unlock()
  }
}

function readState(): Record<string, any> {
  try {
    return JSON.parse(readFileSync(statePath, 'utf8'))
  } catch (e: any) {
    if (e.code === "ENOENT") return {}
    throw e
  }
}
