#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2023 Sandro Knauß <hefee@debian.org>
# SPDX-License-Identifier: LGPL-2.1-or-later

import contextlib
import json
import logging
import pathlib
import re
import subprocess

from debian import deb822, substvars

logging.basicConfig(format='%(levelname).1s: pkgkde '
                           '%(module)s:%(lineno)d: %(message)s')
log = logging.getLogger('pkgkde')

PATHS = [pathlib.Path(__file__).parent.with_name("datalib"),
         pathlib.Path('/usr/share/pkg-kde-tools/lib')
        ]

deb822_logger = logging.getLogger('debian.deb822')
REL_RAW_RE = re.compile('cannot parse package relationship ".*", returning it raw')

class DebianControl:
    """ Simple class for debian/control file.

    source: with point to the source entry in contrile file
    packages: dict with all binary packages in control file

    """
    def __init__(self, path: pathlib.Path) -> None:
        self.path = path

        self.read_path(path)

    def read_path(self, path:pathlib.Path) -> None:
        self.source = None
        self.packages = {}
        with path.open() as cl:
            for block in deb822.Deb822.iter_paragraphs(cl):
                if block.get("Source"):
                    self.source = block
                else:
                    self.packages[block.get("Package")] = block

    def isSinglePackage(self) -> bool:
        """Is there only one binary package?"""
        return len(self.packages) == 1


def active_compat_level() -> int:
    output = subprocess.check_output(["dh_assistant", "active-compat-level"])
    j = json.loads(output)
    return j["active-compat-level"]


def set_substvar(path:pathlib.Path, substvar_dict: dict):
    """ handles a debian/substvars file.

        path: path to substvars file.
        substsvars: is a dict to set key,value in the substvars file.
    """

    with substvars.Substvars.load_from_path(path, missing_ok=True) as svars:
        for var_name, values in substvar_dict.items():
            for pkg in values:
                svars.add_dependency(var_name, pkg)


def filter_rel_raw_warning(record):
    return record.levelno != logging.WARNING or not REL_RAW_RE.match(record.getMessage())


@contextlib.contextmanager
def deb822_filter_rel_raw_warning():
    deb822_logger.addFilter(filter_rel_raw_warning)
    try:
        yield
    finally:
        deb822_logger.removeFilter(filter_rel_raw_warning)
