import sys, os
import re

class Templite(object):
    
    autowrite = re.compile('(^[\'\"])|(^[a-zA-Z0-9_\[\]\'\".]+$)')
    delimiters = ('{{', '}}')
    cache = {}

    def __init__(self, filename=None, text=None, delimiters=None, caching=False):
        """Loads a template from string or file."""
        key = hash(text)
        # set attributes
        self.caching = caching
        if filename:
            self.filename = os.path.abspath(filename)
            mtime = os.path.getmtime(filename)
            self.file = key = filename
            with open(self.filename, "r", encoding="utf8") as f:
                text = f.read()
        elif text:
            self.filename = "<string>"
            key = hash(text)
        else:
            raise ValueError('no template found')
        if delimiters:
            start, end = delimiters
            if len(start) != 2 or len(end) != 2:
                raise ValueError('each delimiter must be two characters long')
            self.delimiters = delimiters
        # check cache
        cache = self.cache
        if caching and key in cache and cache[key][0] == mtime:
            self._code = cache[key][1]
            return
        self._code = self._compile(text)
        if caching:
            cache[key] = (mtime, self._code)
    
    def _compile(self, source):
        offset = 0
        tokens = ['# -*- coding: utf8 -*-']
        start, end = self.delimiters
        #source = re.sub(r"\[/([a-zA-Z0-9_.-]+)\]", r"{{popstyle('\1')}}", source)
        source = re.sub(r"^({}.*{}\s*)$\n".format(re.escape(start), re.escape(end)), r"\1", source, flags=re.M)
        source = re.sub(r"^(\s*{})$\n".format(re.escape(end)), r"\1", source, flags=re.M)
        regex = re.compile('{}(.*?){}'.format(re.escape(start), re.escape(end)), re.DOTALL)
        for i, part in enumerate(regex.split(source)):
            #part = part.replace('\\'.join(start), start)
            #part = part.replace('\\'.join(end), end)
            if i % 2 == 0:
                part = part.replace('\\', '\\\\').replace('"', '\\"')
                part = '{}write("""{}""")'.format('\t' * offset, part)
            else:
                part = part.rstrip()
                if not part: 
                    continue
                part_stripped = part.lstrip()
                if part_stripped.startswith(':'):
                    if not offset:
                        raise SyntaxError('no block statement to terminate: {{%s}}' % part)
                    offset -= 1
                    part = part_stripped[1:]
                    if not part.endswith(':'): 
                        continue
                elif self.autowrite.match(part_stripped):
                    part = 'write({})'.format(part_stripped)
                lines = part.splitlines()
                margin = min(len(l) - len(l.lstrip()) for l in lines if l.strip())
                part = '\n'.join('\t' * offset + l[margin:] for l in lines)
                if part.endswith(':'):
                    offset += 1
            tokens.append(part)
        if offset:
            raise SyntaxError('{:d} block statement(s) not terminated'.format(offset))
        return compile('\n'.join(tokens), self.filename, 'exec')

    def render(self, **namespace):
        """Renders the template according to the given namespace."""
        stack = []
        namespace['__file__'] = ""
        # add write method
        def write(*args):
            for value in args:
                stack.append(str(value))
        namespace['write'] = write
        # execute template code
        exec(self._code, namespace)
        return "".join(stack)


def run(path, namespace={}):
    if not path or not os.path.exists(path):
        return "no template found"
    return Templite(filename=path).render(**namespace)
