#!/usr/bin/env python3
import os
import sys
import subprocess
import threading
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import json
import re
import datetime
import argparse

# ---------------------------------------------------------------------------
# Asura's Wrath — Advanced Native Recomp Launcher (SpartanPort Inspired)
# ---------------------------------------------------------------------------

PKG_DIR = os.path.dirname(os.path.abspath(__file__))
ROM_DATA = os.path.join(PKG_DIR, "rom_data")
CFG_FILE = os.path.join(PKG_DIR, "recomp.cfg")
SETTINGS_FILE = os.path.join(PKG_DIR, "settings.json")
MODS_DIR = os.path.join(PKG_DIR, "mods")
EXTRACTED_DIR = os.path.join(PKG_DIR, "disc_extracted")
TITLE = "BLUS30721"
MODULE_FILE = os.path.join(ROM_DATA, f"{TITLE}.ppumod")

RPCS3_BIN = os.environ.get("RPCS3_BIN")
if not RPCS3_BIN:
    bundled_engine = os.path.join(PKG_DIR, "engine", "rpcs3")
    RPCS3_BIN = bundled_engine if os.path.exists(bundled_engine) else "/home/dio/Projects/ps3-recomp/rpcs3/build/bin/rpcs3"

RPCS3_CFG_DIR = os.path.expanduser("~/.config/rpcs3")
RPCS3_CFG = os.path.join(RPCS3_CFG_DIR, "config.yml")

def update_yml(path, updates):
    if not os.path.exists(path): return
    with open(path, "r") as f: lines = f.readlines()

    new_lines = []
    current_section = None
    current_subsection = None

    for line in lines:
        stripped = line.strip()
        if not stripped or stripped.startswith("#"):
            new_lines.append(line)
            continue

        indent = len(line) - len(line.lstrip())
        if indent == 0 and stripped.endswith(":"):
            current_section = stripped[:-1]
            current_subsection = None
            new_lines.append(line)
            continue
        elif indent == 2 and stripped.endswith(":"):
            current_subsection = stripped[:-1]
            new_lines.append(line)
            continue

        applied = False
        for key_path, val in updates.items():
            parts = key_path.split("/")
            if len(parts) == 2:
                sec, key = parts
                if current_section == sec and stripped.startswith(f"{key}:"):
                    if isinstance(val, bool): val = str(val).lower()
                    prefix = line[:line.find(key)]
                    new_lines.append(f"{prefix}{key}: {val}\n")
                    applied = True
                    break
            elif len(parts) == 3:
                sec, sub, key = parts
                if current_section == sec and current_subsection == sub and stripped.startswith(f"{key}:"):
                    if isinstance(val, bool): val = str(val).lower()
                    prefix = line[:line.find(key)]
                    new_lines.append(f"{prefix}{key}: {val}\n")
                    applied = True
                    break
        if not applied:
            new_lines.append(line)

    with open(path, "w") as f: f.writelines(new_lines)

def load_settings():
    defaults = {
        "fullscreen": True,
        "vsync": True,
        "perf_overlay": False,
        "resolution_scale": 150, # 1080p
        "vblank_rate": 60,
        "anisotropic_filter": 16,
        "upscaling": "FSR",
        "cheat_60fps": True,
        "cheat_one_shot": False,
        "cheat_skip_intro": True,
        "cheat_heavy": False,
        "cheat_burst": False,
        "cheat_god": False,
        "cheat_extras": True,
        "controls": {
            "Jump": "Cross / A",
            "Attack": "Square / X",
            "Heavy": "Triangle / Y",
            "Grab": "Circle / B",
            "Burst": "R1 / RB"
        }
    }
    if os.path.exists(SETTINGS_FILE):
        try:
            with open(SETTINGS_FILE, "r") as f: defaults.update(json.load(f))
        except: pass
    return defaults

