from collections import Counter
from pathlib import Path
import sys


def error_lines(path):
    """Yield each line in the log that reports an ERROR."""
    for line in Path(path).read_text(encoding="utf-8").splitlines():
        if "ERROR" in line:
            yield line


def summarize(path):
    lines = list(error_lines(path))
    # The message is everything after the word ERROR.
    messages = [line.split("ERROR", 1)[1].strip() for line in lines]
    return lines, Counter(messages)


def main():
    if len(sys.argv) < 2:
        print("Usage: python summarize_log.py <logfile>")
        raise SystemExit(1)

    path = Path(sys.argv[1])
    try:
        lines, counts = summarize(path)
    except FileNotFoundError:
        print(f"No such file: {path}")
        raise SystemExit(1)

    Path("errors.txt").write_text("\n".join(lines), encoding="utf-8")

    print(f"{len(lines)} errors found")
    for message, number in counts.most_common():
        print(f"{number}x {message}")


if __name__ == "__main__":
    main()
