import path from "path";
import { promises as fs } from "fs";
import { ensureDir, readJsonFile, writeJsonFile, readTextFile, writeTextFile, deleteFileIfExists } from "../utils/fileUtils.js";
import type { NoteIndexItem, NoteContent } from "./notes.types.js";
import { config } from "../config.js";

const indexFilePath = path.join(config.NOTES_DIR, "index.json");

export async function initNotesStorage(): Promise<void> {
  await ensureDir(config.NOTES_DIR);
  const index = await readJsonFile<NoteIndexItem[]>(indexFilePath, []);
  await writeJsonFile(indexFilePath, index);
}

export async function readIndex(): Promise<NoteIndexItem[]> {
  return readJsonFile<NoteIndexItem[]>(indexFilePath, []);
}

export async function writeIndex(items: NoteIndexItem[]): Promise<void> {
  await writeJsonFile(indexFilePath, items);
}

export function getNoteFilePath(filename: string): string {
  return path.join(config.NOTES_DIR, filename);
}

export async function readNoteContent(id: string, filename: string): Promise<NoteContent> {
  const raw = await readTextFile(getNoteFilePath(filename));
  const [firstLine, ...rest] = raw.split("\n");
  const title = firstLine.replace(/^#\s*/, "").trim();
  const content = rest.join("\n").trimStart();
  return { id, title, content };
}

export async function writeNoteContent(filename: string, title: string, content: string): Promise<void> {
  const body = `# ${title}\n\n${content}`.trimEnd() + "\n";
  await writeTextFile(getNoteFilePath(filename), body);
}

export async function deleteNoteFile(filename: string): Promise<void> {
  await deleteFileIfExists(getNoteFilePath(filename));
}

export async function fileExists(filename: string): Promise<boolean> {
  try {
    await fs.access(getNoteFilePath(filename));
    return true;
  } catch (error) {
    return false;
  }
}
