#!/usr/bin/env python3
"""
Translate remaining English text in Arabic pages
"""

from pathlib import Path
from bs4 import BeautifulSoup

class RemainingTranslator:
    def __init__(self):
        self.base_dir = Path(".")
        
        self.translations = {
            "Our Projects": "مشاريعنا",
            "Projects": "المشاريع",
            "View project": "عرض المشروع",
            "Read more": "اقرأ المزيد",
            "Explore all project": "استكشف جميع المشاريع",
            "Explore": "استكشف",
        }
        
    def translate_page(self, html_file):
        """Translate English text in Arabic page"""
        html_path = self.base_dir / html_file
        if not html_path.exists():
            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: {e}")
            return False
        
        soup = BeautifulSoup(html_content, 'html.parser')
        changed = False
        
        # Translate all text elements
        for element in soup.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'span', 'a', 'button', 'strong']):
            # Skip language switcher
            if element.find_parent('li', id='navigation-Ar'):
                continue
            if 'lang-switcher' in str(element.get('class', [])) or 'en' in str(element.get('class', [])):
                continue
            
            text = element.get_text(strip=True)
            
            # Exact match
            if text in self.translations:
                element.clear()
                element.string = self.translations[text]
                changed = True
            else:
                # Check for partial matches
                for en_text, ar_text in self.translations.items():
                    if en_text in text and len(text) < 50:
                        new_text = text.replace(en_text, ar_text)
                        if new_text != text:
                            element.clear()
                            element.string = new_text
                            changed = True
                            break
        
        # Handle button spans
        buttons = soup.find_all('button')
        for btn in buttons:
            span = btn.find('span')
            if span:
                text = span.get_text(strip=True)
                if text in self.translations:
                    span.string = self.translations[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: {e}")
                return False
        
        return False
    
    def translate_all_arabic_pages(self):
        """Translate all Arabic pages"""
        arabic_pages = [
            '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',
            'ourServicedetail-ar.html',
        ]
        
        translated = 0
        for page in arabic_pages:
            if self.translate_page(page):
                translated += 1
        
        print(f"\nTranslated {translated} pages")

if __name__ == "__main__":
    translator = RemainingTranslator()
    translator.translate_all_arabic_pages()