def save_pkg_path(path):
    """Record the player's copy in recomp.cfg, keeping the disc image pin."""
    disc_pin = ""
    if os.path.exists(CFG_FILE):
        with open(CFG_FILE) as f:
            for line in f:
                if line.startswith("disc_pin="):
                    disc_pin = line.split("=", 1)[1].strip().strip('"')
    if os.path.isfile(path):
        disc_pin = path  # a disc image is both the copy and the pin
    out = f"game_path={path}\ntitle={TITLE}\n"
    if disc_pin: out += f"disc_pin={disc_pin}\n"
    out += f"module={MODULE_FILE}\n"
    with open(CFG_FILE, "w") as f:
        f.write(out)


def apply_settings(settings):
    """Push settings.json onto the engine config + the patch files.
    Shared by the GUI (Apply/Play) and the headless launcher path."""
    upscale_mode = "Bilinear"
    if "FSR" in settings["upscaling"]: upscale_mode = "FSR"

    updates = {
        "Video/Resolution Scale": settings["resolution_scale"],
        "Video/Vblank Rate": settings["vblank_rate"],
        "Video/VSync Mode": "Enabled" if settings["vsync"] else "Disabled",
        "Video/Output Scaling Mode": upscale_mode,
        "Video/Anisotropic Filter Override": settings["anisotropic_filter"],
        "Video/Read Color Buffers": True,
        "Video/Write Color Buffers": True,
        "Video/Frame limit": "Off" if settings["cheat_60fps"] else "Auto",
        "Video/Performance Overlay/Enabled": settings["perf_overlay"],
        "Miscellaneous/Start games in fullscreen mode": settings["fullscreen"]
    }
    update_yml(RPCS3_CFG, updates)
    write_patches(settings)


def game_command(settings, game_path):
    cmd = [RPCS3_BIN, "--no-gui"]
    if settings["fullscreen"]: cmd.append("--fullscreen")
    cmd.append(game_path)
    return cmd


def resolve_disc_path(p):
    """The engine boots an .iso as-is, or the folder that holds PS3_GAME."""
    p = os.path.abspath(os.path.expanduser(p))
    if os.path.isdir(p) and os.path.basename(p.rstrip("/")) == "PS3_GAME":
        return os.path.dirname(p.rstrip("/"))
    return p


def module_is_current(path):
    """True when rom_data already holds a module built from this same copy."""
    if not os.path.exists(MODULE_FILE) or not os.path.exists(CFG_FILE):
        return False
    with open(CFG_FILE) as f:
        for line in f:
            if line.startswith("game_path="):
                return line.split("=", 1)[1].strip().strip('"') == path
    return False


def build_module(game_path, quiet=False):
    """Compile the disc's PPU into rom_data/<title>.ppumod (first run, 5-15 min)."""
    os.makedirs(ROM_DATA, exist_ok=True)
    cmd = [RPCS3_BIN, "--ppumod-build", MODULE_FILE, "--ppumod-title", TITLE, game_path]
    if quiet:
        return subprocess.call(cmd)
    print("progress 0.10 Compiling the game into a native module (5-15 minutes)", flush=True)
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                            text=True, bufsize=1)
    for line in proc.stdout or []:
        line = line.strip()
        if line:
            print(f"progress 0.50 {line[:120]}", flush=True)
    rc = proc.wait()
    print("progress 1.00 Native module ready" if rc == 0 else f"progress 1.00 Build failed ({rc})", flush=True)
    return rc


class AsuraLauncherApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Asura's Wrath — Native Recomp Edition")
        self.root.geometry("1000x700")
        self.root.configure(bg="#0a0a0a")

        self.settings = load_settings()
        self.cfg = self.load_pkg_config()

        # UI Styles
        style = ttk.Style()
        style.theme_use("clam")
        style.configure("TNotebook", background="#0a0a0a", borderwidth=0)
        style.configure("TNotebook.Tab", background="#1a1a1a", foreground="#888", padding=[20, 10], font=("Segoe UI", 10, "bold"))
        style.map("TNotebook.Tab", background=[("selected", "#ff6f00")], foreground=[("selected", "#fff")])

        self.setup_ui()
        self.check_status()

    def load_pkg_config(self):
        cfg = {"game_path": "", "disc_pin": ""}
        if os.path.exists(CFG_FILE):
            with open(CFG_FILE, "r") as f:
                for line in f:
                    if "=" in line:
                        k, v = line.strip().split("=", 1)
                        cfg[k] = v.strip('"')
        return cfg

    def setup_ui(self):
        # Header Banner
        banner = tk.Frame(self.root, bg="#111", height=150)
        banner.pack(fill=tk.X)
        banner.pack_propagate(False)

        try:
            from PIL import Image, ImageTk
            img = Image.open(os.path.join(PKG_DIR, "asuraswrath.png")).resize((200, 120), Image.LANCZOS)
            self.logo = ImageTk.PhotoImage(img)
            tk.Label(banner, image=self.logo, bg="#111").pack(side=tk.LEFT, padx=30)
        except:
            tk.Label(banner, text="ASURA'S WRATH", fg="#ff6f00", bg="#111", font=("Segoe UI", 32, "bold")).pack(side=tk.LEFT, padx=30)

        info_frame = tk.Frame(banner, bg="#111")
        info_frame.pack(side=tk.LEFT, pady=30)
        tk.Label(info_frame, text="NATIVE RECOMPILATION PROJECT", fg="#fff", bg="#111", font=("Segoe UI", 12, "bold")).pack(anchor=tk.W)
        tk.Label(info_frame, text="Zero-Precompile Engine | v1.2-Spartan", fg="#888", bg="#111").pack(anchor=tk.W)

        # Tabs
        self.nb = ttk.Notebook(self.root)
        self.nb.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)

        self.tab_home = tk.Frame(self.nb, bg="#0f0f0f")
        self.tab_video = tk.Frame(self.nb, bg="#0f0f0f")
        self.tab_cheats = tk.Frame(self.nb, bg="#0f0f0f")
        self.tab_controls = tk.Frame(self.nb, bg="#0f0f0f")
        self.tab_mods = tk.Frame(self.nb, bg="#0f0f0f")

        self.nb.add(self.tab_home, text=" HOME ")
        self.nb.add(self.tab_video, text=" VIDEO & GRAPHICS ")
        self.nb.add(self.tab_cheats, text=" CHEATS ")
        self.nb.add(self.tab_controls, text=" CONTROLS ")
        self.nb.add(self.tab_mods, text=" MODS ")

        self.init_home()
        self.init_video()
        self.init_cheats()
        self.init_controls()
        self.init_mods()

    def init_home(self):
        frame = tk.Frame(self.tab_home, bg="#0f0f0f", padx=40, pady=40)
        frame.pack(fill=tk.BOTH, expand=True)

        status_box = tk.Frame(frame, bg="#1a1a1a", padx=20, pady=20)
        status_box.pack(fill=tk.X)

        self.lbl_status = tk.Label(status_box, text="Status: Checking...", fg="#aaa", bg="#1a1a1a", font=("Segoe UI", 11))
        self.lbl_status.pack(anchor=tk.W)

        self.btn_play = tk.Button(frame, text="LAUNCH GAME", bg="#ff6f00", fg="#fff", font=("Segoe UI", 16, "bold"),
                                 relief=tk.FLAT, pady=15, command=self.launch_game)
        self.btn_play.pack(fill=tk.X, pady=30)

        tk.Button(frame, text="Select Game Folder / ISO", bg="#333", fg="#fff", relief=tk.FLAT, command=self.select_disc).pack(side=tk.LEFT)
        tk.Button(frame, text="Rebuild PPU Cache", bg="#333", fg="#fff", relief=tk.FLAT, command=self.rebuild).pack(side=tk.LEFT, padx=10)

    def init_video(self):
        f = tk.Frame(self.tab_video, bg="#0f0f0f", padx=40, pady=40)
        f.pack(fill=tk.BOTH)

        tk.Label(f, text="DISPLAY SETTINGS", fg="#ff6f00", bg="#0f0f0f", font=("Segoe UI", 14, "bold")).pack(anchor=tk.W, pady=(0, 20))

        grid = tk.Frame(f, bg="#0f0f0f")
        grid.pack(fill=tk.X)

        # Resolution
        tk.Label(grid, text="Resolution Scale (Native 720p)", fg="#fff", bg="#0f0f0f").grid(row=0, column=0, sticky=tk.W)
        self.res_var = tk.StringVar(value=str(self.settings["resolution_scale"]))
        cb_res = ttk.Combobox(grid, textvariable=self.res_var, values=["100", "150", "200", "300"], state="readonly")
        cb_res.grid(row=0, column=1, padx=20, pady=10)
        tk.Label(grid, text="150 = 1080p, 300 = 4K", fg="#666", bg="#0f0f0f").grid(row=0, column=2, sticky=tk.W)

        # Refresh Rate
        tk.Label(grid, text="Vblank Rate (Refresh)", fg="#fff", bg="#0f0f0f").grid(row=1, column=0, sticky=tk.W)
        self.vb_var = tk.StringVar(value=str(self.settings["vblank_rate"]))
        cb_vb = ttk.Combobox(grid, textvariable=self.vb_var, values=["60", "120", "144", "240"], state="readonly")
        cb_vb.grid(row=1, column=1, padx=20, pady=10)

        # Enhancements
        self.fs_var = tk.BooleanVar(value=self.settings["fullscreen"])
        tk.Checkbutton(grid, text="Fullscreen Mode", variable=self.fs_var, bg="#0f0f0f", fg="#fff", selectcolor="#000").grid(row=2, column=0, sticky=tk.W, pady=10)

        self.vsync_var = tk.BooleanVar(value=self.settings["vsync"])
        tk.Checkbutton(grid, text="Enable VSync", variable=self.vsync_var, bg="#0f0f0f", fg="#fff", selectcolor="#000").grid(row=2, column=1, sticky=tk.W)

        self.overlay_var = tk.BooleanVar(value=self.settings["perf_overlay"])
        tk.Checkbutton(grid, text="Show Performance Overlay", variable=self.overlay_var, bg="#0f0f0f", fg="#fff", selectcolor="#000").grid(row=3, column=0, sticky=tk.W)

        tk.Label(grid, text="Upscaling Method", fg="#fff", bg="#0f0f0f").grid(row=4, column=0, sticky=tk.W, pady=10)
        self.upscale_var = tk.StringVar(value=self.settings["upscaling"])
        ttk.Combobox(grid, textvariable=self.upscale_var, values=["Bilinear", "FSR (DLSS Alt)", "Nearest"], state="readonly").grid(row=4, column=1, padx=20)

        tk.Button(f, text="APPLY VIDEO SETTINGS", bg="#ff6f00", fg="#fff", relief=tk.FLAT, padx=20, pady=10, command=self.save_settings).pack(pady=30)

    def init_cheats(self):
        f = tk.Frame(self.tab_cheats, bg="#0f0f0f", padx=40, pady=40)
        f.pack(fill=tk.BOTH)

        self.c_60fps = tk.BooleanVar(value=self.settings["cheat_60fps"])
        tk.Checkbutton(f, text="Unlock Framerate (60FPS+ Patch)", variable=self.c_60fps, bg="#0f0f0f", fg="#fff", font=("Segoe UI", 12), selectcolor="#000").pack(anchor=tk.W, pady=5)

        self.c_skip = tk.BooleanVar(value=self.settings["cheat_skip_intro"])
        tk.Checkbutton(f, text="Skip Intro Logos", variable=self.c_skip, bg="#0f0f0f", fg="#fff", font=("Segoe UI", 12), selectcolor="#000").pack(anchor=tk.W, pady=5)

        self.c_one = tk.BooleanVar(value=self.settings["cheat_one_shot"])
        tk.Checkbutton(f, text="One-Shot Enemies", variable=self.c_one, bg="#0f0f0f", fg="#fff", font=("Segoe UI", 12), selectcolor="#000").pack(anchor=tk.W, pady=5)

        self.c_heavy = tk.BooleanVar(value=self.settings["cheat_heavy"])
        tk.Checkbutton(f, text="No Heavy Blow Cooldown", variable=self.c_heavy, bg="#0f0f0f", fg="#fff", font=("Segoe UI", 12), selectcolor="#000").pack(anchor=tk.W, pady=5)

        self.c_burst = tk.BooleanVar(value=self.settings["cheat_burst"])
        tk.Checkbutton(f, text="Infinite Burst Gauge", variable=self.c_burst, bg="#0f0f0f", fg="#fff", font=("Segoe UI", 12), selectcolor="#000").pack(anchor=tk.W, pady=5)

        self.c_god = tk.BooleanVar(value=self.settings["cheat_god"])
        tk.Checkbutton(f, text="God Mode (Invincibility)", variable=self.c_god, bg="#0f0f0f", fg="#fff", font=("Segoe UI", 12), selectcolor="#000").pack(anchor=tk.W, pady=5)

        self.c_extras = tk.BooleanVar(value=self.settings["cheat_extras"])
        tk.Checkbutton(f, text="Unlock All Extras", variable=self.c_extras, bg="#0f0f0f", fg="#fff", font=("Segoe UI", 12), selectcolor="#000").pack(anchor=tk.W, pady=5)

    def init_controls(self):
        f = tk.Frame(self.tab_controls, bg="#0f0f0f", padx=40, pady=40)
        f.pack(fill=tk.BOTH)

        tk.Label(f, text="CUSTOM CONTROL MAPPING", fg="#ff6f00", bg="#0f0f0f", font=("Segoe UI", 14, "bold")).pack(anchor=tk.W, pady=(0, 20))

        self.mapping_vars = {}
        for action, current in self.settings["controls"].items():
            row = tk.Frame(f, bg="#0f0f0f", pady=5)
            row.pack(fill=tk.X)
            tk.Label(row, text=action, fg="#fff", bg="#0f0f0f", width=15, anchor=tk.W).pack(side=tk.LEFT)
            v = tk.StringVar(value=current)
            self.mapping_vars[action] = v
            tk.Entry(row, textvariable=v, bg="#222", fg="#fff", borderwidth=0, insertbackground="#fff").pack(side=tk.LEFT, padx=20)

        tk.Button(f, text="SAVE MAPPINGS", bg="#333", fg="#fff", relief=tk.FLAT, command=self.save_settings).pack(pady=20)

    def init_mods(self):
        f = tk.Frame(self.tab_mods, bg="#0f0f0f", padx=40, pady=40)
        f.pack(fill=tk.BOTH)
        tk.Label(f, text="LOCAL MODS MANAGER", fg="#ff6f00", bg="#0f0f0f", font=("Segoe UI", 14, "bold")).pack(anchor=tk.W)
        tk.Label(f, text="Drop .zip or folder mods into the 'mods' directory", fg="#888", bg="#0f0f0f").pack(anchor=tk.W, pady=10)

        self.mod_list = tk.Listbox(f, bg="#111", fg="#fff", borderwidth=0, highlightthickness=0)
        self.mod_list.pack(fill=tk.BOTH, expand=True)

        tk.Button(f, text="Open Mods Folder", bg="#333", fg="#fff", command=lambda: subprocess.run(["xdg-open", MODS_DIR])).pack(pady=10)

    def check_status(self):
        if not self.cfg["game_path"]:
            self.lbl_status.config(text="Status: No game selected. Please click 'Select Game Folder'.", fg="#ff4444")
        elif not os.path.exists(MODULE_FILE):
            self.lbl_status.config(text="Status: PPU Module missing. Build required for first launch.", fg="#ffcc00")
        else:
            self.lbl_status.config(text="Status: Ready to launch. Zero-precompile cache active.", fg="#44ff44")

    def save_settings(self):
        self.settings.update({
            "fullscreen": self.fs_var.get(),
            "vsync": self.vsync_var.get(),
            "perf_overlay": self.overlay_var.get(),
            "resolution_scale": int(self.res_var.get()),
            "vblank_rate": int(self.vb_var.get()),
            "upscaling": self.upscale_var.get(),
            "cheat_60fps": self.c_60fps.get(),
            "cheat_skip_intro": self.c_skip.get(),
            "cheat_one_shot": self.c_one.get(),
            "cheat_heavy": self.c_heavy.get(),
            "cheat_burst": self.c_burst.get(),
            "cheat_god": self.c_god.get(),
            "cheat_extras": self.c_extras.get(),
            "controls": {a: v.get() for a, v in self.mapping_vars.items()}
        })
        with open(SETTINGS_FILE, "w") as f: json.dump(self.settings, f)

        # Apply to RPCS3 config
        try:
            apply_settings(self.settings)
        except Exception as e: print(e)

        messagebox.showinfo("Settings", "Settings applied successfully!")

    def select_disc(self):
        p = filedialog.askdirectory()
        if p:
            self.cfg["game_path"] = p
            save_pkg_path(p)
            self.check_status()

    def rebuild(self):
        if not self.cfg["game_path"]: return
        subprocess.Popen([RPCS3_BIN, "--ppumod-build", MODULE_FILE, "--ppumod-title", TITLE, self.cfg["game_path"]])

    def launch_game(self):
        if not self.cfg["game_path"]: return
        self.save_settings()

        # Enable PPU Modules in config.yml (idempotent)
        configure_engine()

        self.root.withdraw()
        cmd = game_command(self.settings, self.cfg["game_path"])

        def run():
            subprocess.run(cmd)
            self.root.after(0, self.root.deiconify)
        threading.Thread(target=run, daemon=True).start()

