import re

# Read the full template
with open(r'C:\Users\User\.config\opencode\skills\hl-subaccount-setup\sprint-dashboard-template.html', 'r', encoding='utf-8') as f:
    html = f.read()

# ===== Replace all placeholders =====

# Placeholders that are actually code (DO NOT replace)
code_placeholders = {
    '[data-phase="${phaseId}"]',
    '[data-theme="dark"]',
    '[type="checkbox"]',
}

replacements = {
    '[BRAND_NAME]': 'Home Solutions TT',
    '[INDUSTRY]': 'Real Estate / Residential Home Development',
    '[PIPELINE_TYPE]': 'Real Estate Sales Pipeline',
    '[PIPELINE_TEMPLATE]': 'Real Estate (New Inquiry -> Pre-qualified -> Tour Scheduled -> Offer/Proposal -> Under Contract -> Closed)',
    '[PRIMARY_COLOR]': '#0a9444',
    '[DATE]': 'June 16, 2026',
    
    # Phase 4: Bot Configuration
    '[BOT_NAME]': 'HS Assistant',
    '[TONE]': 'Warm, professional, trustworthy, never pushy',
    '[GOLDEN_RULE]': 'Never assume the buyer budget or timeline. Always ask directly before proposing.',
    '[QUALIFICATION_GOAL]': 'identificar si el lead es comprador de primera vivienda, inversor, diaspora o lujo',
    '[CONVERSION_GOAL]': 'agendar una visita al proyecto de su interes o una consultoria de financiamiento',
    '[SERVICE]': 'Home Purchase / Real Estate',
    '[SERVICE_KEY]': 'HOME_PURCHASE',
    '[SERVICE_KEYWORD]': 'casa, apartamento, vivienda, invertir, comprar',
    '[SERVICE_TYPE]': 'Residential Real Estate',
    
    # Bot Questions
    '[BOT_QUESTION_1]': 'Que tipo de propiedad estas buscando? Eres comprador por primera vez, inversor, o buscas una propiedad de lujo?',
    '[BOT_QUESTION_2]': 'En que proyecto tienes interes? Tenemos Lotus en Chaguanas, Q Building en Belmont, City Heights en San Fernando, EastLake North en Arima, North Hills en Santa Cruz, y Eighteen Moka.',
    '[BOT_QUESTION_3]': 'Cual es tu rango de presupuesto aproximado? Nuestras propiedades estan desde TT$1.2M hasta TT$1.5M+.',
    '[BOT_QUESTION_4]': 'Tienes ya financiamiento aprobado o te gustaria que te ayudemos con opciones? Trabajamos con Republic Bank, Scotiabank, TTMB, First Citizens, y mas.',
    '[BOT_QUESTION_5]': 'Cuando estarias listo para mudarte o comenzar el proceso de compra?',
    '[BOT_QUESTION_6]': 'Te gustaria agendar una visita para ver el proyecto en persona o prefieres un tour virtual primero?',
    
    # Field keys
    '[field_key_1]': 'property_type_seeking',
    '[field_key_2]': 'project_interest',
    '[field_key_3]': 'budget_range',
    '[field_key_4]': 'financing_status',
    '[field_key_5]': 'timeline_to_move',
    '[field_key_6]': 'tour_preference',
    
    # Example outputs
    '[EXAMPLE_OUTPUT_1A]': 'Primera vivienda - comprador primerizo',
    '[EXAMPLE_OUTPUT_2A]': 'Lotus, Chaguanas / EastLake North, Arima',
    '[EXAMPLE_OUTPUT_3A]': 'TT$1.2M - TT$1.4M',
    '[EXAMPLE_OUTPUT_4A]': 'Necesito financiamiento / TTMF 2%',
    '[EXAMPLE_OUTPUT_5A]': 'En los proximos 3-6 meses',
    '[EXAMPLE_OUTPUT_6A]': 'Visita presencial este fin de semana / Tour virtual',
    
    # Action names
    '[ACTION_NAME_1]': 'Book Appointment - Site Visit or Financing Consult',
    '[ACTION_NAME_2]': 'WF: Mover a Oportunidad (IA agenda reunion)',
    '[ACTION_NAME_3]': 'WF: Descalificados (IA descalifica)',
    '[ACTION_NAME_4]': 'Save: Tipo de propiedad buscada',
    '[ACTION_NAME_5]': 'Save: Estado de financiamiento',
    '[ACTION_NAME_6]': 'Stop Bot: Compra completada',
    
    # Disqualification
    '[DISQUALIFIED_FINAL_MESSAGE]': 'Entendemos completamente. Si en el futuro tu situacion cambia o quieres explorar opciones, estamos aqui para ti. Gracias por tu interes en Home Solutions TT!',
    
    # Transfer to human
    '[HUMAN_ASSIGNED_USER_ID]': 'Anabella Dini (adini@homesolutionstt.com)',
    '[HUMAN_REQUEST_PHRASE_1]': 'Quiero hablar con un asesor',
    '[HUMAN_TRANSFER_MESSAGE]': 'Con gusto te transfiero con un asesor de Home Solutions que podra ayudarte personalmente. Por favor espera mientras te conectamos.',
    
    # Missing info
    '[MISSING_INFO_MESSAGE]': 'No tengo esa informacion especifica. Permiteme transferir tu consulta a nuestro equipo de ventas que podra darte una respuesta mas detallada.',
    '[MISSING_INFO_USER]': 'Anabella Dini',
    
    # Unresolved
    '[UNRESOLVED_MESSAGE]': 'He intentado varias veces pero no he podido resolver tu consulta. He escalado tu solicitud a nuestro equipo de soporte.',
    '[UNRESOLVED_USER]': 'Anabella Dini',
    
    # Wrong service
    '[WRONG_SERVICE_MESSAGE]': 'Ese servicio esta fuera de mi alcance directo, pero tengo un colega especializado que puede ayudarte. Te transfiero ahora.',
    '[WRONG_SERVICE_PHRASE_1]': 'Esto no es sobre compra de vivienda',
    '[WRONG_SERVICE_USER_NAME]': 'Anabella Dini',
    
    # Goodbye
    '[GOODBYE_FINAL_MESSAGE]': 'Gracias por conversar con Home Solutions TT! Si necesitas algo mas, no dudes en escribirnos. Que tengas un excelente dia!',
    '[GOODBYE_PHRASE_1]': 'gracias, adios, chao, bye',
    
    # Booking
    '[booking text]': 'Excelente! Me encantaria agendar una visita para que conozcas el proyecto. Que dia y horario te funciona mejor? Tenemos disponibles lunes a viernes de 9am a 4pm y sabados de 10am a 2pm.',
    
    # Calendar
    '[MAIN_CALENDAR]': 'Home Solutions TT - Site Visits Calendar',
    
    # Transfer messages
    '[TRANSFER_FINAL_MESSAGE]': 'Te he transferido con un asesor de Home Solutions que te atendera personalmente. Por favor espera su contacto.',
    '[TRANSFER_PHRASE_1]': 'transferir, transferencia, con un asesor',
    
    # Industry-specific rule
    '[INDUSTRY-SPECIFIC RULE]': 'TRINIDAD REAL ESTATE: Siempre pregunta si el lead tiene financiamiento pre-aprobado. Menciona el TTMF 2% fijo si el presupuesto es bajo TT$1.5M. Para inversores, destaca datos de rentabilidad y apreciacion.',
    
    # Conditions
    '[conditions]': 'TIPO A: Presupuesto menor a TT$800K | TIPO B: Fuera del area de interes | TIPO C: No califica para financiamiento | TIPO D: Ya compro con otro desarrollador',
    
    # Next question
    '[NEXT QUESTION]': 'Te gustaria saber mas sobre opciones de financiamiento o prefieres agendar una visita directamente?',
    
    # Question
    '[QUESTION]': 'Que te parece si empezamos por conocer que tipo de hogar estas buscando?',
    
    # Reason
    '[reason]': 'El lead no califica segun los criterios establecidos',
    
    # Hours/days
    '[REACTIVATE_HOURS]': '12',
    '[WRONG_SERVICE_REACTIVATE_DAYS]': '1',
    
    # Additional placeholders
    '[SECONDARY_COLOR]': '#3a3a3c',
    '[ROLE]': 'Sales & Qualification Assistant',
    '[PLACEHOLDER]': '',
    '[message]': 'Gracias por contactar a Home Solutions TT! Como puedo ayudarte hoy?',
    '[question text]': 'Cuentame, que te motiva a buscar una nueva propiedad?',
    
    # Field labels
    '[FIELD_LABEL_1]': 'Tipo de propiedad buscada',
    '[FIELD_LABEL_2]': 'Proyecto de interes',
    '[FIELD_LABEL_3]': 'Rango de presupuesto',
    '[FIELD_LABEL_4]': 'Estado de financiamiento',
    '[FIELD_LABEL_5]': 'Tiempo estimado para mudanza',
    '[FIELD_LABEL_6]': 'Preferencia de visita',
    
    # Example output variants
    '[EXAMPLE_OUTPUT_1B]': 'Inversor - segunda propiedad',
    '[EXAMPLE_OUTPUT_1C]': 'Lujo - Eighteen Moka',
    '[EXAMPLE_OUTPUT_2B]': 'Q Building, Belmont / North Hills, Santa Cruz',
    '[EXAMPLE_OUTPUT_2C]': 'Eighteen Moka, Maraval',
    '[EXAMPLE_OUTPUT_3B]': 'TT$1.4M - TT$1.5M',
    '[EXAMPLE_OUTPUT_3C]': 'TT$1.5M+',
    '[EXAMPLE_OUTPUT_4B]': 'Pre-aprobado por Republic Bank',
    '[EXAMPLE_OUTPUT_4C]': 'Pago de contado',
    '[EXAMPLE_OUTPUT_5B]': 'En los proximos 1-2 meses',
    '[EXAMPLE_OUTPUT_5C]': 'Sin fecha definida / explorando opciones',
    '[EXAMPLE_OUTPUT_6B]': 'Tour virtual por WhatsApp / Fotos del proyecto',
    '[EXAMPLE_OUTPUT_6C]': 'Quiero recibir el brochure primero',
    
    # Goodbye phrases
    '[GOODBYE_PHRASE_2]': 'muchas gracias, hasta luego, nos vemos',
    '[GOODBYE_PHRASE_3]': 'ok gracias, bye bye, buen dia',
    
    # Human request phrases
    '[HUMAN_REQUEST_PHRASE_2]': 'Necesito ayuda de un agente de ventas',
    '[HUMAN_REQUEST_PHRASE_3]': 'Puedo hablar con alguien de Home Solutions?',
    
    # Transfer phrases
    '[TRANSFER_PHRASE_2]': 'pasar a un asesor, conectame con alguien',
    '[TRANSFER_PHRASE_3]': 'quisiera hablar con un representante',
    
    # Wrong service phrases
    '[WRONG_SERVICE_PHRASE_2]': 'Estoy buscando otro tipo de servicio',
    '[WRONG_SERVICE_PHRASE_3]': 'No es sobre compra de propiedad',
    
    # Special character variants of golden rule and tone
}

