"""Read original APK battle tables for v1.2 research; never contacts a server.""" from collections import Counter import hashlib import json from pathlib import Path import re import sys import zipfile import zlib ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT)) from ranch_assistant.amf import Reader def recover_table(archive, name): logical = f"data/table/{name}.json" member = "assets/codes/" + hashlib.md5(logical.encode()).hexdigest() compressed = archive.read(member) decoded = zlib.decompress(compressed) reader = Reader(decoded) value = reader.read() if reader.pos != len(decoded): raise ValueError(f"Unconsumed table bytes: {name}") return value, {"logical_path": logical, "member": member, "compressed_bytes": len(compressed), "decoded_bytes": len(decoded), "sha256": hashlib.sha256(compressed).hexdigest()} def main(): candidates = list(ROOT.glob("*_1.9.68.apk")) if len(candidates) != 1: raise ValueError("Expected exactly one original 1.9.68 APK") apk = candidates[0] tables, metadata, binaries = {}, {}, {} names = ("stage_info", "task_info", "monster_info", "monster_skill", "monster_setting", "setting", "game_setting", "item_info", "entangle_info", "potential_info", "team_info") with zipfile.ZipFile(apk) as archive: for member in ("assets/MYRMain.app", "assets/MYRDyd.swf"): data = archive.read(member) binaries[member] = {"bytes": len(data), "swf_signature": data[:3].decode("ascii"), "swf_version": data[3], "sha256": hashlib.sha256(data).hexdigest()} for name in names: value, metadata[name] = recover_table(archive, name) tables[name] = value.get("datas", value) if isinstance(value, dict) else value metadata[name]["record_count"] = len(tables[name]) stages = tables["stage_info"] stages = stages.values() if isinstance(stages, dict) else stages stage_levels, battles = [], [] for stage in stages: for level in (stage.get("level") or {}).values(): stage_levels.append(level) if isinstance(level.get("battle"), dict): battles.append(level["battle"]) tasks = list(tables["task_info"].values()) task_battles = [step["battle"] for task in tasks for step in task.get("steps", []) if isinstance(step.get("battle"), dict)] controllers, triggers, win_types, lose_types = Counter(), Counter(), Counter(), Counter() for battle in battles + task_battles: controllers.update(str(x.get("type")) for x in battle.get("controller", [])) triggers.update(str(x.get("type")) for x in battle.get("triggers", [])) win_types.update(str(x) for x in battle.get("winType", [])) lose_types.update(str(x) for x in battle.get("loseType", [])) scripts = ROOT / "analysis/as3/scripts" files = list(scripts.rglob("*.as")) counts = {} for folder in ("net/pixvi/myr/battle", "net/pixvi/myr/view/skill", "net/pixvi/myr/view/attack", "net/pixvi/myr/element/battle"): counts[folder] = len(list((scripts / folder).rglob("*.as"))) missing = set() for file in (scripts / "net/pixvi/myr/battle").rglob("*.as"): for imported in re.findall(r"import ([\w.]+);", file.read_text(encoding="utf-8")): if imported.startswith(("net.pixvi.pfw.", "net.pixvi.common.", "starling.")): if not (scripts / (imported.replace(".", "/") + ".as")).exists(): missing.add(imported) catalog = json.loads((ROOT / "ranch_assistant/data/catalog.json").read_text(encoding="utf-8")) summary = {"artifact": apk.name, "apk_bytes": apk.stat().st_size, "binaries": binaries, "tables": metadata, "battle_coverage": {"stage_level_count": len(stage_levels), "stage_battle_object_count": len(battles), "stage_nonempty_battle_count": sum(bool(b) for b in battles), "task_battle_object_count": len(task_battles), "task_nonempty_battle_count": sum(bool(b) for b in task_battles), "controller_types": dict(controllers), "trigger_types": dict(triggers), "win_types": dict(win_types), "lose_types": dict(lose_types)}, "task_types": dict(Counter(str(t.get("type")) for t in tasks)), "task_update_mode": {"legacy_flag_present": "useOldNewTaskFunction" in tables["setting"], "legacy_flag": tables["setting"].get("useOldNewTaskFunction"), "selected_by_retained_client": "legacy" if tables["setting"].get("useOldNewTaskFunction") is True else "new"}, "retained_sources": {"all_as_files": len(files), "battle_source_counts": counts, "battle_framework_imports_without_retained_source": sorted(missing)}, "helper_catalog": {"has_monster_skill": "monster_skill" in catalog, "has_setting": "setting" in catalog, "task_count": len(catalog["task_info"]), "stage_levels_with_battle": sum(isinstance(l.get("battle"), dict) for s in catalog["stage_info"].values() for l in s.get("level", {}).values())}, "scope": "Static table recovery and retained source inventory only; no battle executed or submitted."} output = ROOT / "analysis/V1_2_BATTLE_INVENTORY.json" output.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(json.dumps({"output": str(output.relative_to(ROOT)), "table_counts": {k: v["record_count"] for k, v in metadata.items()}, "battle_coverage": summary["battle_coverage"], "helper_catalog": summary["helper_catalog"], "missing_framework_sources": len(missing)}, ensure_ascii=True)) if __name__ == "__main__": main()