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

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

# Replace random agent selection with property-based routing
old_selection = """  // Elegir agente aleatorio
  const selectedAgent = agents[Math.floor(Math.random() * agents.length)];
  console.log(`📞 [Handoff] Agente seleccionado: ${selectedAgent.name} (${selectedAgent.phone})`);"""

new_selection = """  // Buscar agente que acopio la propiedad de interes
  let selectedAgent = null;
  if (lead?.qualification?.propertyType) {
    const matchedProperty = await prisma.property.findFirst({
      where: { clientId, propertyType: { contains: lead.qualification.propertyType, mode: 'insensitive' }, deactivatedAt: null, acquiredById: { not: null } },
      include: { acquiredBy: { select: { id: true, name: true, phone: true } } },
      orderBy: { price: 'desc' }
    });
    if (matchedProperty?.acquiredBy?.phone) {
      selectedAgent = matchedProperty.acquiredBy;
      console.log(`🏠 [Handoff] Agente por acopio: ${selectedAgent.name} (propiedad: ${matchedProperty.title})`);
      // Asignar lead al agente que acopio
      if (lead) {
        await prisma.lead.update({ where: { id: lead.id }, data: { assignedToId: selectedAgent.id, assignedAt: new Date() } });
      }
    }
  }
  // Fallback: agente aleatorio si no hay acopio
  if (!selectedAgent) {
    selectedAgent = agents[Math.floor(Math.random() * agents.length)];
  }
  console.log(`📞 [Handoff] Agente seleccionado: ${selectedAgent.name} (${selectedAgent.phone})`);"""

if old_selection in content:
    content = content.replace(old_selection, new_selection)
    with open(filepath, "w") as f:
        f.write(content)
    print("OK - property-based agent routing added")
else:
    print("ERROR - block not found")
