"""Tag-based frontmatter query for memory files."""

from __future__ import annotations

from pathlib import Path

import yaml

from supermemory.config import memory_root


SEARCH_DIRS = ["systems", "decisions", "gotchas", "research", "people"]


def parse_frontmatter(filepath: Path) -> dict | None:
    """Extract YAML frontmatter from a markdown file."""
    try:
        text = filepath.read_text()
    except (OSError, UnicodeDecodeError):
        return None

    if not text.startswith("---"):
        return None

    end = text.find("---", 3)
    if end == -1:
        return None

    try:
        return yaml.safe_load(text[3:end]) or {}
    except yaml.YAMLError:
        return None


def query(
    system: str | None = None,
    concern: str | None = None,
    root: Path | None = None,
) -> list[dict]:
    """Query memory files by system and/or concern tags.

    Returns list of dicts with 'path', 'frontmatter', and 'type' keys.
    """
    root = root or memory_root()
    results = []

    for dirname in SEARCH_DIRS:
        search_dir = root / dirname
        if not search_dir.is_dir():
            continue

        for f in sorted(search_dir.glob("*.md")):
            if f.name.startswith("_"):
                continue

            fm = parse_frontmatter(f)
            if fm is None:
                continue

            if not _matches(fm, system, concern):
                continue

            results.append({
                "path": str(f.relative_to(root)),
                "frontmatter": fm,
                "type": dirname,
            })

    return results


def _matches(fm: dict, system: str | None, concern: str | None) -> bool:
    """Check if frontmatter matches the given filters."""
    if system is None and concern is None:
        return True

    tags = fm.get("tags", []) or []
    systems = fm.get("systems", []) or []
    all_tags = set(tags) | set(systems)

    if system and concern:
        return system in all_tags and concern in all_tags
    if system:
        return system in all_tags
    if concern:
        return concern in all_tags

    return True


def format_results(results: list[dict]) -> str:
    """Format query results as readable markdown."""
    if not results:
        return "No matching memory files found."

    lines = [f"Found {len(results)} matching file(s):\n"]
    for r in results:
        fm = r["frontmatter"]
        tags = fm.get("tags", []) or []
        lines.append(f"- **{r['path']}** [{r['type']}] tags: {', '.join(str(t) for t in tags)}")

    return "\n".join(lines)
