#!/usr/bin/env python3
"""Checks package in `~/packages` against dependencies in `pyproject.toml` files."""

from pathlib import Path
from subprocess import run

from libcli.basecli import BaseCLI
from tomli import loads


class CheckPackageCLI(BaseCLI):
    """Docstring."""

    def init_parser(self) -> None:
        """Docstring."""

        self.ArgumentParser(description=__doc__)

    def add_arguments(self) -> None:
        """Docstring."""

        self.parser.add_argument(
            "PKGNAME",
            help="Name of package to check.",
        )
        self.parser.add_argument(
            "TOML",
            type=Path,
            nargs="+",
            help="List of toml files to check.",
        )

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

        # Search the `~/packages` directory for files whose name contains `PKGNAME`.
        # Sort them by name (which should also be chronological).
        # Run `ls -l` on them.

        pkgdir = Path("~/packages").expanduser()
        pkgname = self.options.PKGNAME
        pkgfiles = list(pkgdir.glob(f"*{pkgname}*"))

        print(f"{' ' + pkgname:->80}")

        if len(pkgfiles) > 0:
            run(["/bin/ls", "-ltr", *pkgfiles], check=True)
            # print("-" * 20)

        # Check toml files.

        for file in self.options.TOML:
            doc = loads(file.read_text(encoding="utf-8"))

            try:
                name = doc["project"]["name"]
            except KeyError:
                self.error(f"{file} has no `project.name`")
                continue

            if name == pkgname or name.endswith("-" + pkgname):
                # `file` is the pyproject.toml for the package itself.

                dist = file.parent.glob("dist/*.whl")
                run(["/bin/ls", "-ltr", *dist], check=True)
                print("-" * 20)

                try:
                    version = doc["project"]["version"]
                    run(["/bin/ls", "-ltr", file], check=True)
                    print(f"project.version={version!r}", file)
                    print("-" * 20)
                except KeyError:
                    self.error(f"{file} has no `project.version`")
                    continue
            else:
                # `file` is the pyproject.toml of what may be a dependent package.
                try:
                    dependencies = doc["project"]["dependencies"]
                except KeyError:
                    self.error(f"{file} has no `project.dependencies`")
                    continue

                for dep in dependencies:
                    if pkgname in dep:
                        print(dep, file.parent.name.ljust(10), self.hideuser(file))


def main() -> None:
    """CLI entry point."""

    CheckPackageCLI().main()


if __name__ == "__main__":
    main()
