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

import argparse
import collections
import contextlib
from dataclasses import dataclass
import itertools
import json
import logging
import os
import pathlib
import re
import subprocess
import sys
import typing
import yaml

from debian import deb822

from . import pkgkde

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

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

deb822_log_filter = contextlib.nullcontext

def deb_host_multiarch():
    try:
        return os.environ["DEB_HOST_MULTIARCH"]
    except KeyError:
        return subprocess.check_output(["dpkg-architecture", "-qDEB_HOST_MULTIARCH"]).strip().decode()


@dataclass
class QtConfig:
    """Config class to be able to switch configs for different QT versions."""
    version: str
    qmlimportscanner: str
    basepath: str

    def get_basepath(self):
        DEB_HOST_MULTIARCH = deb_host_multiarch()
        return self.basepath.format(DEB_HOST_MULTIARCH=DEB_HOST_MULTIARCH)

    @property
    def substvar_basename(self):
        return f"qml{self.version}"

    @property
    def qt_name(self):
        return f"qt{self.version}"

    def substvar_name(self, name):
        return f"{self.substvar_basename}:{name}"

def get_config():
    """Read config file and return a dict with version: QtConfig"""
    config_name = "qt_version_info.yml"
    for path in PATHS:
        p = path/config_name
        if p.exists():
            c = yaml.load(p.read_text(), yaml.BaseLoader)
            for qt_version in c:
                c[qt_version] = QtConfig(version=qt_version,**c[qt_version])
            return c

    raise FileNotFoundError(f"Did't find '{config_name}' in {PATHS}")


def iter_part_over_version(part: str, version: str):
    """ iter over version variants.

    >>> gen = iter_part_over_version("test", "1.2")
    >>> list(gen)
    ["test.1.2",
     "test.1",
     "test"
    ]
    """
    pos = None

    v = version
    while pos != -1:
        v = v[:pos]
        pos = v.rfind(".")
        yield f"{part}.{v}"
    yield part

def iter_tail(parts: list, version: str):
    """iter over all version parants of the tail part of the parts.

    >>> gen = iter_tail(["a","b"], "1")
    >>> list(gen)
    [["a.1","b.1],
     ["a.1", "b"],
     ["a", "b.1"],
     ["a", "b"]
    ]
    """

    item = parts[0]
    tail = parts[1:]
    for i in iter_part_over_version(item, version):
        if tail:
            for t in iter_tail(tail, version):
                yield[i, *t]
        else:
            yield [i,]


@dataclass
class QMLModule:
    name: str
    relpath: str
    debian_pkg: str


class QMLModules:
    """Dict of QML modules with QML module name as key and QMLModule as value."""
    def __init__(self, base_path: pathlib.Path, apt_file:bool):
        self.base_path = base_path
        self._fill_modules(apt_file)

    def _fill_modules(self, apt_file:bool):
        modules = collections.defaultdict(dict)
        try:
            output = subprocess.check_output(["dpkg-query", "-S", self.base_path/"**/qmldir"], text=True)
            for line in output.splitlines():
                package, *_ ,path = line.split(":")
                path = pathlib.Path(path.strip())
                name = self._qmlname(path)
                module = QMLModule(name, self._relpath(path), package)
                modules[module.name][module.relpath] = module
        except subprocess.CalledProcessError:
            pass

        if apt_file:
            _ = str(self.base_path/"*/qmldir")
            search_path = _.replace("*",".*")
            output = subprocess.check_output(["apt-file", "search", "-x", search_path], text=True)
            for line in output.splitlines():
                package, *_ ,path = line.split(":")
                path = pathlib.Path(path.strip())
                name = self._qmlname(path)
                module = QMLModule(name, self._relpath(path), package)
                modules[module.name][module.relpath] = module


        glob = str(self.base_path.relative_to("/")/"**/qmldir")
        for package in pkgkde.DebianControl(pathlib.Path("debian/control")).packages:
            package_path = pathlib.Path(f"debian/{package}")
            for path in package_path.glob(glob):
                # Make path abolute like it would be if installed
                path = pathlib.Path("/")/path.relative_to(package_path)
                name = self._qmlname(path)
                module = QMLModule(name, self._relpath(path), package)
                modules[module.name][module.relpath] = module

        self.modules = dict(modules)

    def _relpath(self, path: pathlib.Path):
        """strip self.basepath from path and remove the qmldir at the end."""
        parts = path.parts
        start = len(self.base_path.parts)
        end = -1 if parts[-1] == "qmldir" else None
        return "/".join(parts[start:end])

    def _qmlname(self, path: pathlib.Path):
        """tranlate a path to QML name.

        e.g. /usr/lib/x86_64-linux-gnu/qt5/qml/org/kde/kirigami.2/templates/qmldir
             -> "org.kde.kirigami.templates"
        """
        relpath = self._relpath(path)
        name = re.sub(r"(\.[0-9])+(/|$)",r"\g<2>", relpath)
        return name.replace("/",".")

    def best_matching_module(self, module_name:str, version: str):
        """the best matching QML module for a specific version.

        QML Modules can be installed in different versions e.g.

        QtQuick.Controls 2.X -> .../qml/QtQuick/Controls.2
        QtQuick.Controls 1.X -> .../qml/QtQuick/Controls

        but there is also KDE Kirigami, that does do the version different:
/MULTI
        org.kde.kirigami.templates 2.X .../kirigami.2/templates

        implements "the selection of different versions of a module in
        subdirectories of its own":

        https://doc.qt.io/qt-6/qtqml-modules-identifiedmodules.html#locally-installed-identified-modules

        """
        module_variants = self.modules[module_name]
        if len(module_variants) == 1:
               return next(iter(module_variants.values()))

        best_matching_module_path = next(i for i in iter_tail(module_name.split("."), version) if "/".join(i) in module_variants)
        return module_variants["/".join(best_matching_module_path)]


