# standard
from pathlib import Path
from typing import Optional

# third party
# custom
from sunwaee.config import get_all_workspaces, get_default_workspace, get_module_dir
from sunwaee.core.fs import find_md, list_md, make_slug, read_md, write_md
from sunwaee.modules.notes.model import Note


def _resolve_dir(workspace: Optional[str]) -> tuple[str, Path]:
    workspace = workspace or get_default_workspace()
    return workspace, get_module_dir(workspace, "notes")


def _resolve_dirs(workspace: Optional[str]) -> list[tuple[str, Path]]:
    if workspace:
        return [_resolve_dir(workspace)]
    return [_resolve_dir(ws) for ws in get_all_workspaces()]


def _find_in_all(
    query: str, workspace: Optional[str]
) -> Optional[tuple[str, Path, Path]]:
    """Search for a note across workspaces. Returns (ws_name, directory, path) or None."""
    for ws, directory in _resolve_dirs(workspace):
        path = find_md(query, directory)
        if path is not None:
            return ws, directory, path
    return None


def _load(path: Path) -> Note:
    meta, body = read_md(path)
    return Note.from_dict(meta, body)


def _save(note: Note, directory: Path, path: Optional[Path] = None) -> Path:
    if path is None:
        slug = make_slug(note.title, note.id)
        path = directory / f"{slug}.md"
    write_md(path, note.to_frontmatter_meta(), note.body)
    return path


def _enrich(note: Note, workspace: str, path: Path) -> dict:
    d = note.to_dict()
    d["workspace"] = workspace
    d["path"] = str(path)
    return d
