from pathlib import Path
import re


def guess_file(path: Path) -> str:
    """Guess the type of a file and return the corresponding file extension."""
    lines = path.read_text().splitlines()

    MAX_LINES = 500  # noqa: N806

    f77ish = True
    f90ish = False

    for i, line in enumerate(lines):
        if i >= MAX_LINES:
            break

        if f77ish:
            s = line[:5]
            if (
                not re.match("^[Cc*]", s)
                and not re.match("^[ \t]*[!#]", s)
                and re.match("[^ \t0-9]", s)
            ):
                f77ish = False

        if not f90ish:
            if not re.match("^[ \t]*!", line) and re.search(
                "program|module|subroutine|function", line, re.I
            ):
                f90ish = True

    if f77ish:
        return ".f"
    elif f90ish:
        return ".f90"
    else:
        raise RuntimeError(f"can't guess the file type: {path}")