# ---------------------------------------------------------------------------
# v1.2 patch pipeline (Phase 1)
# Emits ~/.config/rpcs3/patches/patch.yml + ~/.config/rpcs3/patch_config.yml
# in the engine's v1.2 schema (rpcs3 Utilities/bin_patch.cpp, patch_engine 1.2):
#   * top-level `Version: "1.2"` scalar — missing/wrong => whole file rejected
#   * main key = PPU executable hash (not the title id)
#   * patch lines are [ type, 0x-PPU-vaddr, 0x-value ]
#   * patch_config.yml bookkeeping: hash -> desc -> title -> serial -> appver
#     -> { Enabled: bool }; a missing entry defaults to disabled
# ---------------------------------------------------------------------------
PPU_HASH_FALLBACK = "83096111daff850cc92b637aec1780c4079e1c58"  # confirmed: re/ppu-hash.txt (4 independent signals)
RPCS3_LOG = os.path.expanduser("~/.cache/rpcs3/RPCS3.log")
PATCHES_STATE = os.path.join(RPCS3_CFG_DIR, "patches_state.json")

# Guaranteed no-op: be32 self-write of the 4 zero bytes already at PPU vaddr
# 0x10100 (seg0 + 0x100, module image phdr area). Exercises load -> config ->
# apply -> counter -> success logs end-to-end with zero game risk.
#
# P2 is FINALIZED (see CHEAT_LINES["cheat_60fps"] below): the frame-budget
# word 0x8a9438 (1e6 -> 5e5) now ships inside the 60FPS Unlock block, so this
# list is back to the single pipeline canary. T-006 confirmed 0x8a9438 is
# 1,000,000.0f read by exactly one instruction in the shared sleep helper,
# so 5e5 scales every sleep site (title, menus, gameplay, IO) — it is the
# pacing scale, NOT a duplicate of the 0x19afbac frame-rate target, so both
# lines ship together under the 60FPS Unlock toggle.
PROBE_LINES = [
    "[ be32, 0x10100, 0x00000000 ]",
]

