import math


def format_positional_error(
    line: int,
    pos: int,
    string: str,
    message: str,
    prior_lines: int = 3
) -> str:
    """Format a positional error generated by Scrolls.

    Args:
        line: The line the error was generated on.
        pos: The character the error was generated on.
        string: The script that generated the error.
        message: The message associated with the error.

        prior_lines: The number of lines that should be printed before the line
            the error occurred on. The line containing the error will always
            be printed.

    Returns:
        The formatted error message.

        For example:
        ```text
        ...
        1 print "World"
        2 print "Foo"
        3 print "Bar"
        4 print "bad string
                           ^
        line 4 - Unexpected EOF while parsing string literal.
        ```

        If there are more than `prior_lines` lines before the error, `...` will be
        prepended to the output.
    """
    zfill = max(1, int(math.log10(len(string))))
    lines = [f"{n:0{zfill}} {l}" for n, l in enumerate(string.splitlines())]

    printed_lines = lines[max(0, line - prior_lines): line + 1]

    output_lines = [
        *(["..."] if line - prior_lines >= 1 else []),
        *printed_lines,
        " "*(pos + 1 + zfill) + "^",
        f"line {line}: {message}"
    ]

    return "\n".join(output_lines)