from typing import Iterable
import yaml


def is_myst_notebook(line_iter: Iterable[str]) -> bool:
    """Is the text file a MyST based notebook representation?"""
    # we need to distinguish between markdown representing notebooks
    # and standard notebooks.
    # Therefore, for now we require that, at a mimimum we can find some top matter
    # containing the jupytext format_name
    yaml_lines = []
    for i, line in enumerate(line_iter):
        if i == 0 and not line.startswith("---"):
            return False
        if i != 0 and (line.startswith("---") or line.startswith("...")):
            break
        yaml_lines.append(line.rstrip() + "\n")

    try:
        front_matter = yaml.safe_load("".join(yaml_lines))
    except Exception:
        return False
    if front_matter is None:  # this can occur for empty files
        return False
    if (
        front_matter.get("jupytext", {})
        .get("text_representation", {})
        .get("format_name", None)
        != "myst"
    ):
        return False

    if "name" not in front_matter.get("kernelspec", {}):
        raise IOError(
            "A myst notebook text-representation requires " "kernelspec/name metadata"
        )
    if "display_name" not in front_matter.get("kernelspec", {}):
        raise IOError(
            "A myst notebook text-representation requires "
            "kernelspec/display_name metadata"
        )
    return True