#!/usr/bin/env python3
"""Simplificar Killa: quitar el taller (Rafael, 2026-10-28).
- Misión fallida por arroyo con subtítulo 'Fuiste arrastrado por un arroyo'.
- Diálogo de misión fallida: sin flecha de reiniciar, sin 'Ir al taller'.
- Panel lateral: sin estadísticas directas; botón ESTADÍSTICAS abre ventana nueva.
- Panel lateral: scroll con todo el contenido visible (padding inferior > barra fija).
- Sin panel de taller, sin abrirlo al pasar cerca ni al canalizar.
El punto de inicio/respawn en el mapa (constante TALLER) se mantiene: es un
lugar, no el panel eliminado.
"""
import sys

def rep(path, old, new, count=1):
    s = open(path).read()
    if s.count(old) < 1:
        if new in s:
            print(f"SKIP (ya aplicado) {path}: {old[:60]!r}")
            return
        assert False, f"FALTA en {path}: {old[:90]!r}"
    s = s.replace(old, new, count)
    open(path, 'w').write(s)
    print(f"OK {path}: {old[:60]!r}")

P = 'patch.py'
M = 'misiones.js'
H = 'hudfix-live.html'

# ---------- 1. Diálogo de misión fallida (misiones.js) ----------
# Motivo sin prefijo policial fijo (antes '🚔 ' + motivo, mal para arroyo y
# para tiempo agotado); botones: Reiniciar (sin flecha) + Ver misiones.
rep(M,
    "    + '<div style=\"font-size:14px;line-height:1.6\">🚔 ' + motivo + '</div>'\n"
    "    + '<button class=\"okBtn okBtnGo\" style=\"width:100%;margin-top:14px\" onclick=\"misionFailReiniciar()\">↻ Reiniciar misión</button>'\n"
    "    + '<div style=\"display:flex;gap:8px;margin-top:10px\">'\n"
    "    + '<button class=\"okBtn okBtnBlue\" style=\"flex:1\" onclick=\"misionFailVer()\">📋 Ver misiones</button>'\n"
    "    + '<button class=\"okBtn okBtnAmber\" style=\"flex:1\" onclick=\"misionFailTaller()\">🔧 Ir al taller</button>'\n"
    "    + '</div>';",
    "    + '<div style=\"font-size:14px;line-height:1.6\">' + motivo + '</div>'\n"
    "    + '<button class=\"okBtn okBtnGo\" style=\"width:100%;margin-top:14px\" onclick=\"misionFailReiniciar()\">Reiniciar misión</button>'\n"
    "    + '<button class=\"okBtn okBtnBlue\" style=\"width:100%;margin-top:10px\" onclick=\"misionFailVer()\">Ver misiones</button>';")
rep(M,
    "function misionFailTaller() {\n"
    "  closeMisionOk();\n"
    "  openTaller();\n"
    "}",
    "/* Taller eliminado 2026-10-28: ya no hay botón 'Ir al taller' en este diálogo. */\n"
    "function misionFailTaller() {\n"
    "  closeMisionOk();\n"
    "  openPausa();\n"
    "}")
# Ayudante de fallo por arroyo, junto a openMisionFail.
rep(M,
    "function misionFailReiniciar() {",
    "/* Fallo por arroyo (Rafael, 2026-10-28): la misión en curso se da por\n"
    "   perdida y sale el cuadro de misión fallida con ese subtítulo. */\n"
    "function fallarMisionArroyo() {\n"
    "  const m = S.misionActiva;\n"
    "  if (!m) return false;\n"
    "  S.misionActiva = null; S.misionProg = 0; S.misionSaltos = 0; S.misionTiempo = 0;\n"
    "  S.mission = null;\n"
    "  if (S.person) S.person.setVisible(false);\n"
    "  if (S.ring) S.ring.setVisible(false);\n"
    "  if (S.busRing) S.busRing.setVisible(false);\n"
    "  el('timerWrap').style.display = 'none';\n"
    "  openMisionFail(m, 'Fuiste arrastrado por un arroyo');\n"
    "  return true;\n"
    "}\n"
    "function misionFailReiniciar() {")
