#!/usr/bin/env python3
"""
Translate all content: Arabic pages to Arabic, English pages to English
"""

from pathlib import Path
from bs4 import BeautifulSoup
import re

class ContentTranslator:
    def __init__(self):
        self.base_dir = Path(".")
        
        # English to Arabic translations for Arabic pages
        self.en_to_ar = {
            # Headings and titles
            "Building Great Projects Since 2008": "بناء مشاريع عظيمة منذ عام 2008",
            "Our Expertise": "خبرتنا",
            "Ongoing Projects": "المشاريع الجارية",
            "Our Clients": "عملاؤنا",
            "Latest News": "آخر الأخبار",
            "Contact Us": "اتصل بنا",
            "Who We Are": "من نحن",
            "Services": "خدماتنا",
            "Projects": "المشاريع",
            "Join Us": "انضم إلينا",
            "Home": "الرئيسية",
            
            # Content
            "We have consistently demonstrated our ability to execute complex projects efficiently, adhering to strict timelines and budgetary constraints while maintaining the highest quality standards.": 
            "لقد أظهرنا باستمرار قدرتنا على تنفيذ المشاريع المعقدة بكفاءة، مع الالتزام بجداول زمنية صارمة وقيود مالية مع الحفاظ على أعلى معايير الجودة.",
            
            "SPCC is a quality-driven construction company founded by highly qualified and well-experienced engineers in all disciplines to stand up as an example of good engineering practice.":
            "شركة المشاريع الذكية للإنشاءات هي شركة إنشاءات مدفوعة بالجودة تأسست من قبل مهندسين مؤهلين تأهيلاً عالياً وذوي خبرة واسعة في جميع التخصصات لتكون مثالاً على الممارسة الهندسية الجيدة.",
            
            "Need help? Contact us during office hours.":
            "تحتاج مساعدة؟ اتصل بنا خلال ساعات العمل.",
            
            "Construction Services": "خدمات الإنشاءات",
            "SMART PROJECTS CONSTRUCTION CO.": "شركة المشاريع الذكية للإنشاءات",
            
            # Service descriptions
            "We specialize in constructing robust and efficient industrial facilities tailored to meet the specific needs of various industries. Our expertise encompasses everything from manufacturing plants and warehouses to distribution centers and industrial complexes.":
            "نتخصص في بناء المرافق الصناعية القوية والفعالة المصممة خصيصاً لتلبية الاحتياجات المحددة لمختلف الصناعات. تشمل خبرتنا كل شيء من مصانع التصنيع والمستودعات إلى مراكز التوزيع والمجمعات الصناعية.",
            
            "Our commercial building projects focus on creating functional and aesthetically pleasing spaces that drive business success. We deliver a wide range of commercial structures, including office buildings, retail centers, shopping malls, and mixed-use developments.":
            "تركز مشاريع المباني التجارية لدينا على إنشاء مساحات وظيفية وجذابة من الناحية الجمالية تحقق نجاح الأعمال. نقدم مجموعة واسعة من الهياكل التجارية، بما في ذلك المباني المكتبية ومراكز البيع بالتجزئة ومراكز التسوق والتطويرات متعددة الاستخدامات.",
            
            # Other common phrases
            "Explore our Latest News, Industry Insights, and Noteworthy Achievements":
            "استكشف آخر أخبارنا ورؤى الصناعة والإنجازات البارزة",
            
            "Explore all project": "استكشف جميع المشاريع",
            "View project": "عرض المشروع",
            "Read more": "اقرأ المزيد",
        }
        
        # Arabic to English translations for English pages
        self.ar_to_en = {
            "الرئيسية": "Home",
            "من نحن": "Who We Are",
            "خدماتنا": "Services",
            "المشاريع": "Projects",
            "آخر الأخبار": "Latest News",
            "انضم إلينا": "Join Us",
            "اتصل بنا": "Contact Us",
            "عن السيف": "About El-Seif",
            "الشهادات": "Certificates",
            "العملاء": "Clients",
            "البنية التحتية": "Infrastructure",
            "المباني": "Buildings",
            "المقاولات العامة": "General Contracting",
            "التصميم والبناء": "Design and Build",
            "إدارة المشاريع": "Project Management",
        }
        
    def translate_arabic_page(self, html_file):
        """Translate English content in Arabic pages to Arabic"""
        html_path = self.base_dir / html_file
        if not html_path.exists():
            return False
        
        print(f"Translating Arabic page: {html_file}...")
        
        try:
            with open(html_path, 'r', encoding='utf-8', errors='ignore') as f:
                html_content = f.read()
        except Exception as e:
            print(f"Error reading {html_file}: {e}")
            return False
        
        soup = BeautifulSoup(html_content, 'html.parser')
        changed = False
        
        # Translate headings
        for tag in ['h1', 'h2', 'h3', 'h4', 'h5']:
            headings = soup.find_all(tag)
            for heading in headings:
                text = heading.get_text(strip=True)
                if text in self.en_to_ar:
                    heading.string = self.en_to_ar[text]
                    changed = True
        
        # Translate paragraphs
        paragraphs = soup.find_all('p')
        for p in paragraphs:
            text = p.get_text(strip=True)
            if text in self.en_to_ar:
                p.clear()
                p.string = self.en_to_ar[text]
                changed = True
            else:
                # Check for partial matches
                for en_text, ar_text in self.en_to_ar.items():
                    if en_text in text and len(en_text) > 20:
                        # Replace the English portion
                        new_text = text.replace(en_text, ar_text)
                        if new_text != text:
                            p.clear()
                            p.string = new_text
                            changed = True
                            break
        
        # Translate links (but keep hrefs)
        links = soup.find_all('a')
        for link in links:
            text = link.get_text(strip=True)
            if text in self.en_to_ar:
                link.string = self.en_to_ar[text]
                changed = True
        
        # Translate buttons
        buttons = soup.find_all('button')
        for btn in buttons:
            # Check span inside button
            span = btn.find('span')
            if span:
                text = span.get_text(strip=True)
                if text in self.en_to_ar:
                    span.string = self.en_to_ar[text]
                    changed = True
            
            # Check p inside button
            p_tag = btn.find('p')
            if p_tag:
                text = p_tag.get_text(strip=True)
                if text in self.en_to_ar:
                    p_tag.string = self.en_to_ar[text]
                    changed = True
        
        if changed:
            try:
                with open(html_path, 'w', encoding='utf-8') as f:
                    f.write(str(soup))
                print(f"✓ Translated {html_file}")
                return True
            except Exception as e:
                print(f"Error writing {html_file}: {e}")
                return False
        
        return False
    
    def translate_english_page(self, html_file):
        """Translate Arabic content in English pages to English"""
        html_path = self.base_dir / html_file
        if not html_path.exists():
            return False
        
        print(f"Translating English page: {html_file}...")
        
        try:
            with open(html_path, 'r', encoding='utf-8', errors='ignore') as f:
                html_content = f.read()
        except Exception as e:
            print(f"Error reading {html_file}: {e}")
            return False
        
        soup = BeautifulSoup(html_content, 'html.parser')
        changed = False
        
        # Check if page contains Arabic text
        arabic_pattern = re.compile(r'[\u0600-\u06FF]+')
        
        # Translate headings
        for tag in ['h1', 'h2', 'h3', 'h4', 'h5']:
            headings = soup.find_all(tag)
            for heading in headings:
                text = heading.get_text(strip=True)
                if arabic_pattern.search(text):
                    # Check if it's a known Arabic phrase
                    if text in self.ar_to_en:
                        heading.string = self.ar_to_en[text]
                        changed = True
        
        # Translate links
        links = soup.find_all('a')
        for link in links:
            text = link.get_text(strip=True)
            if arabic_pattern.search(text):
                if text in self.ar_to_en:
                    link.string = self.ar_to_en[text]
                    changed = True
        
        # Translate paragraphs (be careful not to translate Arabic content that should stay)
        paragraphs = soup.find_all('p')
        for p in paragraphs:
            text = p.get_text(strip=True)
            # Only translate if it's a known Arabic phrase
            if text in self.ar_to_en:
                p.clear()
                p.string = self.ar_to_en[text]
                changed = True
        
        if changed:
            try:
                with open(html_path, 'w', encoding='utf-8') as f:
                    f.write(str(soup))
                print(f"✓ Translated {html_file}")
                return True
            except Exception as e:
                print(f"Error writing {html_file}: {e}")
                return False
        
        return False
    
    def translate_all(self):
        """Translate all pages"""
        arabic_pages = [
            'home-ar.html',
            'about-ar.html',
            'ourService-ar.html',
            'ourServicedetail-ar.html',
            'project-ar.html',
            'projectDetail-ar.html',
            'Latest news-ar.html',
            'lastNewsDetails-ar.html',
            'join-ar.html',
            'contactUs-ar.html',
            'search-ar.html',
            'PrivacyPolicy-ar.html',
        ]
        
        english_pages = [
            'home.html',
            'about.html',
            'ourService.html',
            'ourServicedetail.html',
            'project.html',
            'projectDetail.html',
            'Latestnews.html',
            'lastNewsDetails.html',
            'join.html',
            'contactUs.html',
            'search.html',
            'PrivacyPolicy.html',
        ]
        
        ar_count = 0
        en_count = 0
        
        print("Translating Arabic pages...")
        for page in arabic_pages:
            if self.translate_arabic_page(page):
                ar_count += 1
        
        print("\nTranslating English pages...")
        for page in english_pages:
            if self.translate_english_page(page):
                en_count += 1
        
        print(f"\n{'='*60}")
        print(f"Translated {ar_count} Arabic pages")
        print(f"Translated {en_count} English pages")
        print(f"{'='*60}")

if __name__ == "__main__":
    translator = ContentTranslator()
    translator.translate_all()