# Fix the golden rule and tone that have special chars
html = html.replace('[GOLDEN_RULE \u2014 e.g., Nunca asumas el servicio]', '[GOLDEN_RULE]')
html = html.replace('[TONE \u2014 e.g., Amigable, directo, profesional]', '[TONE]')

# Do the replacements
for placeholder, value in replacements.items():
    html = html.replace(placeholder, value)

# Also replace the CSS primary color default
html = html.replace('#20bf62', '#0a9444')

# Switch language to English for T&T market
html = html.replace('lang="es"', 'lang="en"')

# Write the output
output_path = r'C:\Users\User\Documents\opencode_apps\marketing_brains\HomeSolutions\HomeSolutions_TT_GHL_Sprint_Dashboard.html'
with open(output_path, 'w', encoding='utf-8') as f:
    f.write(html)

print(f'Written: {output_path}')
print(f'File size: {len(html)} bytes')

# Check remaining placeholders
remaining = re.findall(r'\[(.*?)\]', html)
remaining = [r for r in remaining if r not in ['data-phase', 'data-src', 'data-theme', 'type', 'BRACKETED', 'lightboxData.current', '']]
if remaining:
    print(f'Remaining placeholders ({len(remaining)}):')
    for r in sorted(set(remaining)):
        print(f'  [{r}]')
else:
    print('All placeholders replaced!')
