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

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

old = """    // Detectar propiedades mencionadas en la respuesta para enviar sus fotos
    const mentionedProperties = detectMentionedProperties(cleanResponse, properties);

    // Retornar objeto con texto y propiedades mencionadas
    return {"""

new = """    // Detectar propiedades mencionadas en la respuesta para enviar sus fotos
    const mentionedProperties = detectMentionedProperties(cleanResponse, properties);

    // Auto-fill lead value with highest mentioned property price
    if (mentionedProperties.length > 0 && lead) {
      const maxPrice = Math.max(...mentionedProperties.map(p => p.price || 0));
      if (maxPrice > 0) {
        const currentLead = await prisma.lead.findUnique({ where: { id: lead.id }, select: { value: true } });
        if (!currentLead?.value || maxPrice > currentLead.value) {
          await prisma.lead.update({ where: { id: lead.id }, data: { value: maxPrice } });
          console.log('[Qualifier] Auto-set lead value to $' + maxPrice.toLocaleString() + ' from property interest');
        }
      }
    }

    // Retornar objeto con texto y propiedades mencionadas
    return {"""

if old in content:
    content = content.replace(old, new)
    with open(filepath, "w") as f:
        f.write(content)
    print("OK - lead value auto-fill added")
else:
    print("ERROR - block not found")
