/**
 * File system operations via Tauri invoke.
 * Falls back to in-memory stubs when running in browser (dev mode).
 */
import { invoke } from "@tauri-apps/api/core"

function isTauri(): boolean {
  return typeof window !== "undefined" && "__TAURI_INTERNALS__" in window
}

export function useFileSystem() {
  async function readFile(path: string): Promise<string> {
    if (!isTauri()) return ""
    return await invoke<string>("read_file", { path })
  }

  async function writeFile(path: string, content: string): Promise<void> {
    if (!isTauri()) return
    await invoke("write_file", { path, content })
  }

  async function listDirectory(path: string): Promise<string[]> {
    if (!isTauri()) return []
    return await invoke<string[]>("list_directory", { path })
  }

  async function createDirectory(path: string): Promise<void> {
    if (!isTauri()) return
    await invoke("create_directory", { path })
  }

  async function pathExists(path: string): Promise<boolean> {
    if (!isTauri()) return true
    try {
      await invoke("list_directory", { path })
      return true
    } catch {
      return false
    }
  }

  return { readFile, writeFile, listDirectory, createDirectory, pathExists }
}
