filepath = "/root/efesto-qa/source/backend/src/services/categoryNotificationService.js"

with open(filepath, "r") as f:
    content = f.read()

old = """async function notifyInteresado(lead, conversation, client, reason = 'Prospecto calificado') {
  return notifyCategoryChange(lead, conversation, client, 'INTERESADO', reason);
}"""

new = """async function notifyInteresado(lead, conversation, client, reason = 'Prospecto calificado') {
  // Intentar notificar al agente que acopio la propiedad de interes
  if (lead?.qualification?.propertyType) {
    try {
      const matchedProperty = await prisma.property.findFirst({
        where: { clientId: client.id, propertyType: { contains: lead.qualification.propertyType, mode: 'insensitive' }, deactivatedAt: null, acquiredById: { not: null } },
        include: { acquiredBy: { select: { id: true, name: true, phone: true } } }
      });
      if (matchedProperty?.acquiredBy?.phone) {
        const instance = await prisma.whatsappInstance.findFirst({ where: { clientId: client.id, status: 'connected' } });
        if (instance) {
          const msg = `🔔 *PROSPECTO INTERESADO*\\n\\n👤 *${lead.name || conversation.remoteName || 'Sin nombre'}*\\n📱 ${conversation.remoteNumber}\\n🏠 Propiedad: ${matchedProperty.title || 'N/A'}\\n💰 Valor: $${matchedProperty.price ? Number(matchedProperty.price).toLocaleString() : 'N/A'}\\n\\n📋 ${reason}\\n\\nEste prospecto fue asignado a ti porque acopiaste esta propiedad.`;
          await evolutionService.sendMessage(instance.instanceName, formatPhoneNumber(matchedProperty.acquiredBy.phone), msg);
          // Asignar lead al agente
          await prisma.lead.update({ where: { id: lead.id }, data: { assignedToId: matchedProperty.acquiredBy.id, assignedAt: new Date() } });
          console.log('[Notify] Interesado notificado al agente que acopio: ' + matchedProperty.acquiredBy.name);
        }
      }
    } catch (e) { console.error('[Notify] Error notifying acopio agent:', e.message); }
  }
  // Tambien notificar al admin/numero general
  return notifyCategoryChange(lead, conversation, client, 'INTERESADO', reason);
}"""

if old in content:
    content = content.replace(old, new)
    with open(filepath, "w") as f:
        f.write(content)
    print("OK - notifyInteresado updated with property agent routing")
else:
    print("ERROR - block not found")
