import re
import yaml


def parse_front_matter_and_content(
    contents: list[str],
) -> tuple[dict[str, str], list[str]]:
    """
    Parse a list of all lines in a file into:
      front matter (merged result of existing ones and title + preview image)
      all markdown lines in the content apart from the recipe name
    """
    front_matter = {"title": "<unnamed>"}
    front_matter_lines = []
    markdown_content = []

    # Emulate a FSM to parse the front matter
    currently_fm = False
    for line in contents:
        if line == "---\n":
            currently_fm = not currently_fm
            continue

        if line[:2] == "# " and front_matter["title"] == "<unnamed>":
            front_matter["title"] = line[2:].strip()
            continue

        result = re.match("^!\[(.+)\]\((.+)\)", line)
        if result is not None and "previewimage" not in front_matter:
            # Take the second group
            image_url = result.group(2)
            # If there is a title ![](blah "title"), this removes it
            front_matter["previewimage"] = image_url.split(" ")[0]

        if currently_fm:
            front_matter_lines.append(line)
        else:
            markdown_content.append(line)

    try:
        # PyYAML will return None if the YAML is simply not there (zero lines)
        front_matter |= yaml.safe_load("\n".join(front_matter_lines)) or {}
    except Exception as e:
        # If there was an error parsing the YAML, there is a case the front
        # matter isn't really a front matter (like a table). In which case,
        # treat them as normal meaningful markdown content.
        meaningful_stuff = contents

    return (front_matter, markdown_content)