#!/usr/bin/env python3
"""
Script to update the Contact Us page with content from scraped pages.
"""

import json
import re
from pathlib import Path

def load_scraped_data():
    """Load scraped pages data."""
    scraped_file = Path('scraped_content/data/scraped_pages.json')
    with open(scraped_file, 'r', encoding='utf-8') as f:
        return json.load(f)

def get_contact_content(scraped_data):
    """Extract contact information from scraped data."""
    contact_page = scraped_data.get('https://smart-const.com/contact-us/', {})
    text_data = contact_page.get('text', {})
    
    # Extract business hours from lists
    business_hours = []
    lists = text_data.get('lists', [])
    for lst in lists:
        for item in lst:
            if 'Saturday' in item or 'Thursday' in item or 'Friday' in item:
                business_hours.append(item)
    
    return {
        'title': text_data.get('title', ''),
        'headings': text_data.get('headings', []),
        'paragraphs': text_data.get('paragraphs', []),
        'business_hours': business_hours[:3] if business_hours else [],
        'company_name': 'Smart Projects Construction Co.',
        'company_short': 'SPCC'
    }

def update_contact_page(file_path, content_data, is_arabic=False):
    """Update the contact page with scraped content."""
    encodings = ['utf-8', 'latin-1', 'cp1252', 'iso-8859-1']
    content = None
    
    for encoding in encodings:
        try:
            with open(file_path, 'r', encoding=encoding) as f:
                content = f.read()
            break
        except UnicodeDecodeError:
            continue
    
    if content is None:
        print(f"Could not read {file_path}")
        return False
    
    # Update company name references
    if is_arabic:
        content = content.replace('El Seif', 'شركة المشاريع الذكية للإنشاءات')
        content = content.replace('ESEC', 'SPCC')
        
        # Update heading
        heading_pattern = r'(<h3>Connect with El Seif</h3>)'
        new_heading = '<h3>تواصل مع شركة المشاريع الذكية للإنشاءات</h3>'
        content = re.sub(heading_pattern, new_heading, content)
        
        # Update description
        desc_pattern = r'(<p>\s*We would love to hear from you, so feel free to reach out to us\s*and let\'s start building a successful partnership together\.\s*</p>)'
        new_desc = f'''<p>
                نحن نود أن نسمع منك، فلا تتردد في التواصل معنا
                وابدأ بناء شراكة ناجحة معاً.
              </p>'''
        content = re.sub(desc_pattern, new_desc, content, flags=re.DOTALL)
        
        # Add business hours section if not exists
        if content_data['business_hours']:
            hours_text = '<div class="contactUsNumbers mt-4">\n<h4>ساعات العمل</h4>\n'
            for hours in content_data['business_hours']:
                hours_text += f'<p>{hours}</p>\n'
            hours_text += '</div>'
            
            # Insert after phone number section
            phone_section_pattern = r'(</div>\s*</div>\s*<div class="w-100">)'
            content = re.sub(phone_section_pattern, rf'{hours_text}\1', content, count=1)
    else:
        # English updates
        content = content.replace('El Seif', content_data['company_name'])
        content = content.replace('ESEC', content_data['company_short'])
        
        # Update heading
        heading_pattern = r'(<h3>Connect with El Seif</h3>)'
        new_heading = f'<h3>Connect with {content_data["company_short"]}</h3>'
        content = re.sub(heading_pattern, new_heading, content)
        
        # Update description
        desc_pattern = r'(<p>\s*We would love to hear from you, so feel free to reach out to us\s*and let\'s start building a successful partnership together\.\s*</p>)'
        company_desc = content_data['paragraphs'][0] if content_data['paragraphs'] else 'We would love to hear from you.'
        new_desc = f'''<p>
                {company_desc} We would love to hear from you, so feel free to reach out to us
                and let's start building a successful partnership together.
              </p>'''
        content = re.sub(desc_pattern, new_desc, content, flags=re.DOTALL)
        
        # Add business hours section if not exists
        if content_data['business_hours']:
            hours_text = '<div class="contactUsNumbers mt-4">\n<h4>Business Hours</h4>\n'
            for hours in content_data['business_hours']:
                hours_text += f'<p>{hours}</p>\n'
            hours_text += '</div>'
            
            # Insert after phone number section
            phone_section_pattern = r'(</div>\s*</div>\s*<div class="w-100">)'
            content = re.sub(phone_section_pattern, rf'{hours_text}\1', content, count=1)
    
    # Write back
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        print(f"✓ Updated {file_path}")
        return True
    except Exception as e:
        print(f"Error writing {file_path}: {e}")
        return False

def main():
    """Main function."""
    scraped_data = load_scraped_data()
    content_data = get_contact_content(scraped_data)
    
    print(f"Company: {content_data['company_name']}")
    print(f"Business Hours: {content_data['business_hours']}")
    
    # Update English page
    update_contact_page('contactUs.html', content_data, is_arabic=False)
    
    # Update Arabic page
    update_contact_page('contactUs-ar.html', content_data, is_arabic=True)
    
    print("\nDone!")

if __name__ == '__main__':
    main()
