# translator.py
from .translator_enhanced import KEYWORDS, MODULES, TYPES
import re
import ast

def translate(text):
    """
    Translate Arabic Python code to English Python code
    """
    # First, replace keywords
    for ar, en in KEYWORDS.items():
        # Use word boundaries to avoid partial replacements
        pattern = r'\b' + re.escape(ar) + r'\b'
        text = re.sub(pattern, en, text)
    
    # Replace module imports
    for ar, en in MODULES.items():
        pattern = r'\b' + re.escape(ar) + r'\b'
        text = re.sub(pattern, en, text)
    
    # Replace type annotations
    for ar, en in TYPES.items():
        pattern = r'\b' + re.escape(ar) + r'\b'
        text = re.sub(pattern, en, text)
    
    # Handle Arabic string literals
    text = handle_arabic_strings(text)
    
    return text

def handle_arabic_strings(text):
    """
    Preserve Arabic text inside string literals
    """
    lines = text.split('\n')
    result = []
    
    for line in lines:
        # Skip lines that are inside strings
        in_string = False
        string_char = None
        new_line = []
        i = 0
        
        while i < len(line):
            char = line[i]
            
            # Handle escape sequences
            if char == '\\' and i + 1 < len(line):
                new_line.append(char + line[i+1])
                i += 2
                continue
            
            # Toggle string state
            if char in ('"', "'") and (i == 0 or line[i-1] != '\\'):
                if not in_string:
                    in_string = True
                    string_char = char
                elif string_char == char:
                    in_string = False
                    string_char = None
            
            new_line.append(char)
            i += 1
        
        result.append(''.join(new_line))
    
    return '\n'.join(result)

def translate_ast(code):
    """
    Translate using AST for more accurate parsing
    """
    try:
        tree = ast.parse(code)
        translated_code = ast.unparse(tree) if hasattr(ast, 'unparse') else code
        return translated_code
    except:
        # Fallback to regex-based translation
        return translate(code)

def run(path, execute=True):
    """
    Read, translate and optionally execute Python code
    """
    with open(path, "r", encoding="utf-8") as f:
        code = f.read()
    
    py_code = translate(code)
    
    if execute:
        # Create a safe execution environment
        safe_globals = {
            '__builtins__': __builtins__,
            '__name__': '__main__',
        }
        
        try:
            exec(py_code, safe_globals)
        except Exception as e:
            print(f"خطأ في التنفيذ: {e}")
            print(f"الكود المترجم:\n{py_code}")
    else:
        return py_code

def compile_to_py(source_path, output_path=None):
    """
    Compile Arabic Python to standard Python file
    """
    with open(source_path, "r", encoding="utf-8") as f:
        code = f.read()
    
    py_code = translate(code)
    
    if output_path:
        with open(output_path, "w", encoding="utf-8") as f:
            f.write(py_code)
        print(f"تم تجميع الكود إلى: {output_path}")
    
    return py_code