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

import logging
import os
import pathlib
import subprocess
import sys
import typing

from debian.debian_support import DpkgArchTable

PKGKDE_GETQMLDEPENDS = "pkgkde-getqmldepends"

sys.path.insert(0,'/usr/share/pkg-kde-tools')
parent_path = pathlib.Path(__file__).parent.absolute()
if parent_path not in ("/usr/bin", "/bin"):
    sys.path.insert(0, str(parent_path))
    PKGKDE_GETQMLDEPENDS = parent_path/"pkgkde-getqmldepends"

from pythonlib import qmldeps

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

log = logging.getLogger()
log.setLevel(logging.INFO)

def qmlfiles_args(pkg_name: str) -> list[str | pathlib.Path]:
    qmlfiles_path = pathlib.Path(f"debian/{pkg_name}.qmlfiles")
    ret = []
    multiarch = qmldeps.deb_host_multiarch()
    if qmlfiles_path.exists():
        content = qmlfiles_path.read_text()
        args = content.split()
        for arg in args:
            if "${DEB_HOST_MULTIARCH}" in arg:
                arg = arg.replace("${DEB_HOST_MULTIARCH}", multiarch)

            if "*" in arg:
                ret.extend(pathlib.Path().glob(arg))
            else:
                ret.append(arg)
    return ret

def qt_version_from_files(files: list[str|pathlib.Path]) -> typing.Optional[str]:
    qt_version = None
    for path in files:
        if qt_version:
            break
        if not isinstance(path, pathlib.Path):
            continue
        if not qt_version:
            for p, ver in qt_versions.items():
                if p in path.parts:
                    qt_version = ver
                    break
    return qt_version



qt_configs = qmldeps.get_config()
qt_versions = {i.qt_name: k for k,i in qt_configs.items()}
control = qmldeps.DebianControl(pathlib.Path("debian/control"))
single_pkg = control.isSinglePackage()

failed = False

getqmldepends_glob_args = sys.argv[1:]

arch_any = "-a" in getqmldepends_glob_args
arch_all = "-i" in getqmldepends_glob_args

try:
    host_arch = os.environ["DEB_HOST_ARCH"]
except KeyError:
    host_arch = subprocess.check_output(["dpkg-architecture", "-qDEB_HOST_ARCH"]).strip().decode()

archtable = DpkgArchTable.load_arch_table()

if not arch_any and not arch_all:
    arch_any = True
    arch_all = True

for pkg_name, pkg in control.packages.items():
    archs =  pkg.get("Architecture", "").split()

    skip = True
    if archs == []:
        skip = False
    elif arch_all and "all" in archs:
        skip = False
    elif arch_any and any(archtable.matches_architecture(host_arch, arch) for arch in archs):
        skip = False

    if skip:
        continue

    for qt_version, config_qt in qt_configs.items():
        var_name = config_qt.substvar_name("Depends")
        var = f"${{{var_name}}}"
        for field in ("Depends", "Recommends", "Suggests"):
            if var in pkg.get(field, ""):
                break
        else:
            continue
        break
    else:
        qt_version = None

    extra_args = qmlfiles_args(pkg_name)

    if not extra_args:
        root_path = list(p.parent for p in pathlib.Path(f"debian/{pkg_name}").glob("**/qmldir"))
        if root_path:
            extra_args = ["-rootPath"] + root_path

    if not extra_args:
        files = list(pathlib.Path(f"debian/{pkg_name}").glob("**/*.qml"))
        if single_pkg and not files:
            files = list(pathlib.Path(".").glob("**/*.qml"))
        if files:
            extra_args = ["-qmlFiles"] + files

    if extra_args:
        if not qt_version:
            qt_version = qt_version_from_files(extra_args)
        cmd = [PKGKDE_GETQMLDEPENDS]
        cmd.extend(getqmldepends_glob_args)

        cmd.extend(["-p", pkg_name])
        if qt_version:
            cmd.extend(["--qt", qt_version])

        cmd.append("--")
        cmd.extend(extra_args)

        log.info(f"Execute {' '.join(str(i) for i in cmd)}")
        try:
            subprocess.check_call(cmd)
        except subprocess.CalledProcessError as e:
            log.error(f"{PKGKDE_GETQMLDEPENDS} failed with {e.returncode}.")
            failed = True
    elif qt_version or single_pkg:
        log.error(f"{pkg_name}: No automatic qml files found for package you need to add the files by hand to debian/{pkg_name}.qmlfiles")

if failed:
    sys.exit(1)
