#!/usr/bin/env python3
"""Assert, on a synced + applied tree, every assumption Vanta makes about it.

Each of these fails SILENTLY in the real build if it stops being true: an
overlay naming a resource the target does not have is a no-op, a moved
vendor/extra hook means our layer quietly stops being included, and a
-include of a missing file is skipped without a word. So they are checked
here, loudly, before a multi-hour build is spent finding out.
"""
import glob
import json
import os
import re
import sys

import argparse

_ap = argparse.ArgumentParser()
_ap.add_argument("src", nargs="?", default=os.path.expanduser("~/vanta"))
_ap.add_argument("--device", default=os.environ.get("VANTA_DEVICE", "b5q"))
ARGS = _ap.parse_args()
SRC = ARGS.src
DEVICE = ARGS.device
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TOK = json.load(open(os.path.join(HERE, "design/tokens.json")))
fails = []


def ok(cond, what):
    print(("ok    " if cond else "FAIL  ") + what)
    if not cond:
        fails.append(what)


def read(rel):
    p = os.path.join(SRC, rel)
    return open(p, errors="replace").read() if os.path.exists(p) else ""


def names_in(dirrel, kind):
    found = set()
    for f in glob.glob(os.path.join(SRC, dirrel, "*.xml")):
        found |= set(re.findall(rf'<{kind}\s+name="([^"]+)"', open(f, errors="replace").read()))
    return found


# 1. The vendor/extra hook: still first, and still ours to use.
common = read("vendor/lineage/config/common.mk")
inherits = re.findall(r"inherit-product(?:-if-exists)?,\s*([^)\s]+)", common)
ok(bool(inherits) and inherits[0] == "vendor/extra/product.mk",
   "vendor/lineage common.mk inherits vendor/extra/product.mk first")
plist = read(".repo/project.list").split()
ok("vendor/extra" not in plist, "vendor/extra is not claimed by any repo project")
ok(os.path.exists(os.path.join(SRC, "vendor/extra/product.mk")), "vendor/extra/product.mk installed")

# 1b. Boot animation: Lineage's module installs to /product/media (read before
#     /system/media), so ours only shows if its genrule still takes a prebuilt.
ba = read("vendor/lineage/bootanimation/Android.bp")
ok('soong_config_variable("lineage_bootanimation", "prebuilt_file")' in ba,
   "Lineage bootanimation genrule still honours lineage_bootanimation.prebuilt_file")
ok("lineage_bootanimation,prebuilt_file,vendor/vanta/prebuilt/bootanimation.zip" in read("vendor/vanta/vanta.mk"),
   "vanta.mk points the genrule at our boot animation")

# 1c. Every module Vanta overrides must exist (overriding a missing module is
#     silently a no-op, and the Lineage one ships beside ours).
def module_defined(name, *bps):
    return any(re.search(rf'name:\s*"{re.escape(name)}"', read(bp)) for bp in bps)
for name, bps in {
    "Updater": ["packages/apps/Updater/Android.bp", "packages/apps/Updater/app/Android.bp"],
    "LineageSetupWizard": ["packages/apps/SetupWizard/Android.bp", "packages/apps/SetupWizard/app/Android.bp"],
}.items():
    ok(module_defined(name, *bps), f"tree defines {name} (overridden by Vanta)")

# 1d. Brand RRO targets still carry their package names.
ok('package="lineageos.platform"' in read("lineage-sdk/lineage/res/AndroidManifest.xml"),
   "lineage-sdk resources are package lineageos.platform (VantaBrandPlatformOverlay target)")
ok('package="org.lineageos.lineageparts"' in read("packages/apps/LineageParts/AndroidManifest.xml"),
   "LineageParts is org.lineageos.lineageparts (VantaBrandPartsOverlay target)")

# 1e. Recovery art is ours (recovery.sh copies it in after every sync).
for dpi in sorted(glob.glob(os.path.join(HERE, "vendor/vanta/recovery/res-*"))):
    for f in ("logo_image.png", "fastbootd.png", "loop00000.png"):
        mine = os.path.join(dpi, "images", f)
        theirs = os.path.join(SRC, "bootable/recovery", os.path.basename(dpi), "images", f)
        ok(os.path.exists(theirs) and open(mine, "rb").read() == open(theirs, "rb").read(),
           f"recovery {os.path.basename(dpi)}/{f} is Vanta's")

# 1f. The named font family rides in Lineage's own module (tools/fonts.sh),
#     and no Vanta module installs a file name a Lineage module in the same
#     place already installs: Android 17's Soong emits an install rule for
#     every module, so that is a Kati "overriding commands" failure an hour
#     into the build, and `overrides:` does not prevent it.
FONTS = "packages/overlays/Lineage/fonts/etc"
ok(module_defined("fonts_customization.xml", f"{FONTS}/Android.bp"),
   "Lineage still builds fonts_customization.xml (Vanta's family rides in it)")
