import { readTextFile, writeTextFile } from "@tauri-apps/api/fs";
import { parse, stringify } from "smol-toml";

export const readTomlFile = async <T>(path: string): Promise<T | null> => {
  try {
    const contents = await readTextFile(path);
    return parse(contents) as T;
  } catch (error) {
    console.error(`Failed to read JSON file ${path}: ${error}`);
    throw new Error(`Failed to read JSON file ${path}: ${error}`);
  }
};

export const writeTomlFile = async <T>(path: string, data: T): Promise<void> => {
  try {
    const tomlString = stringify(data);
    await writeTextFile(path, tomlString);
  } catch (error) {
    console.error(`Error writing file ${path}: ${error}`);
    throw new Error(`Error writing file ${path}: ${error}`);
  }
};
