#!/usr/bin/env python3
"""Un pkg-config minimo per configure di ffmpeg, quando sul Mac non c'è (brew install pkgconf lo rende inutile).

Capisce --exists, --cflags, --libs, --static, --modversion e i vincoli «vpx >= 1.4.0»; cerca i .pc in PKG_CONFIG_PATH
e segue Requires (e Requires.private con --static).
"""
import os
import re
import sys


def find(name):
    for d in os.environ.get("PKG_CONFIG_PATH", "").split(":"):
        path = os.path.join(d, name + ".pc")
        if d and os.path.exists(path):
            return path
    return None


def load(name):
    path = find(name)
    if not path:
        return None
    variables, fields = {}, {}
    for raw in open(path, encoding="utf-8"):
        line = raw.split("#", 1)[0].strip()
        expand = lambda s: re.sub(r"\$\{(\w+)\}", lambda m: variables.get(m.group(1), ""), s)
        if m := re.match(r"^(\w+)\s*=\s*(.*)$", line):
            variables[m.group(1)] = expand(m.group(2))
        elif m := re.match(r"^([\w.]+)\s*:\s*(.*)$", line):
            fields[m.group(1)] = expand(m.group(2))
    return fields


def version(text):
    return [int(p) for p in re.findall(r"\d+", text)]


def requires(text):
    return [m.group(1) for m in re.finditer(r"([\w.+-]+)(\s*[<>=!]+\s*[\w.]+)?", text or "")]


def collect(name, static, seen):
    if name in seen:
        return []
    seen.add(name)
    pc = load(name)
    if pc is None:
        raise LookupError(name)
    out = [pc]
    deps = requires(pc.get("Requires")) + (requires(pc.get("Requires.private")) if static else [])
    for dep in deps:
        out += collect(dep, static, seen)
    return out


def main(argv):
    flags = [a for a in argv if a.startswith("--")]
    # configure passa anche «dav1d >= 1.0.0» come un argomento solo.
    words = [w for a in argv if not a.startswith("--") for w in a.split()]
    static = "--static" in flags
    # «vpx >= 1.4.0 opus» → [(vpx, >=, 1.4.0), (opus, None, None)]
    mods, i = [], 0
    while i < len(words):
        if i + 2 < len(words) and words[i + 1] in ("<", "<=", "=", ">=", ">", "!="):
            mods.append((words[i], words[i + 1], words[i + 2]))
            i += 3
        else:
            mods.append((words[i], None, None))
            i += 1
    try:
        pcs = []
        for name, op, want in mods:
            found = collect(name, static, set())
            if op:
                have, need = version(found[0].get("Version", "0")), version(want)
                ok = {"<": have < need, "<=": have <= need, "=": have == need,
                      ">=": have >= need, ">": have > need, "!=": have != need}[op]
                if not ok:
                    raise LookupError(f"{name} {op} {want}")
            pcs += found
    except LookupError as missing:
        if "--print-errors" in flags:
            print(f"Package {missing} was not found", file=sys.stderr)
        return 1
    if "--modversion" in flags:
        print(pcs[0].get("Version", ""))
    out = []
    if "--cflags" in flags:
        out += [f for pc in pcs for f in pc.get("Cflags", "").split()]
    if "--libs" in flags:
        out += [f for pc in pcs for f in pc.get("Libs", "").split()]
        if static:
            out += [f for pc in pcs for f in pc.get("Libs.private", "").split()]
    if out:
        print(" ".join(dict.fromkeys(out)))
    return 0


sys.exit(main(sys.argv[1:]))
