# Extracts code from latex documents.
# Python cose is in the {python} and {pythoncont} environments
# Python 3 code. Full documentation at http://artint.info/code/python/aipython.pdf

# Development cycle (in aipython directory):
# cd ..;python extract_code.py; cd aipython

# Artificial Intelligence: Foundations of Computational Agents 3e
# http://artint.info
# Copyright David L Poole and Alan K Mackworth 2023.
# This work is licensed under a Creative Commons
# Attribution-NonCommercial-ShareAlike 4.0 International License.
# See: http://creativecommons.org/licenses/by-nc-sa/4.0/deed.en_US.

import re

all_files = ['python.tex', 'agents.tex', 'search.tex', 'csp.tex', 'propositions.tex',
                 'planning.tex', 'learning.tex', 'learnDeep.tex', 'uncertainty.tex',
                 'learnUncertainty.tex', 'causality.tex', 'planUncertainty.tex',
                  'rl.tex',  'mas.tex', 
                 'relations.tex', 'knowledge.tex', 'relationalLearning.tex']
base_folder = 'aipython/'
solution_folder = "solutions/"

#### Edit these if you want mutiple versions that extract different chapters
base_folder_alt = 'aipython_322/'
base_folder_dev = 'aipython_dev/'
files_alt = ['python.tex', 'search.tex','csp.tex' #, 'propositions.tex'
                 ,'planning.tex', 'uncertainty.tex', 'planUncertainty.tex']
# Edit the following when you create development variants
files_dev = all_files + ['LLMs.tex']
af = ['python.tex', 'agents.tex', 'search.tex', 'csp.tex', 'propositions.tex',
                 'planning.tex', 'learning.tex', 'learnDeep.tex', 'uncertainty.tex',
                 'learnUncertainty.tex', 'causality.tex', 'planUncertainty.tex',
                  'rl.tex',  'mas.tex', 
                 'relations.tex', 'knowledge.tex', 'relationalLearning.tex']
##base_folder_alt = 'aifca_new/'
##files_alt = ['python.tex', 'search.tex','csp.tex', 'propositions.tex', 'planning.tex', 'uncertainty.tex', 'planUncertainty.tex']


#### Make sure the version in the header matched the one in aipython.tex
header = 'header.py'

def extract_code(files,base_folder, listfiles=False, mksols=False):
    output_files = {}    # name:file dictionary
    headerfile = open(header,'r')
    headertext = headerfile.readlines()
    headerfile.close()
    for file_name in files:
        #print('Opening file:',file_name)
        file = open(file_name,'r')
        output = None
        for line in file:
            #print(line,end="")
            if output:
                if line.startswith("\\end{python") or line.startswith("\\end{solutioncode"):
                    #print("found",line,end="")
                    output = None
                else:
                    output.write(line)
            elif line.startswith("\\begin{python}"):
                #print("found",line,end="")
                py,name,desc = re.findall('\\{[^\\}]*\\}',line)
                name = name[1:-1]
                if listfiles:
                    print(f"{name}.py")
                if name in output_files:
                    print("Warning overwriting file",name,"-",desc[1:-1])
                output = open(base_folder+name+'.py','w')
                output_files[name] = output
                output.write("# "+name+".py - "+desc[1:-1]+"\n")
                for headl in headertext:
                    output.write(headl)
            elif line.startswith("\\begin{pythoncont}"):
                #print("found",line,end="")
                py,name= re.findall('\\{[^\\}]*\\}',line)
                name = name[1:-1]
                output = output_files[name]
            elif mksols and line.startswith("\\begin{solutioncode}"):
                #print("found",line,end="")
                py,name,desc = re.findall('\\{[^\\}]*\\}',line)
                name = name[1:-1]
                if listfiles:
                    print(f"{name}.py")
                if name in output_files:
                    print("Warning overwriting file",name,"-",desc[1:-1])
                output = open(solution_folder+name+'.py','w')
                output_files[name] = output
                output.write("# "+name+".py - "+desc[1:-1]+"\n")
                for headl in headertext:
                    output.write(headl)
            elif mksols and line.startswith("\\begin{solutioncodecont}"):
                #print("found",line,end="")
                py,name= re.findall('\\{[^\\}]*\\}',line)
                name = name[1:-1]
                output = output_files[name]
        file.close()
    for f in output_files.values():
        f.close()
        
                                 
        
#extract_code(all_files,base_folder,listfiles=False)
#extract_code(files_alt,base_folder_alt)
extract_code(files_dev,base_folder_dev)
#quit()
