"""Exports the notes to the vault."""

from pathlib import Path

from pydantic import BaseModel


def get_note_str(note: BaseModel) -> str:
    """Gets the string representation of a note."""
    header = "---\n"
    for field in note:  # pyright: ignore[reportGeneralTypeIssues]
        name = field[0]
        value = field[1]

        if name == "content" or name == "name":
            continue

        if isinstance(value, str):
            if value.startswith("[[") and value.endswith("]]"):
                value = f"'{value}'"

        if value is None:
            value = ""

        header += f"{name}: {value}\n"

    header += "---\n"

    content = getattr(note, "content", None)

    return header + (content or "")


def export(vault: Path, notes: list[BaseModel] | BaseModel) -> None:
    """Exports the notes to the vault."""
    if not isinstance(notes, list):
        notes = [notes]

    for note in notes:
        note_str = get_note_str(note)

        name = getattr(note, "name", None)
        if name is None:
            raise ValueError("Note name is required")

        note_path = vault.joinpath(f"{name}.md")
        note_path.write_text(note_str)
