#!/usr/bin/env python

import os, sys

from sage.misc.preparser import preparse

SAGE_ROOT=os.environ["SAGE_ROOT"]
os.environ["LD_LIBRARY_PATH"] = SAGE_ROOT + "/local/lib"
os.environ["PYTHONPATH"]=SAGE_ROOT + "/local/lib/python/site-packages"
PYTHON=SAGE_ROOT + "/local/bin/python"
DOCTEST="""
    s = doctest.testmod(sys.modules[__name__], optionflags=doctest.NORMALIZE_WHITESPACE)
    sys.exit(s[0])        
"""
TEST_CODE= """
if __name__ ==  '__main__':
    import doctest, sys
""" + DOCTEST

def doc_preparse(s):
    """
    Run the preparser on the documentation string s.
    This *only* preparses the input lines, i.e., those
    that begin with "sage:".or with "...:"
    """
    # Deal with code whose output should be ignored. 
    s = s.replace("sage.:", "\nsage.:")  
    t = []
    for L in s.split('\n'):
        begin = L.lstrip()[:5]
        if begin == 'sage:':
            t.append(preparse(L))
        elif begin == '...: ':
            t.append(preparse(L, reset=False))
        else:
            t.append(L)
    return '\n'.join(t)

def extract_doc(file_name, module):
    a = os.path.abspath(file_name)
    i = a.rfind("sage/")
    module_name = a[i:].replace("/",".")
    j = module_name.rfind(".")
    module_name = module_name[:j]
    F = open(file_name).read()
    n = 0
    i = 0
    s =  "from sage.all import *\n"
    while True:
        i = F.find('"""')
        if i == -1: break
        j = i+3 + F[i+3:].find('"""')
        s += "def foo%s():"%n
        n += 1
        s += "\tr"+doc_preparse(F[i:j+3]) + "\n\n"
        F = F[j+3:]

    s += TEST_CODE
    # Allow for "sage:" instead of the traditional Python ">>>".
    s = s.replace("sage:",">>>")
    return s


def test_file(file):
    if os.path.exists(file):
        name = os.path.basename(file)
        name = name[:name.find(".")]
        s = extract_doc(file, name)
        f = ".doctest/%s.py"%name
        #f = "__test_%s.py"%name
        if not os.path.exists(".doctest"):
            os.makedirs(".doctest")
        open(f,"w").write(s)
        n = os.system("%s %s"%(PYTHON, f))
        sys.exit(bool(n))
    else:
        print "Error running %s, since file %s does not exist."%(
            sys.argv[0], sys.argv[1])
        sys.exit(1)
    
                
if __name__ ==  '__main__':
    import os, sys
    if len(sys.argv) == 1:
        print "Usage: %s <filename.pyx>"%(sys.argv[0])
    else:
        file = sys.argv[1]
        test_file(file)
