#!/usr/bin/env python3
"""
Fix navigation links to properly route to Arabic or English pages
"""

from pathlib import Path
from bs4 import BeautifulSoup

class NavigationFixer:
    def __init__(self):
        self.base_dir = Path(".")
        
        # Page mapping: English -> Arabic
        self.page_mapping = {
            "home.html": "home-ar.html",
            "about.html": "about-ar.html",
            "ourService.html": "ourService-ar.html",
            "ourServicedetail.html": "ourServicedetail-ar.html",
            "project.html": "project-ar.html",
            "projectDetail.html": "projectDetail-ar.html",
            "Latestnews.html": "Latest news-ar.html",
            "lastNewsDetails.html": "lastNewsDetails-ar.html",
            "join.html": "join-ar.html",
            "contactUs.html": "contactUs-ar.html",
            "search.html": "search-ar.html",
            "PrivacyPolicy.html": "PrivacyPolicy-ar.html",
        }
        
        # Reverse mapping: Arabic -> English
        self.reverse_mapping = {v: k for k, v in self.page_mapping.items()}
        
    def fix_navigation_links(self, html_file, is_arabic=False):
        """Fix navigation links 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
        
        print(f"Fixing navigation in {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')
        
        # Find all navigation menus
        navs = soup.find_all('nav') + soup.find_all('div', class_='mobile-sidebar-nav')
        
        for nav in navs:
            # Find all links in navigation
            links = nav.find_all('a', href=True)
            
            for link in links:
                href = link.get('href', '')
                
                # Skip external links, anchors, and language switcher
                if (href.startswith('http') or 
                    href.startswith('#') or 
                    href.startswith('mailto:') or 
                    href.startswith('tel:') or
                    'lang' in link.get('class', []) or
                    'languageSwitch' in str(link)):
                    continue
                
                # Get the target page name
                target_page = href.split('/')[-1] if '/' in href else href
                
                if is_arabic:
                    # On Arabic page - convert English links to Arabic
                    if target_page in self.page_mapping:
                        link['href'] = self.page_mapping[target_page]
                    # If already Arabic, keep it
                    elif '-ar.html' in target_page or 'Latest news-ar.html' in target_page:
                        continue
                    # If it's a base name without extension, try to find Arabic version
                    elif target_page.endswith('.html') and target_page not in self.reverse_mapping:
                        # Check if there's an Arabic version
                        ar_version = target_page.replace('.html', '-ar.html')
                        if (self.base_dir / ar_version).exists():
                            link['href'] = ar_version
                else:
                    # On English page - convert Arabic links to English
                    if target_page in self.reverse_mapping:
                        link['href'] = self.reverse_mapping[target_page]
                    # If it's Arabic version, convert to English
                    elif '-ar.html' in target_page:
                        en_version = target_page.replace('-ar.html', '.html')
                        if en_version in self.page_mapping.values() or (self.base_dir / en_version).exists():
                            link['href'] = en_version.replace('-ar.html', '.html')
                    # Keep English links as is
                    elif target_page.endswith('.html') and '-ar' not in target_page:
                        continue
        
        # Fix language switcher links (navigation-Ar class or lang-switcher)
        lang_switchers = soup.find_all('a', href=True)
        for switcher in lang_switchers:
            href = switcher.get('href', '')
            classes = switcher.get('class', [])
            parent_classes = switcher.parent.get('class', []) if switcher.parent else []
            
            # Check if this is a language switcher
            is_lang_switcher = (
                'navigation-Ar' in str(classes) or 
                'navigation-Ar' in str(parent_classes) or
                'lang-switcher' in str(classes) or
                switcher.parent and switcher.parent.get('id') == 'navigation-Ar'
            )
            
            if is_lang_switcher:
                if is_arabic:
                    # Arabic page -> switch to English
                    current_page = html_file
                    if current_page in self.reverse_mapping:
                        switcher['href'] = self.reverse_mapping[current_page]
                    elif current_page == 'Latest news-ar.html':
                        switcher['href'] = 'Latestnews.html'
                    elif '-ar.html' in current_page:
                        switcher['href'] = current_page.replace('-ar.html', '.html')
                    else:
                        switcher['href'] = current_page.replace('.html', '.html').replace('Latest news-ar.html', 'Latestnews.html')
                else:
                    # English page -> switch to Arabic
                    current_page = html_file
                    if current_page in self.page_mapping:
                        switcher['href'] = self.page_mapping[current_page]
                    elif current_page == 'Latestnews.html':
                        switcher['href'] = 'Latest news-ar.html'
                    else:
                        switcher['href'] = current_page.replace('.html', '-ar.html')
        
        # Fix any double -ar-ar issues
        all_links = soup.find_all('a', href=True)
        for link in all_links:
            href = link.get('href', '')
            if '-ar-ar.html' in href:
                link['href'] = href.replace('-ar-ar.html', '-ar.html')
            if href == 'home-ar-ar.html':
                link['href'] = 'home-ar.html' if is_arabic else 'home.html'
        
        # Save
        with open(html_path, 'w', encoding='utf-8') as f:
            f.write(str(soup))
        
        print(f"✓ Fixed {html_file}")
        return True
    
    def fix_all_pages(self):
        """Fix navigation in all HTML pages"""
        # Focus on main pages first
        main_pages = [
            'home.html', 'home-ar.html',
            'about.html', 'about-ar.html',
            'ourService.html', 'ourService-ar.html',
            'project.html', 'project-ar.html',
            'contactUs.html', 'contactUs-ar.html',
            'Latestnews.html', 'Latest news-ar.html',
            'join.html', 'join-ar.html',
            'search.html', 'search-ar.html',
            'PrivacyPolicy.html', 'PrivacyPolicy-ar.html',
        ]
        
        fixed_count = 0
        for page_name in main_pages:
            html_file = self.base_dir / page_name
            if html_file.exists():
                is_arabic = '-ar.html' in page_name or page_name.startswith('Latest news-ar')
                if self.fix_navigation_links(page_name, is_arabic):
                    fixed_count += 1
        
        print(f"\n{'='*60}")
        print(f"Fixed navigation in {fixed_count} files")
        print(f"{'='*60}")

if __name__ == "__main__":
    fixer = NavigationFixer()
    fixer.fix_all_pages()