ours_fc = os.path.join(HERE, "vendor/vanta/fonts/fonts_customization.xml")
ok(read(f"{FONTS}/fonts_customization.xml") == open(ours_fc, encoding="utf-8").read(),
   "tree's fonts_customization.xml is Vanta's (tools/fonts.sh ran)")


def installs(bp_text):
    out = set()
    for m in re.finditer(r"\b(prebuilt_etc|prebuilt_font)\s*\{(.*?)\n\}", bp_text, re.S):
        body = m.group(2)
        fn = re.search(r'filename:\s*"([^"]+)"', body) or re.search(r'name:\s*"([^"]+)"', body)
        sub_dir = re.search(r'sub_dir:\s*"([^"]+)"', body)
        part = "product" if re.search(r"product_specific:\s*true", body) else "system"
        out.add((m.group(1), part, sub_dir.group(1) if sub_dir else "", fn.group(1)))
    return out


mine, theirs = set(), set()
for bp in glob.glob(os.path.join(SRC, "vendor/vanta/**/Android.bp"), recursive=True):
    mine |= installs(open(bp, errors="replace").read())
for bp in glob.glob(os.path.join(SRC, "packages/overlays/Lineage/**/Android.bp"), recursive=True):
    theirs |= installs(open(bp, errors="replace").read())
clash = sorted(mine & theirs)
ok(not clash, "no Vanta prebuilt installs over a Lineage prebuilt" + (f" ({clash})" if clash else ""))

# 2. Paths the device trees point at exist (-include'd = silent if missing).
ok(os.path.exists(os.path.join(SRC, "vendor/lineage/config/BoardConfigReservedSize.mk")),
   "vendor/lineage/config/BoardConfigReservedSize.mk exists")
ok(os.path.exists(os.path.join(SRC, "vendor/lineage/config/common_full_phone.mk")),
   "vendor/lineage/config/common_full_phone.mk exists")

# 3. The device: product registered, inheriting Lineage, and everything its
#    makefiles inherit unconditionally actually synced (a missing blob repo
#    stops product config with an error that does not name the manifest).
if DEVICE == "beyond2lte":
    ok("lineage_beyond2lte.mk" in read("device/samsung/beyond2lte/AndroidProducts.mk"), "lineage_beyond2lte registered")
    ok("vendor/lineage/config/common_full_phone.mk" in read("device/samsung/beyond2lte/lineage_beyond2lte.mk"),
       "lineage_beyond2lte inherits common_full_phone")
    ok("vendor/vanta/props/system.prop" in read("device/samsung/beyond2lte/BoardConfig.mk"), "Vanta board config applied")
    ok("config_num_physical_slots" in read("device/samsung/beyond2lte/overlay/frameworks/base/core/res/res/values/config.xml"),
       "dual-SIM physical slots overlay present")
elif DEVICE == "b5q":
    ok("lineage_b5q.mk" in read("device/samsung/b5q/AndroidProducts.mk"), "lineage_b5q registered")
    ok("vendor/lineage/config/common_full_phone.mk" in read("device/samsung/b5q/lineage_b5q.mk"),
       "lineage_b5q inherits common_full_phone")
    for f in ("vendor/samsung/b5q/b5q-vendor.mk", "vendor/samsung/sm8550-common/sm8550-common-vendor.mk",
              "vendor/samsung/sm8550-common/BoardConfigVendor.mk", "device/samsung/sm8550-common/common.mk",
              "hardware/samsung/Android.bp"):
        ok(os.path.exists(os.path.join(SRC, f)), f"{f} synced")
    ok(os.path.exists(os.path.join(SRC, "kernel/samsung/sm8550/arch/arm64/configs/b5q_defconfig")),
       "kernel has b5q_defconfig")
    # Each <layout> is a fold state; its default display is the one HOME (and Vanta's cover face) lands on.
    lay = read("device/samsung/b5q/configs/display/display_layout_configuration.xml")
    defaults = {}
    for st, body in re.findall(r"<layout>\s*<state>(\d+)</state>(.*?)</layout>", lay, re.S):
        d = re.search(r'<display[^>]*defaultDisplay="true"[^>]*>\s*<address>(\d+)</address>', body)
        if d:
            defaults[st] = d.group(1)
    ok(defaults.get("0") is not None and defaults.get("3") is not None and defaults["0"] != defaults["3"],
       "b5q display layout gives display 0 to the cover when closed and to the inner panel when open")
    ok("display_layout_configuration.xml" in read("device/samsung/b5q/device.mk"), "b5q installs its display layout")    # Soong dies with "found in multiple namespaces" when the Exynoobs 23.2
    # vendor trees prebuild a module hardware/samsung also builds from source
    # (real 24.0 failure: libsamsungSoundbooster_plus, 2026-10-11). apply.sh
    # runs tools/vendor_fix.py to drop the prebuilts; this proves it.
    for rel, name in (("vendor/samsung/b5q/Android.bp", "libsamsungSoundbooster_plus"),
                      ("vendor/samsung/sm8550-common/Android.bp", "hermesd")):
        ok(f'name: "{name}"' not in read(rel),
           f"vendor {name} prebuilt dropped (hardware/samsung builds it)")

