from pathlib import Path
from typing import Optional

import frontmatter
from slugify import slugify

from sunwaee.core.logger import get_logger

_log = get_logger("core.fs")


def make_slug(title: str, fallback_id: str) -> str:
    s = slugify(title)
    return s if s else fallback_id


def write_md(path: Path, metadata: dict, body: str) -> None:
    _log.debug("Writing %s", path)
    post = frontmatter.Post(body, **metadata)
    path.parent.mkdir(parents=True, exist_ok=True)
    with open(path, "wb") as f:
        frontmatter.dump(post, f)


def read_md(path: Path) -> tuple[dict, str]:
    _log.debug("Reading %s", path)
    post = frontmatter.load(str(path))
    return dict(post.metadata), post.content


def list_md(directory: Path) -> list[Path]:
    if not directory.exists():
        return []
    return sorted(directory.glob("*.md"), key=lambda p: p.stat().st_mtime, reverse=True)


def find_md(query: str, directory: Path) -> Optional[Path]:
    """Find a markdown file by id, slug (filename stem), or title (case-insensitive)."""
    _log.debug("Searching for %r in %s", query, directory)
    for path in list_md(directory):
        meta, _ = read_md(path)
        if meta.get("id") == query:
            return path
        if path.stem == query:
            return path
        if meta.get("title", "").lower() == query.lower():
            return path
    _log.debug("No match found for %r in %s", query, directory)
    return None


def search_md(query: str, directory: Path) -> list[Path]:
    """Return files where query appears in title, tags, or body."""
    q = query.lower()
    results = []
    for path in list_md(directory):
        meta, body = read_md(path)
        if (
            q in meta.get("title", "").lower()
            or q in body.lower()
            or any(q in tag.lower() for tag in meta.get("tags", []))
        ):
            results.append(path)
    return results
