#!/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

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 = []
    if qmlfiles_path.exists():
        content = qmlfiles_path.read_text()
        args = content.split()
        for arg in args:
            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

target_arch = os.getenv("DEB_TARGET_ARCH")

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:
        if "any" in archs:
            skip = False
        elif target_arch in archs:
            skip = False
        elif archs != ["all"] and not target_arch:
            log.warning(f"{pkg_name}: SKIP - set DEB_TARGET_ARCH environment variable.")

    if skip:
        continue

    for qt_version, config_qt in qt_configs.items():
        var_name = config_qt.substvar_name("Depends")
        var = f"${{{var_name}}}"
        if var in pkg.get("Depends", "") or var in pkg.get("Recomments", ""):
            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)
