#!/usr/bin/env python3
"""Drop vendor-tree prebuilt modules that duplicate hardware/samsung source.

On lineage-24.0 the Exynoobs 23.2 vendor trees prebuild modules that Lineage's
own hardware/samsung also builds from source, and Soong aborts the build with
"found in multiple namespaces ... when including in vendor partition" (real
failure: libsamsungSoundbooster_plus, b5q, 2026-10-11; hermesd,
sm8550-common). hardware/samsung is the official LineageOS tree, so the vendor
prebuilt is the copy that goes.

Applied by tools/apply.sh after every `repo sync` (the trees re-arrive pinned
and pristine). Anchored and idempotent like device/uprev.py: if the name is
gone the file is left alone; if the name is present but not as the expected
module type, the run fails loudly instead of guessing.
"""
import argparse
import os
import re
import sys

# (path under the source root, module type, module name)
CLASHES = [
    ("vendor/samsung/b5q/Android.bp", "cc_prebuilt_library_shared",
     "libsamsungSoundbooster_plus"),
    ("vendor/samsung/sm8550-common/Android.bp", "cc_prebuilt_binary", "hermesd"),
]


def drop(text, kind, name, path):
    if f'name: "{name}"' not in text:
        return text, False  # already applied
    m = re.search(rf"^{re.escape(kind)} \{{\n    name: \"{re.escape(name)}\",",
                  text, re.M)
    if not m:
        raise SystemExit(
            f"vendor_fix: FAIL {path}: {name} is present but not as {kind}; "
            "the tree moved, anchor the block by hand")
    depth = 0
    j = m.start()
    while j < len(text):
        if text[j] == "{":
            depth += 1
        elif text[j] == "}":
            depth -= 1
            if depth == 0:
                break
        j += 1
    else:
        raise SystemExit(f"vendor_fix: FAIL {path}: unbalanced braces at {name}")
    end = j + 1
    if end < len(text) and text[end] == "\n":
        end += 1
    return text[:m.start()] + text[end:], True


def main():

    ap = argparse.ArgumentParser()
    ap.add_argument("--tree", required=True, help="Android source root")
    ap.add_argument("--check", action="store_true")
    a = ap.parse_args()
    if not os.path.isdir(os.path.join(a.tree, "vendor/samsung")):
        print("vendor_fix: no vendor/samsung trees on this device, nothing to do")
        return 0
    changed = 0
    for rel, kind, name in CLASHES:
        p = os.path.join(a.tree, rel)
        if not os.path.exists(p):
            print(f"vendor_fix: FAIL missing {rel}", file=sys.stderr)
            return 2
        t = open(p).read()
        t2, did = drop(t, kind, name, rel)
        if did:
            changed += 1
            print(("would drop " if a.check else "dropped ") + f"{rel}: {name}")
            if not a.check:
                open(p, "w").write(t2)
    print("vendor_fix: already clean" if not changed else f"vendor_fix: {changed} dropped")
    return 0


if __name__ == "__main__":
    sys.exit(main())