# Comentario de inicio de misión: ya no es 'el taller', es el punto de inicio.
rep(M,
    "  /* Toda misión empieza en el taller (2026-10-24, orden de Rafael): el\n"
    "     jugador aparece en el taller, quieto y mirando al norte, con la cámara\n"
    "     centrada ahí. Igual que el regreso en grúa. Cubre todas las entradas:\n"
    "     menú, repetir, siguiente y reiniciar. */",
    "  /* Toda misión empieza en el punto de inicio (2026-10-24, orden de Rafael):\n"
    "     el jugador aparece ahí, quieto y mirando al norte, con la cámara\n"
    "     centrada ahí. Igual que el regreso en grúa. Cubre todas las entradas:\n"
    "     menú, repetir, siguiente y reiniciar. */")

# ---------- 2. Arrastre por arroyo -> misión fallida (patch.py) ----------
# towReal (función original, no texto de patch.py): añadir un rep en patch.py
# tras el renombre tow->towReal, para no generar pasajero nuevo si hay misión.
rep(P,
    'rep("function tow(reason) {\\n  if (S.sweptBusy) return;", "function towReal(reason) {\\n  if (S.sweptBusy) return;")',
    'rep("function tow(reason) {\\n  if (S.sweptBusy) return;", "function towReal(reason) {\\n  if (S.sweptBusy) return;")\n'
    'rep("  if (S.mission && S.mission.stage === \'dropoff\') { S.mission = null; spawnPickup(1400); }", "  if (S.mission && S.mission.stage === \'dropoff\') { S.mission = null; if (!S.misionActiva) spawnPickup(1400); }")')
# tow (grúa): tras towReal, si había misión, falla por arroyo.
rep(P,
    '"function tow(reason) { if (S.gruaBusy || S.sweptBusy) return; gruaAnim(function () { towReal(reason); }); }\\n"',
    '"function tow(reason) { if (S.gruaBusy || S.sweptBusy) return; gruaAnim(function () { towReal(reason); if (S.misionActiva && typeof fallarMisionArroyo === \'function\') fallarMisionArroyo(); }); }\\n"')
# riverLossReal (arroyo al río / grúa acuática): sin taller, sin pasajero
# nuevo si había misión; en ese caso, cuadro de misión fallida por arroyo.
rep(P,
    '"  S.scene.time.delayedCall(700, () => { S.sweptBusy = false; openTaller(); spawnPickup(900); });\\n"',
    '"  S.scene.time.delayedCall(700, () => { S.sweptBusy = false; if (S.misionActiva && typeof fallarMisionArroyo === \'function\') fallarMisionArroyo(); else spawnPickup(900); });\\n"')

# ---------- 3. Panel lateral: estadísticas a ventana nueva, sin taller ----------
# Estilo del botón nuevo en la barra de pausa.
rep(P,
    " .pbtnSalir{flex:1;border:0;border-radius:10px;padding:11px;font:800 14px Nunito,Arial,sans-serif;cursor:pointer;color:#fff;background:#e11d2e}",
    " .pbtnSalir{flex:1;border:0;border-radius:10px;padding:11px;font:800 14px Nunito,Arial,sans-serif;cursor:pointer;color:#fff;background:#e11d2e} .pbtnEst{flex:1;border:0;border-radius:10px;padding:11px;font:800 14px Nunito,Arial,sans-serif;cursor:pointer;color:#14202b;background:#ffd54f}")
# statsHTMLPausa: extraer la tabla a estadisticasHTML() y quitarla del panel;
# la barra fija pasa de IR AL TALLER a ESTADÍSTICAS.
rep(P,
    '"function statsHTMLPausa() {\\n"\n'
    '    "  const L = led();\\n"',
    '"function estadisticasHTML() {\\n"\n'
    '    "  const L = led();\\n"')
