#!/usr/bin/env python
#-*- coding: utf-8 -*-
"""Execute and analize Hebrew Python scripts """

from optparse import OptionParser
from code import InteractiveConsole
try:
    import readline
except ImportError:
    pass

import hpy, tokenize

class HebrewConsole(InteractiveConsole):
    
    def runsource(self, string, *args, **kw):
        try:
            # Terminal sends a byte string using some encoding.
            # TODO: detect real terminal encoding
            pystring = hpy.translateString(string.decode('utf8'),
                                           hpy.pythonString)
        except (tokenize.TokenError, hpy.htokenize.TokenError), e:
            # XXX dirty hack
            if e.args[0] == 'EOF in multi-line string':
                return True  # incomple input
            print string
            self.showsyntaxerror()
        except SystemExit:
            raise
        except:
            print 'INTERNAL HPYTHON ERROR:'
            self.showtraceback()
        else:
            # return value is important for incomplete commands
            return InteractiveConsole.runsource(self, pystring, *args, **kw)

# Parse options
parser = OptionParser(usage='usage: %prog [options] FILE',
                      version='%prog ' + hpy.__version__)

parser.add_option("-s", "--source",
                  action="store_true", dest="source",
                  help="show translated source")

parser.add_option("-t", "--tokens",
                  action="store_true", dest="tokens",
                  help="show tokens in source")

parser.add_option("-c", "--compile",
                  action="store_true", dest="compile",
                  help="compile hpy module to python module")

parser.set_defaults(source=False, tokens=False, compile=False)

options, args = parser.parse_args()

# Run

if len(args) > 1:
    parser.error("too many files, I'm confused")
elif len(args) == 1:
    path = args[0]
    if options.tokens:
        hpy.printTokens(path)    
    if options.source:
        print hpy.source(path)

    if options.compile:
        hpy.compileModule(path)
    else:
        hpy.execute(path)
else:    
    HebrewConsole().interact()
