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

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

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