import os.path
import subprocess
import collections

from .policy import ALLOWED_LICENSES, IGNORED_PACKAGES, IGNORED_CI_REQUIREMENTS

LicenceCheckResult = collections.namedtuple("LicenceCheckResult", ["ok", "msg"])


def check_policy_js():
    if os.path.isfile("package.json"):
        all_allowed_licenses = "; ".join(ALLOWED_LICENSES)
        all_ignored_packages = ";".join(IGNORED_PACKAGES)

        try:
            output = subprocess.check_output(
                [
                    "npx",
                    "license-checker",
                    "--production",
                    "--excludePackages",
                    all_ignored_packages,
                    "--onlyAllow",
                    all_allowed_licenses,
                ],
                stderr=subprocess.STDOUT,
            )
            return LicenceCheckResult(True, output.decode())
        except subprocess.CalledProcessError as e:
            msg = (
                b"Some javascript dependencies contain licenses not allowed by the policy: %i %s"
                % (e.returncode, e.output)
            )
            return LicenceCheckResult(False, msg.decode())


def check_policy(ignore_ci=True):
    all_allowed_licenses = ";".join(ALLOWED_LICENSES)
    all_ignored_packages = IGNORED_PACKAGES
    if ignore_ci:
        all_ignored_packages += IGNORED_CI_REQUIREMENTS

    output = b"No violations where found"

    try:
        output = subprocess.check_output(
            [
                "pip-licenses",
                "--allow-only",
                all_allowed_licenses,
                "--ignore-packages",
                *all_ignored_packages,
                "--collect-all-failures",
            ],
            stderr=subprocess.STDOUT,
        )
    except subprocess.CalledProcessError as e:
        msg = (
            b"Some python dependencies contain licenses not allowed by the policy: \n %s"
            % e.output
        )
        return LicenceCheckResult(False, msg.decode())

    return LicenceCheckResult(True, output.decode())