rep(P,
    '"    + \'</table>\'\\n"\n'
    '    "    + \'<div class=pbtnRow><button class=pbtnGo onclick=closePausa()>▶ SEGUIR JUGANDO</button><button class=pbtnTaller onclick=irAlTallerDesdePausa()>🔧 IR AL TALLER</button><button class=pbtnMulti onclick=irAMultiDesdePausa()>Modo Multijugador</button><button class=pbtnSalir onclick=salirDelJuegoDesdePausa()>Salir del juego</button></div>\';\\n"',
    '"    + \'</table>\';\\n"\n'
    '    "}\n"\n'
    '    "function statsHTMLPausa() {\\n"\n'
    '    "  return misionesHTMLPausa()\\n"\n'
    '    "    + \'<div class=pbtnRow><button class=pbtnGo onclick=closePausa()>▶ SEGUIR JUGANDO</button><button class=pbtnEst onclick=abrirEstadisticasDesdePausa()>📊 ESTADÍSTICAS</button><button class=pbtnMulti onclick=irAMultiDesdePausa()>Modo Multijugador</button><button class=pbtnSalir onclick=salirDelJuegoDesdePausa()>Salir del juego</button></div>\';\\n"\n'
    '    "}\n"\n'
    '    "function abrirEstadisticasDesdePausa() {\\n"\n'
    '    "  const p = document.getElementById(\'pausaPanel\');\\n"\n'
    '    "  if (p) p.classList.remove(\'open\');\\n"\n'
    '    "  const bk0 = document.getElementById(\'pausaBack\');\\n"\n'
    '    "  if (bk0) bk0.classList.remove(\'open\');\\n"\n'
    '    "  let bk = document.getElementById(\'estadisticasBack\');\\n"\n'
    '    "  if (!bk) {\\n"\n'
    '    "    bk = document.createElement(\'div\'); bk.id = \'estadisticasBack\'; bk.onclick = () => cerrarEstadisticas(); document.body.appendChild(bk);\\n"\n'
    '    "    const q = document.createElement(\'div\'); q.id = \'estadisticasPanel\'; q.innerHTML = \'<div id=estadisticasCard></div>\'; document.body.appendChild(q);\\n"\n'
    '    "    const st = document.createElement(\'style\');\\n"\n'
    '    "    st.textContent = \'#estadisticasBack{position:fixed;inset:0;z-index:96;background:rgba(6,10,14,.55);display:none} #estadisticasBack.open{display:block} #estadisticasPanel{position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);width:min(88vw,360px);max-height:92vh;overflow:auto;z-index:97;background:#101820;color:#eef4f8;border:1px solid rgba(255,255,255,.2);border-radius:16px;box-shadow:0 8px 30px rgba(0,0,0,.5);font-family:Nunito,Arial,sans-serif;padding:20px;box-sizing:border-box;display:none} #estadisticasPanel.open{display:block} #estadisticasPanel table{width:100%;border-collapse:collapse;font-size:14px} #estadisticasPanel td{padding:5px 4px;border-bottom:1px solid rgba(255,255,255,.08)} #estadisticasPanel .n{text-align:right;font-weight:700;white-space:nowrap}\';\\n"\n'
    '    "    document.head.appendChild(st);\\n"\n'
    '    "  }\\n"\n'
    '    "  document.getElementById(\'estadisticasCard\').innerHTML = estadisticasHTML() + \'<button class=pbtnGo style=width:100%;margin-top:14px onclick=cerrarEstadisticas()>← VOLVER A MISIONES</button>\';\\n"\n'
    '    "  bk.classList.add(\'open\');\\n"\n'
    '    "  document.getElementById(\'estadisticasPanel\').classList.add(\'open\');\\n"\n'
    '    "}\\n"\n'
    '    "function cerrarEstadisticas() {\\n"\n'
    '    "  const q = document.getElementById(\'estadisticasPanel\');\\n"\n'
    '    "  if (q) q.classList.remove(\'open\');\\n"\n'
    '    "  const bk = document.getElementById(\'estadisticasBack\');\\n"\n'
    '    "  if (bk) bk.classList.remove(\'open\');\\n"\n'
    '    "  openPausa();\\n"\n'
    '    "}\\n"')
# statsHTMLPausa ya no necesita el prefijo misionesHTMLPausa() + tabla: la
# función nueva statsHTMLPausa debe empezar con 'return misionesHTMLPausa()'.
# Pero el rep anterior dejó el cuerpo viejo: 'return misionesHTMLPausa() + ...'
# seguido de la tabla. Revisar y limpiar en el paso siguiente (verificación).

