filepath = "/root/efesto-qa/source/backend/src/routes/webhook.js"

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

old_routing = """    const messageData = {
      remoteJid: resolvedJid,
      key: data.key,  // Incluir key completa para descargar medios
      message: data.message,
      pushName: data.pushName
    };

    // Check instance purpose for routing
    const instance = await prisma.whatsappInstance.findUnique({
      where: { instanceName },
      select: { purpose: true }
    });"""

new_routing = """    const messageData = {
      remoteJid: resolvedJid,
      key: data.key,  // Incluir key completa para descargar medios
      message: data.message,
      pushName: data.pushName
    };

    // Smart filter: check if conversation existed before connection
    const instance = await prisma.whatsappInstance.findUnique({
      where: { instanceName },
      select: { purpose: true, connectedAt: true, id: true }
    });

    if (instance?.connectedAt) {
      const phoneNumber = resolvedJid?.replace('@s.whatsapp.net', '') || '';
      const existingConvo = await prisma.conversation.findFirst({
        where: { instanceId: instance.id, remoteNumber: phoneNumber },
        select: { id: true, lastMessageAt: true, aiResponseEnabled: true }
      });

      if (existingConvo) {
        const fourMonthsAgo = new Date();
        fourMonthsAgo.setMonth(fourMonthsAgo.getMonth() - 4);

        if (existingConvo.lastMessageAt > fourMonthsAgo) {
          // Conversacion reciente pre-existente: apagar IA y no contestar
          if (existingConvo.aiResponseEnabled) {
            await prisma.conversation.update({
              where: { id: existingConvo.id },
              data: { aiResponseEnabled: false }
            });
            console.log('Conversation ' + phoneNumber + ' existed before reconnect. AI disabled.');
          }
          return;
        } else {
          console.log('Conversation ' + phoneNumber + ' inactive >4 months. Treating as potential new client.');
        }
      }
      // New conversation (not in DB) - will be created by the service and AI will respond
    }"""

if old_routing in content:
    content = content.replace(old_routing, new_routing)
    with open(filepath, "w", errors="surrogateescape") as f:
        f.write(content)
    print("OK - smart conversation filter added")
else:
    print("ERROR - could not find routing block")
