#!/usr/bin/env python3
"""Música de menús (pista 1) + sonido de toque de botones, Killa 2026-10-28."""
def rep(path, old, new):
    s = open(path).read()
    if old not in s:
        if new in s:
            print('SKIP ya aplicado:', old[:60])
            return
        raise AssertionError('FALTA: ' + old[:90])
    open(path, 'w').write(s.replace(old, new, 1))
    print('OK:', old[:60])

P = 'patch.py'

# A. Funciones de música y clic, al inicio del script UI v2.
rep(P,
    "/* UI v2: navegación Portada -> Modo -> Misiones / Multijugador, con ATRÁS. */\n(function(){\n",
    "/* UI v2: navegación Portada -> Modo -> Misiones / Multijugador, con ATRÁS. */\n(function(){\n"
    "  /* Música de menús (Rafael, 2026-10-28): pista 1, Afrobeat Instrumental de Sub_Clair, en bucle, volumen moderado. Suena en portada/menús y se detiene al empezar misión/carrera, donde arranca la emisora. */\n"
    "  var menuAudio = null;\n"
    "  window.menuMusicStart = function() { try { if (!menuAudio) { menuAudio = new Audio('menu-musica.mp3'); menuAudio.loop = true; menuAudio.volume = 0.5; } if (menuAudio.paused) { var pr = menuAudio.play(); if (pr && pr.catch) pr.catch(function(){}); } } catch(e){} };\n"
    "  window.menuMusicStop = function() { try { if (menuAudio) { menuAudio.pause(); menuAudio.currentTime = 0; } } catch(e){} };\n"
    "  /* Sonido de toque de botones (Rafael, 2026-10-28): blip corto sintetizado con WebAudio, sin archivo. */\n"
    "  var clickCtx = null;\n"
    "  window.killaClick = function() { try { var AC = window.AudioContext || window.webkitAudioContext; if (!AC) return; if (!clickCtx) clickCtx = new AC(); var ctx = clickCtx; if (ctx.state === 'suspended') ctx.resume(); var t = ctx.currentTime; var o = ctx.createOscillator(), g = ctx.createGain(); o.type = 'sine'; o.frequency.setValueAtTime(1150, t); o.frequency.exponentialRampToValueAtTime(700, t + 0.08); g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(0.18, t + 0.012); g.gain.exponentialRampToValueAtTime(0.0001, t + 0.12); o.connect(g); g.connect(ctx.destination); o.start(t); o.stop(t + 0.13); } catch(e){} };\n"
    "  document.addEventListener('click', function(e) { try { var el = e.target && e.target.closest ? e.target.closest('button, .go') : null; if (el && !el.disabled) window.killaClick(); } catch(err){} });\n"
    "  document.addEventListener('click', function(e) { try { var ov = document.getElementById('startOverlay'); if (ov && getComputedStyle(ov).display !== 'none') window.menuMusicStart(); } catch(err){} });\n")

# B. Al mostrar cualquier vista de menú, arranca la música.
rep(P,
    "    window.killaUIVista = vista;\n",
    "    window.killaUIVista = vista;\n"
    "    try { window.menuMusicStart(); } catch(e) {}\n")

# C. Al empezar misión/carrera, detiene la música (luego arranca la emisora).
rep(P,
    "  window.killaUIStartMision = function(id){\n",
    "  window.killaUIStartMision = function(id){\n"
    "    try { window.menuMusicStop(); } catch(e) {}\n")
rep(P,
    "  window.killaUIStartCarrera = function(veh){\n",
    "  window.killaUIStartCarrera = function(veh){\n"
    "    try { window.menuMusicStop(); } catch(e) {}\n")

# D. startGame: por seguridad, también detiene la música antes de la emisora.
rep(P,
    "  S.started = true;\\n  sfxPlay('arranque');",
    "  S.started = true;\\n  try { if (window.menuMusicStop) window.menuMusicStop(); } catch (e) {}\\n  sfxPlay('arranque');")

# E. Ir a Multijugador desde pausa: es menú, así que para la emisora (la
# música de menús arranca con killaUIShow('multi')); antes solo la restauraba.
rep(P,
    "  if (typeof killaUIShow === 'function') killaUIShow('multi');\\n\"\n"
    "    \"  radioUnduck();\\n\"",
    "  if (typeof killaUIShow === 'function') killaUIShow('multi');\\n\"\n"
    "    \"  try { stopRadio(); } catch (e) {}\\n\"")
print('DONE')
