#!/usr/bin/env python

import hy

import sys
import os


if len(sys.argv) > 1:
    from hy.importer import import_file_to_module
    sys.argv.pop(0)
    import_file_to_module("__main__", sys.argv[0])
    sys.exit(0)  # right?


import readline
import code
import ast

from hy.lex.states import Idle, LexException
from hy.lex.machine import Machine
from hy.compiler import hy_compile
from hy.core import process

import hy.completer

from hy.macros import macro
from hy.models.expression import HyExpression
from hy.models.string import HyString
from hy.models.symbol import HySymbol


_machine = Machine(Idle, 1, 0)


class HyREPL(code.InteractiveConsole):
    def runsource(self, source, filename='<input>', symbol='single'):
        global _machine

        try:
            _machine.process(source + "\n")
        except LexException as e:
            _machine = Machine(Idle, 1, 0)
            self.showsyntaxerror(filename)
            return False

        if type(_machine.state) != Idle:
            _machine = Machine(Idle, 1, 0)
            return True

        tokens = process(_machine.nodes)

        _machine = Machine(Idle, 1, 0)
        try:
            _ast = hy_compile(tokens, root=ast.Interactive)
            code = compile(_ast, filename, symbol)
        except Exception:
            self.showtraceback()
            return False

        self.runcode(code)
        return False


sys.ps1 = "=> "
sys.ps2 = "... "

history = os.path.expanduser("~/.hy-history")
readline.parse_and_bind("set blink-matching-paren on")


@macro("koan")
def koan_macro(tree):
    return HyExpression([HySymbol('print'),
                         HyString("""
  Ummon asked the head monk, "What sutra are you lecturing on?"
  "The Nirvana Sutra."
  "The Nirvana Sutra has the Four Virtues, hasn't it?"
  "It has."
  Ummon asked, picking up a cup, "How many virtues has this?"
  "None at all, " said the monk.
  "But ancient people said it had, didn't they?" said Ummon.
  "Whatdo you think of what they said?"
  Ummon struck the cup and asked, "You understand?"
  "No," said the monk.
  "Then," said Ummon, "You'd better go on with your lectures on the sutra."
""")])


@macro("ideas")
def koan_macro(tree):
    return HyExpression([HySymbol('print'),
                         HyString("""

    => (import-from sh figlet)
    => (figlet "Hi, Hy!")
     _   _ _     _   _       _
    | | | (_)   | | | |_   _| |
    | |_| | |   | |_| | | | | |
    |  _  | |_  |  _  | |_| |_|
    |_| |_|_( ) |_| |_|\__, (_)
            |/         |___/


;;; string things
(.join ", " ["what" "the" "heck"])


;;; this one plays with command line bits
(import-from sh cat grep)
(-> (cat "/usr/share/dict/words") (grep "-E" "bro$"))


;;; filtering a list w/ a lambda
(filter (lambda [x] (= (% x 2) 0)) (range 0 10))


;;; swaggin' functional bits (Python rulez)
(max (map (lambda [x] (len x)) ["hi" "my" "name" "is" "paul"]))

""")])


try:
    readline.read_history_file(history)
except IOError:
    open(history, 'a').close()

readline.parse_and_bind("tab: complete")

hr = HyREPL()
hr.interact("{appname} {version}".format(
    appname=hy.__appname__,
    version=hy.__version__
))
readline.write_history_file(history)
