# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

# src/pdftl/cli/metadata.py


def get_project_version():
    """
    Gets the project version from installed package metadata or the
    setuptools_scm generated _version.py file.
    """
    import importlib.metadata

    # 1. Try standard package metadata (Best for pip-installed users)
    try:
        return importlib.metadata.version("pdftl")
    except importlib.metadata.PackageNotFoundError:
        pass

    # 2. Fallback: Read the file generated by setuptools_scm
    # This works for local dev/editable installs where metadata might fail
    try:
        # Since help.py is in pdftl.cli, we import from the package root
        # pylint: disable=import-outside-toplevel
        from pdftl._version import version

        return version
    except ImportError:
        # _version.py might not exist if setuptools_scm hasn't run yet
        return "unknown-dev-version"


def get_dependencies_status():
    import importlib.metadata

    from packaging.requirements import Requirement

    try:
        raw_reqs = importlib.metadata.requires("pdftl") or []
    except importlib.metadata.PackageNotFoundError:
        return [], []

    required_pkgs = set()
    optional_pkgs = set()

    # We will ignore dependencies that ONLY exist for these extras
    IGNORED_GROUPS = {"dev", "docs", "test", "dev-all"}

    for req_str in raw_reqs:
        req = Requirement(req_str)

        # 1. Ignore self-references
        if req.name == "pdftl":
            continue

        # 2. Must be optional
        if not req.marker:
            required_pkgs.add(req.name)
            continue

        # 3. FILTER: Check if this requirement belongs to a "ignored" extra.
        # The marker string usually looks like: 'extra == "dev"'
        marker_str = str(req.marker)

        # If the marker explicitly restricts this to a banned group, skip it.
        # (This simplistic string check is effective for standard metadata)
        is_dev_tool = any(
            f"extra == '{g}'" in marker_str or f'extra == "{g}"' in marker_str
            for g in IGNORED_GROUPS
        )

        if is_dev_tool:
            continue

        optional_pkgs.add(req.name)

    return _get_status(required_pkgs), _get_status(optional_pkgs)


def _get_status(pkgs):
    import importlib.metadata

    # Check status of each identified package
    results = []
    for pkg in sorted(pkgs):
        try:
            ver = importlib.metadata.version(pkg)
            results.append((pkg, ver))
        except importlib.metadata.PackageNotFoundError:
            results.append((pkg, None))
    return results
