# -*- coding: utf-8 -*-

"""
Call as script
"""

import argparse
import importlib.metadata
import pathlib
import sys

from . import Structure

if sys.version_info >= (3, 11):
    import tomllib
else:
    import tomli as tomllib
#


_PACKAGE_NAME = "ncw"
_INFO_TEXT = """This package does not have a useful commandline interface;
programs like jq and yq offer much more sophisticated functionality
for shell environments, and we do not intend to re-invent the wheel.

Package documentation is available at https://blackstream-x.gitlab.io/ncw/"""


def get_file_contents(file_name: str, up_dirs: int = 0) -> str:
    """get contents of a file in an ancestor directory
    of the current file (up_dirs directory levels up)
    """
    file_dir_path = pathlib.Path(__file__).resolve()
    for _ in range(up_dirs):
        file_dir_path = file_dir_path.parent
    #
    file_path = file_dir_path / file_name
    return file_path.read_text(encoding="utf-8")


def get_metadata_version(
    metadata_file_name: str = "pyproject.toml", up_dirs: int = 3
) -> str:
    """get version information from metadata_file up_dirs directories above"""
    try:
        metadata_file_contents = get_file_contents(metadata_file_name, up_dirs=up_dirs)
    except IOError as error:
        return str(error)
    #
    metadata = Structure(tomllib.loads(metadata_file_contents))
    try:
        version = metadata["project.version"]
    except KeyError:
        return f"Error: no version information in metadata from {metadata_file_name}"
    #
    return f"{version} (read directly from {metadata_file_name})"


def main() -> None:
    """Script fuction autogenerated by uv, might delete later"""
    try:
        version = importlib.metadata.version(_PACKAGE_NAME)
    except importlib.metadata.PackageNotFoundError:
        version = get_metadata_version()
    #
    argument_parser = argparse.ArgumentParser(
        prog="ncw", description="Nested collections wrapper"
    )
    argument_parser.add_argument("--version", action="version", version=version)
    argument_parser.parse_args()
    print(_INFO_TEXT)


if __name__ == "__main__":
    main()  # not testable

# vim: fileencoding=utf-8 ts=4 sts=4 sw=4 autoindent expandtab syntax=python:
