#!/usr/bin/env python3
"""
Arivu (அறிவு) - Tamil Programming Language
Main entry point for running Arivu programs

Usage:
    arivu <filename.rj>
    arivu -c "<code>"
    arivu  (for REPL)
"""

import sys
import argparse
from pathlib import Path
from .lexer import Lexer
from .parser import Parser
from .interpreter import Interpreter


def run_file(filename: str):
    """Run an Arivu source file"""
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            source = f.read()
        
        run_code(source, filename)
    
    except FileNotFoundError:
        print(f"Error: File '{filename}' not found")
        sys.exit(1)
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)


def run_code(source: str, filename: str = "<string>"):
    """Run rajini++ source code"""
    try:
        # Lexical analysis
        lexer = Lexer(source)
        tokens = lexer.tokenize()
        
        # Syntax analysis
        parser = Parser(tokens)
        ast = parser.parse()
        
        # Interpretation
        interpreter = Interpreter()
        interpreter.run(ast)
    
    except SyntaxError as e:
        print(f"Syntax Error in {filename}: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"Runtime Error in {filename}: {e}")
        sys.exit(1)


def repl():
    """Interactive REPL (Read-Eval-Print-Loop)"""
    print("╔════════════════════════════════════════╗")
    print("║   rajini++ Interactive Shell          ║")
    print("║   'En vazhi, thani vazhi!'            ║")
    print("║   Type 'exit' to quit                 ║")
    print("╚════════════════════════════════════════╝\n")
    
    interpreter = Interpreter()
    
    while True:
        try:
            # Read input
            line = input("rajini++ > ")
            
            # Check for exit
            if line.strip().lower() in ('exit', 'quit'):
                print("Vanakkam! (Goodbye!)")
                break
            
            # Skip empty lines
            if not line.strip():
                continue
            
            # Ensure statement ends with semicolon if needed
            line = line.strip()
            if not line.endswith(';') and not line.endswith('}'):
                line += ';'
            
            # Lexical analysis
            lexer = Lexer(line)
            tokens = lexer.tokenize()
            
            # Syntax analysis
            parser = Parser(tokens)
            ast = parser.parse()
            
            # Interpretation
            result = interpreter.interpret(ast)
            
            # Print result if it's an expression
            if result is not None and not line.strip().startswith(('PONGAL', 'STYLE', 'THALAIVA', 'PUNCH')):
                print(interpreter.value_to_string(result))
        
        except KeyboardInterrupt:
            print("\nVanakkam! (Goodbye!)")
            break
        except EOFError:
            print("\nVanakkam! (Goodbye!)")
            break
        except Exception as e:
            print(f"Error: {e}")


def main():
    """Main entry point"""
    parser = argparse.ArgumentParser(
        description='rajini++ - A programming language with style!',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog='''
Examples:
  python rajini.py program.rj          Run a rajini++ program
  python rajini.py -c "PUNCH(42);"     Execute code directly
  python rajini.py                     Start interactive REPL

"En vazhi, thani vazhi!" - My way is a unique way!
        '''
    )
    
    parser.add_argument(
        'file',
        nargs='?',
        help='rajini++ source file to execute (.rj extension)'
    )
    
    parser.add_argument(
        '-c', '--code',
        help='Execute rajini++ code directly'
    )
    
    parser.add_argument(
        '-v', '--version',
        action='version',
        version='rajini++ 1.0.0 - "Thalaiva Edition"'
    )
    
    args = parser.parse_args()
    
    # Execute code directly
    if args.code:
        run_code(args.code)
    
    # Run file
    elif args.file:
        run_file(args.file)
    
    # Start REPL
    else:
        repl()


if __name__ == '__main__':
    main()