elif DEVICE == "gsi_arm64":
    gsi = read("vendor/lineage/build/target/product/lineage_gsi_arm64.mk")
    ok("PRODUCT_NAME := lineage_gsi_arm64" in gsi, "lineage_gsi_arm64 product exists")
    generic = read("vendor/lineage/build/target/product/lineage_generic_target.mk")
    ok("vendor/lineage/config/common_full_phone.mk" in gsi + (generic if "lineage_generic_target.mk" in gsi else ""),
       "lineage_gsi_arm64 reaches common_full_phone (so vendor/extra, so Vanta)")
else:
    ok(False, f"verify_tree knows no device {DEVICE!r}")

# 4. Every overlaid resource exists in its target.
fw = "frameworks/base/core/res/res/values"
dimens, bools = names_in(fw, "dimen"), names_in(fw, "bool")
for k in TOK["radii_dp"]:
    ok(k in dimens, f"framework has dimen {k}")
for k in TOK["framework_bools"]:
    ok(k in bools, f"framework has bool {k}")
fr = names_in("frameworks/base/packages/SettingsProvider/res/values", "fraction")
for k in TOK["motion"]:
    ok(k in fr, f"SettingsProvider has fraction {k}")

# 4b. Every name in the generated RROs exists in its target, and each value
#     beats every night/vNN variant the target has. An RRO value is only used
#     when its configuration is equal to or better than the target's best
#     match, so an overlay values/ entry silently loses to a target
#     values-night-v34/ one. SettingsLib is a static lib of Settings, so its
#     res dirs count as Settings'.
OVERLAY_TARGETS = {
    "VantaFrameworkOverlay": ["frameworks/base/core/res/res"],
    "VantaRailOnly": ["frameworks/base/core/res/res"],
    "VantaSettingsOverlay": ["packages/apps/Settings/res", "frameworks/base/packages/SettingsLib/SettingsTheme/res",
                             "frameworks/base/packages/SettingsLib/res"],
    "VantaLauncher3Overlay": ["packages/apps/Launcher3/res", "packages/apps/Launcher3/quickstep/res"],
}
VALUE_RE = re.compile(r'<(color|dimen|integer|bool|string|style|fraction)\s+name="([^"]+)"'
                      r'|<item\s+name="([^"]+)"[^>]*\btype="([^"]+)"')


def quals(dirname):
    """values-night-v34 -> (night, 34); None if it carries any other qualifier."""
    night, ver = False, 0
    for q in dirname.split("-")[1:]:
        if q == "night":
            night = True
        elif re.fullmatch(r"v\d+", q):
            ver = int(q[1:])
        else:
            return None
    return night, ver


def res_index(root):
    """(type, name) -> {(night, ver)} over one res/ dir (values* entries + color*/drawable* files)."""
    idx = {}
    for d in sorted(glob.glob(os.path.join(root, "*"))):
        base, q = os.path.basename(d), quals(os.path.basename(d))
        if q is None:
            continue
        kind = base.split("-")[0]
        for f in glob.glob(os.path.join(d, "*.xml")):
            if kind == "values":
                for m in VALUE_RE.finditer(open(f, errors="replace").read()):
                    key = (m.group(1), m.group(2)) if m.group(1) else (m.group(4), m.group(3))
                    idx.setdefault(key, set()).add(q)
            elif kind in ("color", "drawable", "layout"):
                idx.setdefault((kind, os.path.basename(f)[:-4]), set()).add(q)
    return idx


def style_items(roots, name):
    for root in roots:
        for f in glob.glob(os.path.join(root, "values*", "*.xml")):
            m = re.search(rf'<style\s+name="{re.escape(name)}"[^>]*>(.*?)</style>', open(f, errors="replace").read(), re.S)
            if m:
                return set(re.findall(r'<item\s+name="([^"]+)"', m.group(1)))
    return None


