#!/usr/bin/env python3
"""
Translate navigation bar and footer elements in Arabic pages
"""

from pathlib import Path
from bs4 import BeautifulSoup

class ArabicTranslator:
    def __init__(self):
        self.base_dir = Path(".")
        
        # Translation mapping
        self.translations = {
            # Navigation items
            "Home": "الرئيسية",
            "Who We Are": "من نحن",
            "About Us": "من نحن",
            "Services": "خدماتنا",
            "Projects": "المشاريع",
            "Latest News": "آخر الأخبار",
            "Join Us": "انضم إلينا",
            "Contact Us": "اتصل بنا",
            "Search": "بحث",
            "Privacy Policy": "سياسة الخصوصية",
            
            # Submenu items
            "About El-Seif": "عن السيف",
            "Certificates": "الشهادات",
            "Clients": "العملاء",
            "Infrastructure": "البنية التحتية",
            "Buildings": "المباني",
            "General Contracting": "المقاولات العامة",
            "Design and Build": "التصميم والبناء",
            "Project Management": "إدارة المشاريع",
            
            # Footer
            "Quick Links": "روابط سريعة",
            "Newsletter": "النشرة الإخبارية",
            "Subscribe": "اشترك",
            "All Rights Reserved": "جميع الحقوق محفوظة",
            "Designed And Developed by": "صمم وطور بواسطة",
        }
        
    def translate_navigation(self, soup):
        """Translate navigation menu items"""
        # Find all navigation menus
        navs = soup.find_all('nav') + soup.find_all('div', class_='mobile-sidebar-nav')
        
        for nav in navs:
            links = nav.find_all('a', href=True)
            for link in links:
                text = link.get_text(strip=True)
                href = link.get('href', '')
                
                # Translate main menu items
                if text in self.translations:
                    link.string = self.translations[text]
                
                # Translate submenu items based on href patterns
                if '#certificates' in href:
                    link.string = "الشهادات"
                elif '#clients' in href:
                    link.string = "العملاء"
                elif 'ourServicedetail' in href:
                    # Check which service based on context or use generic
                    if text == "Services" or text == "خدماتنا":
                        # Try to determine service type from parent context
                        parent_li = link.find_parent('li')
                        if parent_li:
                            # Check if there are multiple service links
                            service_links = parent_li.find_all('a', href=lambda x: x and 'ourServicedetail' in x)
                            service_index = service_links.index(link) if link in service_links else -1
                            service_names = ["البنية التحتية", "المباني", "المقاولات العامة", "التصميم والبناء", "إدارة المشاريع"]
                            if 0 <= service_index < len(service_names):
                                link.string = service_names[service_index]
        
        return soup
    
    def translate_footer(self, soup):
        """Translate footer elements"""
        footer = soup.find('footer')
        if not footer:
            return soup
        
        # Translate footer headings
        headings = footer.find_all(['h3', 'h4', 'h5'])
        for heading in headings:
            text = heading.get_text(strip=True)
            if text in self.translations:
                heading.string = self.translations[text]
        
        # Translate footer links
        footer_links = footer.find_all('a')
        for link in footer_links:
            text = link.get_text(strip=True)
            if text in self.translations:
                link.string = self.translations[text]
        
        # Translate footer text content
        paragraphs = footer.find_all('p')
        for p in paragraphs:
            text = p.get_text(strip=True)
            # Check for common footer phrases
            if "All Rights Reserved" in text:
                p.string = text.replace("All Rights Reserved", "جميع الحقوق محفوظة")
            if "Designed And Developed by" in text:
                p.string = text.replace("Designed And Developed by", "صمم وطور بواسطة")
            if "Newsletter" in text:
                p.string = text.replace("Newsletter", "النشرة الإخبارية")
        
        # Translate form placeholders and buttons
        inputs = footer.find_all('input')
        for inp in inputs:
            placeholder = inp.get('placeholder', '')
            if placeholder and placeholder in self.translations:
                inp['placeholder'] = self.translations[placeholder]
            elif placeholder == "info@example.com":
                inp['placeholder'] = "البريد الإلكتروني"
        
        buttons = footer.find_all('button')
        for btn in buttons:
            btn_text = btn.get_text(strip=True)
            if btn_text in self.translations:
                # Find span or text node and replace
                span = btn.find('span')
                if span:
                    span.string = self.translations[btn_text]
                else:
                    btn.string = self.translations[btn_text]
        
        return soup
    
    def translate_page(self, html_file):
        """Translate navigation and footer in a single HTML file"""
        html_path = self.base_dir / html_file
        if not html_path.exists():
            print(f"File not found: {html_file}")
            return False
        
        # Only process Arabic pages
        if '-ar.html' not in html_file and not html_file.startswith('Latest news-ar'):
            return False
        
        print(f"Translating {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')
        
        # Translate navigation
        soup = self.translate_navigation(soup)
        
        # Translate footer
        soup = self.translate_footer(soup)
        
        # Save
        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
    
    def translate_all(self):
        """Translate all Arabic 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',
        ]
        
        translated_count = 0
        for page in arabic_pages:
            if self.translate_page(page):
                translated_count += 1
        
        print(f"\n{'='*60}")
        print(f"Translated {translated_count} Arabic pages")
        print(f"{'='*60}")

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