"""Read-only reference for the AI Power Progressia Python mini-project.

Run: python3 word_count.py notes.txt
Counts whitespace-separated words, not linguistic tokens. UTF-8 files up to 1 MiB.
"""

import argparse
from pathlib import Path

MAX_BYTES = 1024 * 1024


def count_words(text: str) -> int:
    return len(text.split())


def count_file(path: Path) -> int:
    if not path.is_file():
        raise ValueError("Choose an existing regular text file.")
    with path.open("rb") as source:
        content = source.read(MAX_BYTES + 1)
    if len(content) > MAX_BYTES:
        raise ValueError("File exceeds the 1 MiB practice limit.")
    return count_words(content.decode("utf-8"))


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("path", type=Path)
    args = parser.parse_args()
    try:
        print(count_file(args.path))
        return 0
    except (OSError, UnicodeError, ValueError) as error:
        parser.exit(1, f"Unable to count words: {error}\n")


if __name__ == "__main__":
    raise SystemExit(main())