for ov, roots in OVERLAY_TARGETS.items():
    ores = os.path.join(HERE, "vendor/vanta/overlay", ov, "res")
    mine = res_index(ores)
    ok(bool(mine), f"{ov} has generated resources")
    theirs = {}
    for r in roots:
        for k, v in res_index(os.path.join(SRC, r)).items():
            theirs.setdefault(k, set()).update(v)
    uncovered = []
    for (kind, name), oq in sorted(mine.items()):
        ok((kind, name) in theirs, f"{ov}: target has {kind} {name}")
        for night, ver in sorted(theirs.get((kind, name), ())):
            if not any(n == night and v >= ver for n, v in oq):
                uncovered.append(f"{kind}/{name}@{'night-' if night else ''}v{ver}")
        if kind == "style":
            up = style_items([os.path.join(SRC, r) for r in roots], name)
            ours = style_items([ores], name)
            ok(up is not None and ours is not None and up <= ours,
               f"{ov}: style {name} re-declares every upstream item" + (f" (missing {sorted(up - ours)})" if up and ours and not up <= ours else ""))
    ok(not uncovered, f"{ov}: every value covers the target's night/vNN variants"
       + (": " + " ".join(uncovered) if uncovered else ""))

# 4c. Rail only: the modules VantaRailOnly overrides must exist (overriding a
#     missing module is silently a no-op), and Settings' navigation picker
#     must still hide a mode whose overlay package is not installed, instead of
#     listing it (that is why no Settings patch is carried).
bp = open(os.path.join(HERE, "vendor/vanta/Android.bp")).read()
rail = re.search(r'name:\s*"VantaRailOnly"(.*?)\n}', bp, re.S)
overridden = re.findall(r'"([^"]+)"', re.search(r"overrides:\s*\[(.*?)\]", rail.group(1), re.S).group(1)) if rail else []
ok(len(overridden) == 2, "VantaRailOnly overrides the 3-button and 2-button overlays")
for mod in overridden:
    ok(re.search(rf'name:\s*"{mod}"', read(f"frameworks/base/packages/overlays/{mod}/Android.bp")) is not None,
       f"tree defines {mod}")
nav = read("packages/apps/Settings/src/com/android/settings/gestures/SystemNavigationGestureSettings.java")
for mode in ("NAV_BAR_MODE_3BUTTON_OVERLAY", "NAV_BAR_MODE_2BUTTON_OVERLAY"):
    ok(len(re.findall(rf"isOverlayPackageAvailable\(\s*\w+,\s*{mode}\)", nav)) >= 2,
       f"Settings nav picker + search index gate {mode} on the overlay being installed")
ctl = read("packages/apps/Settings/src/com/android/settings/gestures/SystemNavigationPreferenceController.java")
at = ctl.find("static boolean isOverlayPackageAvailable(Context")
ok(at >= 0 and re.search(r"catch\s*\(\s*(PackageManager\.)?NameNotFoundException[^)]*\)\s*\{[^}]*return false;",
                         ctl[at:at + 600]) is not None,
   "Settings treats a missing nav overlay package as unavailable, not a crash")

# 4d. Recents target: QuickStep is still the com.android.launcher3 package.
ok('package="com.android.launcher3"' in read("packages/apps/Launcher3/quickstep/AndroidManifest.xml"),
   "Launcher3 QuickStep package is com.android.launcher3 (VantaLauncher3Overlay target)")

# 5. The font overlay the identity names is built by this tree.
font = TOK["theme"]["font"]
hits = [p for p in glob.glob(os.path.join(SRC, "vendor/vanta/overlay/**/AndroidManifest.xml"), recursive=True)
        + glob.glob(os.path.join(SRC, "packages/overlays/**/AndroidManifest.xml"), recursive=True)
        + glob.glob(os.path.join(SRC, "frameworks/base/packages/overlays/**/AndroidManifest.xml"), recursive=True)
        if f'package="{font}"' in open(p, errors="replace").read()]
ok(bool(hits), f"font overlay {font} exists in tree")

# 5b. Google apps: vanta.mk inherits vendor/gapps when the profile says so.
if os.environ.get("VANTA_GAPPS") == "true":
    ok(os.path.exists(os.path.join(SRC, "vendor/gapps/arm64/arm64-vendor.mk")), "vendor/gapps (MindTheGapps) synced")
    ok("SetupWizard" in read("vendor/gapps/arm64/arm64-vendor.mk"),
       "MindTheGapps still ships a SetupWizard module (VantaWelcome overrides it by that name)")

# 6. Kernel root (only the S10 carries KernelSU-Next).
if DEVICE == "beyond2lte":
    k = "kernel/samsung/exynos9820"
    ok(os.path.islink(os.path.join(SRC, k, "drivers/kernelsu")), "KernelSU-Next linked into drivers/")
    ok(os.path.exists(os.path.join(SRC, k, "arch/arm64/configs/vanta.config")), "kernel fragment vanta.config installed")

print(f"verify_tree: {'FAILED ' + str(len(fails)) if fails else 'ok'}")
sys.exit(1 if fails else 0)