# RE-verified cheat addresses (re/candidates.csv -> docs/CHEAT-SPECS.md,
# T-004 @ 72d302b + T-006 P2 answer @ c64b59d). cheat_60fps ships TWO lines:
#   * 0x19afbac = 60.0f  — the frame-rate TARGET the engine loop consumes.
#   * 0x8a9438  = 5e5    — the seconds->us PACE SCALE in the shared sleep
#     helper (native 1e6); 5e5 makes a sleep(1/30) round trip exactly 16667us
#     = one 60fps frame. T-006 proved a single reader, so it scales every
#     sleep site (title, menus, gameplay, IO) — it is the pacing half of the
#     unlock, not a duplicate of the target. Both ship together under the
#     60FPS Unlock toggle; flipping it off returns native 30fps pacing.
# Encodings are the CORRECTED ones: 30.0f = 0x41F00000, 60.0f = 0x42700000
# (the spec's old table was wrong — 0x42C00000 is 96.0f). Syntax note
# (bin_patch.cpp:808): float patch types (bef32/lef32/bef64/lef64) take the
# value as a DECIMAL FLOAT in YAML — the engine converts it to the
# endian-encoded word on write; a hex word like 0x42700000 fails yaml-cpp
# "bad conversion" and the whole block is skipped.
# A slot with no verified lines emits NO block (a block without patch lines
# fails engine load); the other six slots are TBD on purpose (their state
# lives in heap/objects or save-profile data, not .rodata — T-006 census).
# 60 FPS also toggles Video/Frame limit in save_settings.
CHEAT_LINES = {
    "cheat_60fps": [
        "[ bef32, 0x19afbac, 60.0 ]",
        "[ bef32, 0x0008a9438, 500000.0 ]",
    ],
    "cheat_skip_intro": [],
    "cheat_one_shot": [],
    "cheat_heavy": [],
    "cheat_burst": [],
    "cheat_god": [],
    "cheat_extras": [],
}
CHEAT_LABELS = {
    "cheat_60fps": "60FPS Unlock",
    "cheat_skip_intro": "Skip Intro Logos",
    "cheat_one_shot": "One-Shot Enemies",
    "cheat_heavy": "No Heavy Blow Cooldown",
    "cheat_burst": "Infinite Burst Gauge",
    "cheat_god": "God Mode",
    "cheat_extras": "Unlock All Extras",
}


