#!/usr/bin/env python3
"""Print items in `toml` file."""

from argparse import ArgumentParser
from pathlib import Path

from rich.pretty import pprint
from tomli import loads


def main() -> None:
    """Docstring."""

    parser = ArgumentParser(description=__doc__)
    parser.add_argument(
        "--file",
        type=Path,
        default="pyproject.toml",
        help="Path to toml file to read (default: `%(default)s`).",
    )
    parser.add_argument("KEY", nargs="*", help="List of keys to data items.")
    args = parser.parse_args()

    if len(args.KEY) == 1 and "." in args.KEY[0]:
        args.KEY = args.KEY[0].split(".")

    try:
        doc = loads(args.file.read_text(encoding="utf-8"))
    except FileNotFoundError as e:
        parser.exit(2, f"{e}\n")

    for key in args.KEY:
        try:
            doc = doc[key]
        except KeyError:
            parser.exit(2, f"[KeyError] No such key: {key!r}\n")

    if isinstance(doc, str):
        print(doc)
    elif isinstance(doc, list):
        for line in doc:
            print(line)
    else:
        pprint(doc)


if __name__ == "__main__":
    main()
