import sys
import os
import traceback
from .compiler import TamilCompiler

def read_file(filepath):
    if not os.path.exists(filepath):
        print(f"❌ பிழை (Error): File '{filepath}' not found.")
        sys.exit(1)
    with open(filepath, 'r', encoding='utf-8') as f:
        return f.read()

def run():
    """Handles the 'tamilpp' command to run code directly."""
    if len(sys.argv) < 2:
        print("Usage: tamilpp <filename.tpp>")
        sys.exit(1)
        
    filepath = sys.argv[1]
    code = read_file(filepath)
    
    compiler = TamilCompiler()
    python_code = compiler.translate(code)
    
    # Execute the code in a clean __main__ namespace
    exec_globals = {'__name__': '__main__', '__file__': filepath}
    try:
        exec(python_code, exec_globals)
    except Exception as e:
        print("\n❌ இயற்பிழை (Runtime Error):")
        traceback.print_exc()

def compile_file():
    """Handles the 'tamilppc' command to compile to a .py file."""
    if len(sys.argv) < 2:
        print("Usage: tamilppc <filename.tpp>")
        sys.exit(1)
        
    filepath = sys.argv[1]
    code = read_file(filepath)
    
    compiler = TamilCompiler()
    python_code = compiler.translate(code)
    
    # Create the output filename (e.g., example.tpp -> example.py)
    out_filepath = filepath.rsplit('.', 1)[0] + '.py'
    
    with open(out_filepath, 'w', encoding='utf-8') as f:
        f.write("# Compiled by TamilPP Compiler\n\n")
        f.write(python_code)
        
    print(f"✅ வெற்றி! Successfully compiled to: {out_filepath}")