/**
 * Persists synthesised `.drive.jsonl` content to on-device storage, ready
 * to hand to `GuidanceOptions.source = { kind: "replay", corpusPath }`
 * (MapmapNav.types.ts).
 *
 * Uses `expo-file-system`'s SDK 57 "next" API (`File`/`Directory`/`Paths`) —
 * the legacy `FileSystem.writeAsStringAsync` API was replaced in this SDK.
 */
import { Directory, File, Paths } from "expo-file-system";

const CORPUS_DIRECTORY_NAME = "drive-corpora";

let corpusSequence = 0;

function corpusFileName(): string {
  corpusSequence += 1;
  return `${Date.now()}-${corpusSequence}.drive.jsonl`;
}

/**
 * Writes `content` (as produced by `synthesizeDriveCorpus`) to a new file
 * under the app's document directory and returns its absolute `file://`
 * URI — the same string `GuidanceOptions.source.corpusPath` expects.
 */
export async function writeCorpusToFile(content: string): Promise<string> {
  const directory = new Directory(Paths.document, CORPUS_DIRECTORY_NAME);
  if (!directory.exists) {
    directory.create({ intermediates: true, idempotent: true });
  }

  const file = new File(directory, corpusFileName());
  file.create({ intermediates: true, overwrite: true });
  file.write(content);

  return file.uri;
}
