#!/usr/bin/env python3
# Reproduce SFZ-only crash. Load SFZ ch=1, no notes, poll every 0.2s.
import ctypes, os, struct, subprocess, sys, time

BRIDGE = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "build", "Release", "daw_vst_bridge.exe"))
SFZ = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "sfizz-src", "tests", "TestFiles", "g2_test.sfz"))
SHM_NAME = "SonicForge_DAW_IPC"
SIZE = 11160
ML, MR = 8, 1032
MIDI_Q, MIDI_Q_COUNT = 2064, 2832
CTRL_Q, CTRL_Q_COUNT = 2836, 11156

kern = ctypes.windll.kernel32
PAGE_READWRITE, FILE_MAP_ALL_ACCESS = 0x04, 0xF001F
kern.CreateFileMappingW.restype = ctypes.c_void_p
kern.CreateFileMappingW.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_wchar_p]
kern.MapViewOfFile.restype = ctypes.c_void_p
kern.MapViewOfFile.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_size_t]
kern.UnmapViewOfFile.restype = ctypes.c_int
kern.UnmapViewOfFile.argtypes = [ctypes.c_void_p]
kern.CloseHandle.restype = ctypes.c_int
kern.CloseHandle.argtypes = [ctypes.c_void_p]
h = kern.CreateFileMappingW(None, None, PAGE_READWRITE, 0, SIZE, SHM_NAME)
if not h: sys.exit("CreateFileMappingW failed")
v = kern.MapViewOfFile(h, FILE_MAP_ALL_ACCESS, 0, 0, 0)
if not v: sys.exit("MapViewOfFile failed")
buf = (ctypes.c_ubyte * SIZE).from_address(v)

def w32(o, x): struct.pack_into("<I", buf, o, x)
def set_str(o, s, cap):
    b = s.encode("utf-8")[:cap - 1]
    for i, x in enumerate(b): buf[o + i] = x
    for i in range(len(b), cap): buf[o + i] = 0

def note_on(ch, pitch, vel):
    w32(MIDI_Q_COUNT, 0)
    base = MIDI_Q
    buf[base] = 0x9; buf[base+1] = ch; buf[base+2] = pitch; buf[base+3] = vel
    buf[base+4] = 0; buf[base+5] = 0; buf[base+6] = 0; buf[base+7] = 0
    struct.pack_into("<I", buf, base + 8, 0)
    w32(MIDI_Q_COUNT, 1)

def load_instrument(itype, path, ch=0):
    w32(CTRL_Q_COUNT, 0)
    set_str(CTRL_Q + 16, path, 1024)
    w32(CTRL_Q + 0, 2); w32(CTRL_Q + 4, itype); w32(CTRL_Q + 8, 0); w32(CTRL_Q + 12, ch)
    w32(CTRL_Q_COUNT, 1)

env = dict(os.environ, SF_PARENT_PID=str(os.getpid()), SF_SAMPLE_RATE="44100")
logpath = os.path.join(os.path.dirname(BRIDGE), "repro_sfz.txt")
logf = open(logpath, "w", encoding="utf-8")
proc = subprocess.Popen([BRIDGE], env=env, cwd=os.path.dirname(BRIDGE),
                        stdout=logf, stderr=subprocess.STDOUT, text=True)
try:
    load_instrument(3, SFZ, ch=1)
    t0 = time.time()
    last_line = ""
    while time.time() - t0 < 8:
        if proc.poll() is not None:
            print("DIED after %.2fs rc=%s" % (time.time() - t0, proc.poll()))
            break
        time.sleep(0.2)
    else:
        print("ALIVE after 8s")
    logf.flush()
    print("log:", open(logpath, encoding="utf-8").read())
finally:
    if proc.poll() is None:
        proc.terminate()
        try: proc.wait(timeout=3)
        except subprocess.TimeoutExpired: proc.kill()
    logf.close()
    kern.UnmapViewOfFile(v)
    kern.CloseHandle(h)
