import os, json
from pathlib import Path

root = Path("client/cocos/assets/resources")
monsters_dir = root / "monsters" / "archetypes"
chars_dir = root / "characters"

print(f"Monsters dir exists: {monsters_dir.exists()}")
print(f"Chars dir exists: {chars_dir.exists()}")

monster_manifests = list(monsters_dir.glob("*/*_anim_manifest.json"))
char_manifests = list(chars_dir.glob("*/*_anim_manifest.json"))

print(f"Found {len(monster_manifests)} monster manifests, {len(char_manifests)} char manifests.")
assert len(monster_manifests) == 10, f"Expected 10 monster manifests, found {len(monster_manifests)}"
assert len(char_manifests) == 6, f"Expected 6 character manifests, found {len(char_manifests)}"

total_frames_audited = 0
out_of_bounds_count = 0

all_manifests = monster_manifests + char_manifests
for mpath in all_manifests:
    with open(mpath, "r", encoding="utf-8") as f:
        data = json.load(f)
    pivot = data.get("defaultPivot") or data.get("pivot")
    assert pivot == [0.5, 0.90] or pivot == [0.5, 0.9], f"Wrong pivot {pivot} in {mpath}"
    frames = data.get("frames", {})
    tex_w = data.get("textureWidth") or data.get("texture_width")
    tex_h = data.get("textureHeight") or data.get("texture_height")
    assert tex_w and tex_h
    # verify power of two
    assert (tex_w & (tex_w - 1)) == 0, f"tex_w {tex_w} not power of two in {mpath}"
    assert (tex_h & (tex_h - 1)) == 0, f"tex_h {tex_h} not power of two in {mpath}"

    for fid, fmeta in frames.items():
        total_frames_audited += 1
        uv = fmeta.get("uv")
        assert uv is not None, f"Missing uv in {fid} of {mpath}"
        u0, v0, u1, v1 = uv
        if not (0.0 <= u0 <= 1.0 and 0.0 <= v0 <= 1.0 and 0.0 <= u1 <= 1.0 and 0.0 <= v1 <= 1.0):
            out_of_bounds_count += 1
            print(f"Out of bounds UV in {mpath.name}: {fid} -> {uv}")

print(f"Scaffolding UV check: Audited {total_frames_audited} frames across {len(all_manifests)} manifests.")
print(f"Out of bounds count: {out_of_bounds_count}")
assert out_of_bounds_count == 0, "Out of bounds UV coordinates detected!"

print("ALL SCAFFOLDING CHECKS PASSED!")