def resolve_ppu_hash():
    """Newest engine ground truth first: RPCS3.log 'PPU executable hash' line,
    then the launcher's last written state file, then the recorded constant."""
    try:
        with open(RPCS3_LOG) as f:
            for line in reversed(f.readlines()):
                m = re.search(r"PPU executable hash: PPU-([0-9a-f]{40})", line)
                if m:
                    return m.group(1)
    except Exception:
        pass
    try:
        if os.path.exists(PATCHES_STATE):
            with open(PATCHES_STATE) as f:
                h = json.load(f).get("ppu_hash", "")
            if re.fullmatch(r"[0-9a-f]{40}", h):
                return h
    except Exception:
        pass
    return PPU_HASH_FALLBACK


def write_patches(settings):
    ppu_hash = resolve_ppu_hash()
    ppu_key = "PPU-" + ppu_hash
    patch_dir = os.path.join(RPCS3_CFG_DIR, "patches")
    os.makedirs(patch_dir, exist_ok=True)
    patch_file = os.path.join(patch_dir, "patch.yml")
    config_file = os.path.join(RPCS3_CFG_DIR, "patch_config.yml")

    blocks = [("Pipeline Probe (Phase 1)", True, PROBE_LINES,
               "be32 self-write no-op at PPU vaddr 0x10100; verifies the v1.2 pipeline end-to-end")]
    for slot, lines in CHEAT_LINES.items():
        if lines:
            blocks.append((CHEAT_LABELS[slot], bool(settings.get(slot)), lines,
                           CHEAT_LABELS[slot] + " (RE-verified addresses, T-004)"))

    # --- patches/patch.yml (v1.2 schema, main key = PPU executable hash) ---
    out = [
        "# Generated by asuraswrath launcher - v1.2 patch engine schema",
        'Version: "1.2"',
        "",
        f"{ppu_key}:",
    ]
    for desc, _enabled, lines, notes in blocks:
        out += [
            f'  "{desc}":',
            "    Games:",
            '      "Asura\'s Wrath":',
            f"        {TITLE}:",
            "          - All",
            '    Author: "dio"',
            f'    Notes: "{notes}"',
            "    Patch:",
        ]
        out += [f"      - {ln}" for ln in lines]
        out.append("")
    with open(patch_file, "w") as f:
        f.write("\n".join(out).rstrip() + "\n")

    # --- patch_config.yml (enable bookkeeping; missing entry = disabled) ---
    c = [
        "# Generated by asuraswrath launcher - v1.2 enable bookkeeping",
        f"{ppu_key}:",
    ]
    for desc, enabled, _lines, _notes in blocks:
        c += [
            f'  "{desc}":',
            '    "Asura\'s Wrath":',
            f"      {TITLE}:",
            "        All:",
            f"          Enabled: {str(enabled).lower()}",
        ]
    with open(config_file, "w") as f:
        f.write("\n".join(c) + "\n")

    # --- patches_state.json (bookkeeping: which hash we wrote for) ---
    state = {
        "ppu_hash": ppu_hash,
        "game": TITLE,
        "blocks": [desc for desc, _e, _l, _n in blocks],
        "written_at": datetime.datetime.now().astimezone().isoformat(timespec="seconds"),
    }
    with open(PATCHES_STATE, "w") as f:
        json.dump(state, f, indent=2)
    print(f"[asuraswrath] v1.2 patches written: {ppu_key} ({len(blocks)} block(s))")