# openPausa: sin guarda de taller.
rep(P,
    '"function openPausa() {\\n"\n'
    '    "  if (!S.started) return;\\n"\n'
    '    "  const t = document.getElementById(\'tallerPanel\');\\n"\n'
    '    "  if (t && t.style.display === \'flex\') return;\\n"',
    '"function openPausa() {\\n"\n'
    '    "  if (!S.started) return;\\n"')
# Ir al taller desde pausa: ya no existe; si algo lo llama, vuelve al panel.
rep(P,
    '"function irAlTallerDesdePausa() {\\n"\n'
    '    "  const p = document.getElementById(\'pausaPanel\');\\n"\n'
    '    "  if (p) p.classList.remove(\'open\');\\n"\n'
    '    "  const bk = document.getElementById(\'pausaBack\');\\n"\n'
    '    "  if (bk) bk.classList.remove(\'open\');\\n"\n'
    '    "  openTaller();\\n"\n'
    '    "}\\n"',
    '"function irAlTallerDesdePausa() {\\n"\n'
    '    "  openPausa();\\n"\n'
    '    "}\\n"')
# Escape: sin rama de taller.
rep(P,
    '"    const t = document.getElementById(\'tallerPanel\');\\n"\n'
    '    "    if (t && t.style.display === \'flex\') { closeTaller(); return; }\\n"\n',
    '')
# Fondo completo: sin 'llega al taller'.
rep(P,
    "showAlert('🏗️ ¡Fondo completo! Llega al taller 🔧 a canalizar un arroyo'",
    "showAlert('🏗️ ¡Fondo completo! Abre el menú de misiones para canalizar un arroyo'")
# Proximidad al taller: ya no abre nada.
rep(P,
    '"  const dTaller = Phaser.Math.Distance.Between(car.x, car.y, TALLER.x, TALLER.y);\\n"\n'
    '    "  if (dTaller > 170) { S.tallerNear = false; S.tallerArmed = true; }\\n"\n'
    '    "  if (S.tallerArmed && dTaller < 115 && car.body.speed < 45 && !S.tallerNear) { S.tallerNear = true; openTaller(); }\\n"',
    '')
# Canalizar: sin taller como destino; siempre vuelve al panel lateral.
rep(P,
    '"  actuBarra(true); if (desdeLateral) { try { openPausa(); } catch (e) {} } else openTaller();\\n"',
    '"  actuBarra(true); try { openPausa(); } catch (e) {}\\n"')
# Texto oculto de portada: sin taller.
rep(P,
    "canaliza en el taller los 3 arroyos",
    "canaliza desde el menú de misiones los 3 arroyos")
# openTaller: panel eliminado; cualquier llamada vieja cae al panel lateral.
rep(P,
    '"function openTaller() {\\n"',
    '"function openTaller() { /* Taller eliminado 2026-10-28: sin panel; cae al menú lateral. */\\n"\n'
    '    "  try { if (S && S.started) openPausa(); } catch (e) {}\\n"\n'
    '    "  return;\\n"\n'
    '    "}\\n"\n'
    '    "function openTallerEliminado() {\\n"')

# ---------- 4. Scroll lateral completo (hudfix) ----------
rep(H,
    "  #pausaCard { padding-bottom:196px !important; }",
    "  #pausaCard { padding-bottom:300px !important; scroll-padding-bottom:280px !important; }\n"
    "  #pausaPanel { overflow:hidden !important; }\n"
    "  #pausaPanel .pbtnEst { background:#ffd54f !important; color:#14202b !important; border-radius:0 !important; clip-path:polygon(8px 0,100% 0,calc(100% - 8px) 100%,0 100%) !important; }\n"
    "  #pausaPanel .pbtnGo, #pausaPanel .pbtnEst { clip-path:polygon(12px 0,100% 0,calc(100% - 12px) 100%,0 100%) !important; }\n"
    "  #estadisticasPanel { background:linear-gradient(120deg,#061f38 0%,#0a3a5e 100%) !important; border:1px solid rgba(34,211,238,.4) !important; }\n"
    "  #estadisticasPanel .n { color:#ffd54f !important; }")
print("DONE (revisar statsHTMLPausa a mano)")