def get_overrides() -> dict[str, str]:
    """translate the qmldeps.overrides to an dict."""
    qml_overrides_path = pathlib.Path("debian/qmldeps.overrides")
    overrides = dict()
    if not qml_overrides_path.exists():
        return overrides

    for line in qml_overrides_path.read_text().splitlines():
        parts = line.split(" ")
        overrides[parts[0]] = " ".join(parts[1:])

    return overrides


def get_optional() -> dict[str, str]:
    """Translate the qmldeps.optional to an set of QML modules."""
    qml_optional_path = pathlib.Path("debian/qmldeps.optional")
    optional = dict()
    if not qml_optional_path.exists():
        return optional

    for line in qml_optional_path.read_text().splitlines():
        parts = line.split(" ")
        optional[parts[0]] = " ".join(parts[1:])

    return optional


class Status:
    """track the status.
    the failed propery tells, if the detection failed somewhere"""
    def __init__(self):
        self.failed = False

status = Status()


def detect_qml_deps_in_qmldir(qmldir: pathlib.Path, qml_modules: QMLModules) -> set[QMLModule]:
    """transform import and depends line in qmldir files to QMLModules"""
    pkgs = set()
    importline = re.compile(r"^\s*(import|depends)\s+(?P<name>[^ \t]+)(\s+(?P<version>.+))?\s*$")
    for line in qmldir.read_text().splitlines():
        if m := importline.match(line):
            name = m.group("name")
            version = m.group("version")
            if version == "auto":
                version="1"
            elif version is None:
                version="1"
            try:
                module = qml_modules.best_matching_module(name, version)
            except KeyError:
                log.error(f"Missing QML module {name}")
                status.failed = True
            else:
                pkgs.add(module.debian_pkg)
    return pkgs


def is_var_missing_in_control(pkg, var_name):
    """ Checks if ${var_name} is in Depends/Recommends/Suggests"""
    var = f"${{{var_name}}}"
    for field in ("Depends", "Recommends", "Suggests"):
        if var in pkg.get(field, ""):
            return False
    return True


def is_var_complete_demoted(pkg, var_name, fieldname):
    """ Checks if ${var_name} exists in demoted field"""
    var = f"${{{var_name}}}"
    demoted = False
    for _fieldname in ("Depends", "Recommends", "Suggests"):
        if _fieldname == fieldname:
            demoted = True
            continue
        if not demoted:
            continue
        if var in pkg.get(_fieldname, ""):
            return True
    return False



def partial_demotion(pkg, dependencies, fieldname):
    """ Remove the depenencies that are demoted in debian/control.
        This was the default behaviour for Debhelper < 14."""
    demotion = False
    demoted = False
    for _fieldname in ("Depends", "Recommends", "Suggests"):
        if _fieldname == fieldname:
            demotion = True
            continue
        if not demotion:
            continue

        if field := pkg.get(_fieldname, ""):
            with deb822_log_filter():
                field = deb822.PkgRelation.parse_relations(field)
            depends = set(i["name"] for i in itertools.chain.from_iterable(field))
            if dependencies & depends:
                log.warning(f"Detected dependencies ({dependencies&depends}) are demoted from {fieldname} to {_fieldname}. To be future proof with debhelper level 14, add -d {_fieldname} with the corresponding qml files.")
                dependencies -= depends
                demoted = True
    return demoted

def main(command_line_arguments: typing.List[str]):
    global deb822_log_filter
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-v', '--verbose', action='store_true',
        default=os.environ.get('DH_VERBOSE') == '1',
        help='turn verbose mode on')
    parser.add_argument(
        '--show', action='store_true',
        help='Show dependecies on stdout.')
    parser.add_argument(
        '-d', dest='fieldname',
        default="Depends",
        choices=['Depends', 'Recommends', 'Suggests'],
        help='Add dependencies to be added to the control file dependency field dependency-field.')
    parser.add_argument(
        '-p', '--package',
        help='package name to act on')
    parser.add_argument(
        '--qt',
        default="6",
        help='choose QT version')
    parser.add_argument(
        '--apt-file', action='store_true',
        help="use apt-file to search for QML modules")
    parser.add_argument(
        'qis', nargs='+',
        help="arguments for qmlimportscanner.")

    options, unused_args = parser.parse_known_args(command_line_arguments)

    if options.verbose:
        log.setLevel(logging.DEBUG)
        log.debug(f'{command_line_arguments=}')
        log.debug(f'{options=}')
        log.debug(f'{unused_args=}')
        deb822_log_filter = contextlib.nullcontext
    else:
        log.setLevel(logging.INFO)
        deb822_log_filter = pkgkde.deb822_filter_rel_raw_warning

    status.failed = False

    config = get_config()
    config_qt = config[options.qt]
    qml_modules = QMLModules(pathlib.Path(config_qt.get_basepath()), options.apt_file)

    # override the QML module resolution with a predefined list of Debian packages.
    for name, pkg in get_overrides().items():
        module = QMLModule(name, "override", pkg.strip())
        qml_modules.modules[name] = {"override": module}

    # If those QML modules already exists, do not modify them.
    # If not add an override with no Debian pkg.
    for name, pkg in get_optional().items():
        if name not in qml_modules.modules:
            module = QMLModule(name, "optional", pkg.strip())
            qml_modules.modules[name] = {"optional": module}

    qmlimportscanner = config_qt.qmlimportscanner
    if not pathlib.Path(qmlimportscanner).exists():
        qmlimportscanner = "debian/tmp/"+qmlimportscanner
        if not pathlib.Path(qmlimportscanner).exists():
            log.error(f"Missing {config_qt.qmlimportscanner}.")
            sys.exit(2)

    log.debug(f"Run {' '.join([qmlimportscanner, *options.qis])}")
    output = subprocess.check_output([qmlimportscanner, *options.qis])

    qmldirs = []
    mode = None
    for entry in options.qis:
        if entry.startswith("-"):
            mode = entry
        elif mode == "-rootPath":
            qmldirs.append(pathlib.Path(entry+"/qmldir"))
        elif mode == "-qmlFiles" and entry.endswith("/qmldir"):
            qmldirs.append(pathlib.Path(entry))

    pkgs = set()

    for qmldir in qmldirs:
        pkgs |= detect_qml_deps_in_qmldir(qmldir, qml_modules)

    for dep in json.loads(output):
        if dep["type"] != "module":
            continue
        name = dep.get("name")
        version = dep.get("version")

        try:
            module = qml_modules.best_matching_module(name, version)
        except KeyError:
            log.error(f"Missing QML module {name}")
            status.failed = True
        else:
            pkgs.add(module.debian_pkg)

    try:
        dc = pkgkde.DebianControl(pathlib.Path("debian/control"))
        if dc.isSinglePackage():
            pkg_name = next(iter(dc.packages.keys()))
        else:
            pkg_name = options.package
    except FileNotFoundError:
        pkg_name = None

    if not pkg_name in dc.packages:
        log.error(f"Unknown package name {pkg_name}")
        pkg_name = None
        status.failed = True

    pkgs -= set([pkg_name, ""])

    if pkg_name:
        if not pkgs:
            if not status.failed:
                log.info("No QML depedencies detected.")
                return
            else:
                sys.exit(1)

        pkg = dc.packages[pkg_name]
        if options.show:
            print("depends on:")
            print(", ".join(sorted(pkgs)))

        var_name = config_qt.substvar_name(options.fieldname)

        substvar_data = {var_name: pkgs}

        if pkgkde.active_compat_level() < 14:
            if is_var_missing_in_control(pkg, var_name):
                depends_var = config_qt.substvar_name("Depends")
                if not is_var_missing_in_control(pkg, depends_var):
                    substvar_data[depends_var] = pkgs
                    log.warning(f"{var_name} is missing in Depends/Recommends/Suggests. pkg-kde-tools >= 0.22.0 supports mutliple fields. In order to not break builds, the detected dependencies are added to {depends_var}, too.")
                else:
                    log.error(f"cannot insert qml dependency (missing {var_name} in Depends/Recommends/Suggests)")
                    status.failed = True

            if is_var_complete_demoted(pkg, var_name, options.fieldname):
                log.warning("The full demotion will not work anymore with Debhelper 14. Please use -d parameter to tell dh_qmldeps the correct dependency fieldname.")

            partial_demotion(pkg, pkgs, options.fieldname)

        substvars_path = pathlib.Path(f"debian/{pkg_name}.substvars")
        log.debug(f"{substvars_path}: add {substvar_data}")
        pkgkde.set_substvar(substvars_path, substvar_data)
    else:
        print("depends on:")
        print(", ".join(sorted(pkgs)))

    if status.failed:
        sys.exit(1)

if __name__ == '__main__':
    main(sys.argv[1:])
