#!/usr/bin/env python3
"""
Patch MobileTicketAgent.vue to add socket realtime listeners.
globalStore is already imported from a previous patch - just destructure $socket.
"""

TARGET = '/home/frappe/frappe-bench/frappe-bench/apps/helpdesk/desk/src/pages/ticket/MobileTicketAgent.vue'

with open(TARGET, 'r') as f:
    content = f.read()

# Verify globalStore is already imported
assert 'globalStore' in content, 'ERROR: globalStore not found - check imports'

# ── 1. Add $socket destructure after existing globalStore usage ──────────────
# globalStore() is called as `const { $dialog } = globalStore();` in the file
OLD_STORE_INIT = 'const ticketStatusStore = useTicketStatusStore();\nconst { getUser } = useUserStore();'
NEW_STORE_INIT = '''const ticketStatusStore = useTicketStatusStore();
const { getUser } = useUserStore();
const { $socket } = globalStore();'''

assert OLD_STORE_INIT in content, 'ERROR: store init anchor not found'
# Only patch if $socket not already added
if '$socket' not in content:
    content = content.replace(OLD_STORE_INIT, NEW_STORE_INIT, 1)
else:
    print('INFO: $socket already present, skipping destructure')

# ── 2. Patch onMounted to add socket listeners ───────────────────────────────
OLD_MOUNTED = '''onMounted(() => {
  document.title = props.ticketId;
});'''

NEW_MOUNTED = '''onMounted(() => {
  document.title = props.ticketId;

  // BMG: realtime — reload when a new comment is posted
  $socket.on("helpdesk:ticket-comment", (data) => {
    if (String(data.ticket_id) === String(props.ticketId)) {
      ticket.reload();
    }
  });

  // BMG: realtime — reload when ticket is updated by another user
  $socket.on("helpdesk:ticket-update", (data) => {
    if (String(data.ticket_id) === String(props.ticketId)) {
      ticket.reload();
    }
  });
});'''

assert OLD_MOUNTED in content, 'ERROR: onMounted anchor not found'
content = content.replace(OLD_MOUNTED, NEW_MOUNTED, 1)

# ── 3. Patch onUnmounted to remove socket listeners ─────────────────────────
OLD_UNMOUNTED = '''onUnmounted(() => {
  document.title = "Helpdesk";
});'''

NEW_UNMOUNTED = '''onUnmounted(() => {
  document.title = "Helpdesk";
  $socket.off("helpdesk:ticket-comment");
  $socket.off("helpdesk:ticket-update");
});'''

assert OLD_UNMOUNTED in content, 'ERROR: onUnmounted anchor not found'
content = content.replace(OLD_UNMOUNTED, NEW_UNMOUNTED, 1)

with open(TARGET, 'w') as f:
    f.write(content)

print('PATCH OK')
