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

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

# Replace the photo sending decision block
old_block = """      // === NUEVO: Enviar fotos de propiedades mencionadas ===
      if (mentionedProperties.length > 0) {
        // Re-check FRESCO antes de iniciar envío de fotos
        const convBeforePhotos = await prisma.conversation.findUnique({
          where: { id: conversationId },
          select: { aiResponseEnabled: true }
        });
        if (!convBeforePhotos?.aiResponseEnabled) {
          console.log('🛑 [AgentService] AI desactivada, omitiendo TODAS las fotos');
          mentionedProperties = []; // Vaciar para no entrar al loop
        }
      }

      if (mentionedProperties.length > 0) {
        console.log(`📸 [AgentService] Enviando fotos de ${mentionedProperties.length} propiedad(es)...`);

        const MAX_IMAGES_PER_PROPERTY = 3; // Máximo de fotos por propiedad"""

new_block = """      // === Enviar fichas/fotos de propiedades mencionadas ===
      if (mentionedProperties.length > 0) {
        // Re-check antes de iniciar envio
        const convBeforePhotos = await prisma.conversation.findUnique({
          where: { id: conversationId },
          select: { aiResponseEnabled: true }
        });
        if (!convBeforePhotos?.aiResponseEnabled) {
          console.log('🛑 [AgentService] AI desactivada, omitiendo fichas/fotos');
          mentionedProperties = [];
        }
      }

      // Detectar si el prospecto pidio fotos explicitamente
      const askedForPhotos = /(?:quiero|envía|envíame|manda|muéstra|muestrame|puedo ver|ver|pásame|pasame).*(?:foto|imagen|image)/i.test(messageText)
        || /(?:foto|fotos|imagen|imagenes)/i.test(messageText);

      if (mentionedProperties.length > 0) {
        console.log(`🔗 [AgentService] Enviando fichas de ${mentionedProperties.length} propiedad(es)${askedForPhotos ? ' + fotos' : ' (sin fotos, no las pidio)'}...`);

        const MAX_IMAGES_PER_PROPERTY = askedForPhotos ? 3 : 0; // Fotos SOLO si las pidio"""

content = content.replace(old_block, new_block)

with open(filepath, "w") as f:
    f.write(content)

print("OK - agent photo logic updated")