def configure_engine():
    try:
        os.makedirs(RPCS3_CFG_DIR, exist_ok=True)
        if not os.path.exists(RPCS3_CFG): return
        update_yml(RPCS3_CFG, {
            "Core/PPU Modules Mode": "Prefer",
            "Core/PPU Modules Dir": f"{ROM_DATA}/"
        })
    except: pass


def main(argv=None):
    """No arguments: the GUI, exactly as before. With --game / --prepare the
    launcher runs windowless, for RecompLauncher and shortcuts (see
    recomplauncher.json)."""
    ap = argparse.ArgumentParser(prog="asuraswrath",
        description="Asura's Wrath — native recomp launcher")
    ap.add_argument("path", nargs="?", help="your copy: the .iso, or the game folder")
    ap.add_argument("--game", dest="game_opt", metavar="PATH",
        help="your copy of the game, same as the positional path")
    ap.add_argument("--prepare", action="store_true",
        help="build the native PPU module without a window, with progress lines")
    ap.add_argument("--dry-run", action="store_true",
        help="print the engine command instead of starting the game")
    ap.add_argument("--version", action="version", version="asuraswrath 1.2-asura")
    args = ap.parse_args(argv)

    path = args.game_opt or args.path
    if not path and args.prepare:
        if os.path.exists(CFG_FILE):
            with open(CFG_FILE) as f:
                for line in f:
                    if line.startswith("game_path="):
                        path = line.split("=", 1)[1].strip().strip('"')
    if not path:
        return None  # GUI mode: unchanged behaviour

    path = resolve_disc_path(path)
    if not os.path.exists(path):
        print(f"asuraswrath: no such game path: {path}", file=sys.stderr)
        return 2

    settings = load_settings()
    cmd = game_command(settings, path)
    if args.dry_run:
        print(" ".join(cmd))  # touches nothing on disk
        return 0

    save_pkg_path(path)
    apply_settings(settings)
    configure_engine()

    if args.prepare or not os.path.exists(MODULE_FILE):
        if args.prepare and module_is_current(path):
            print("progress 1.00 Native module already built from this copy", flush=True)
            return 0
        if not args.prepare:
            print("[asuraswrath] first run: building the native PPU module", flush=True)
        rc = build_module(path, quiet=not args.prepare)
        if rc != 0:
            print(f"asuraswrath: native module build failed ({rc})", file=sys.stderr)
            return 3
    if args.prepare:
        return 0
    return subprocess.call(cmd)


if __name__ == "__main__":
    rc = main()
    if rc is None:
        root = tk.Tk()
        app = AsuraLauncherApp(root)
        root.mainloop()
    else:
        sys.exit(rc)
