"""Gate critical rolls on native full forehand windup; add one isolated PCM SFX."""
from pathlib import Path
import hashlib
import struct

ORIGIN=0x2AD000
SFX_TABLE=0x2AD200
PCM_TABLE=0x2AD400
STREAM=0x2AD480
SAMPLE=0x2AE000
SOUND_ID=123


def install(data, assemble, patch, with_flash=True, with_sound=True):
    code=assemble('critical_slap', ORIGIN)
    assert len(code)<SFX_TABLE-ORIGIN
    patch(ORIGIN,b'\xFF'*len(code),code)
    patch(0xC378,bytes.fromhex('4240102b006c'),bytes.fromhex('4eb9002ad000'))
    patch(0xC4A8,bytes.fromhex('4ef9002ff400'),bytes.fromhex('4ef9002ad004'))
    if not with_sound:
        return
    sample=Path(__file__).with_name('critical_twin_cobra.pcm').read_bytes()
    assert len(sample)==4497 and sample[-1]==0 and 0 not in sample[:-1]
    assert hashlib.sha256(sample).hexdigest()=='ce014d721f2022444e19bcc8617f34fd79e2f16b6938745f8e3fdcaa4d456240'
    patch(SAMPLE,b'\xFF'*len(sample),sample)
    old_pcm=bytes(data[0x1B01C:0x1B094])
    patch(PCM_TABLE,b'\xFF'*128,old_pcm+struct.pack('>II',SAMPLE,0))
    # Native PCM voice patch6F; note/rate chosen from captured hardware-driver
    # playback. One-shot stream with bounded note-off; other samples unchanged.
    stream=bytes((0,0xC0,0x6F,0,0,0xE0,0x19,0xB0,0,0x90,60,127,72,0x80,60,0,0,0,255,255))
    patch(STREAM,b'\xFF'*len(stream),stream)
    old_table=bytes(data[0x2C648:0x2C648+123*4])
    patch(SFX_TABLE,b'\xFF'*(124*4),old_table+struct.pack('>I',STREAM))
    patch(0x1A294,bytes.fromhex('b07c007a'),bytes.fromhex('b07c007b'))
    patch(0x1A29E,bytes.fromhex('b07c00306d0000066100005c'),bytes.fromhex('4eb9002ad00c4e714e714e71'))
    patch(0x1A2C8,bytes.fromhex('41f90002c648'),bytes.fromhex('41f9002ad200'))
    patch(0x1A77E,bytes.fromhex('43fa089c2231000420310000'),bytes.fromhex('4eb9002ad0084e714e714e71'))
