#!/usr/bin/python3
# Copyright (c) 2024- Stuart Prescott <stuart@debian.org>
# Released under the same terms as QtPy
"""
Build the Depends/Recommends for each of the API packages based on the
Build-Depends that are in the package. This is done to save repeating the
package names in multiple places.

Build-Depends used unconditionally are added to Depends
Build-Depends that are arch-specific are added to Recommends

The packages are listed in the debian/foo.substvars files so that they are
then picked when the binary packages are created.
"""
# pylint: disable=invalid-name

import re
from typing import Any, Optional

from debian.deb822 import Deb822, _PkgRelationMixin
from debian.substvars import Substvars


class DControl(Deb822, _PkgRelationMixin):
    """Class for debian/control file"""

    _relationship_fields = [
        "build-depends",
        "depends",
        "recommends",
    ]

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        Deb822.__init__(self, *args, **kwargs)
        _PkgRelationMixin.__init__(self, *args, **kwargs)


header: Optional[DControl] = None
binaries: list[DControl] = []

with open("debian/control", encoding="UTF-8") as fh:
    for para in DControl.iter_paragraphs(fh):
        if not header:
            header = para
            continue
        binaries.append(para)

assert header is not None


bds = header.relations["build-depends"]
assert bds is not None

package_re = re.compile(r"python3-qtpy-(.*)")

for b in binaries:
    package = b["Package"]
    m = package_re.match(package)
    if not m:
        continue
    api = m.group(1)
    print(f"Processing {package} for {api}")

    deps = []
    recs = []
    for d in bds:
        if api in d[0]["name"]:
            if d[0]["arch"]:
                recs.append(d[0]["name"])
            else:
                deps.append(d[0]["name"])

    svars = Substvars()
    svars.add_dependency("qtpy:Depends", ", ".join(deps))
    svars.add_dependency("qtpy:Recommends", ", ".join(recs))

    with open(f"debian/{package}.substvars", "w", encoding="UTF-8") as fh:
        svars.write_substvars(fh)
