#! /usr/bin/env python3

import re
import os
import time
import codecs # This is important for reading files with Unicode characters.


# Create a variable for the path to the appendix critica.
path = '/Users/sjhuskey/Documents/Sam-Py/DLL-Scripts/basetext.txt'

# Open the file with utf-8 encoding.
source_file = codecs.open(path,'r','utf-8')

# Read the file.
source_text = source_file.read()

# Tell python what to search for (with thanks to https://stackoverflow.com/questions/13168761/python-use-regex-sub-multiple-times-in-1-pass).

print('Gosh, that\'s a lot of unencoded text! We\'d better get started!')
time.sleep(5)

# Handle additive emendation, since it is indicated by < >, which would be swept up by other routines below.
print('Okay, we\'ll handle editorial additions first, since their angle brackets\n might cause trouble later.')
time.sleep(4)
search_addition = re.compile(r'<([a-zA-Z]*)>')
replace0 = search_addition.sub(r'<supplied reason="lost">\1</supplied>', source_text)

# Search for numbers at beginning of paragraphs, then wrap paragraph in <p n="[number]"> </p>/
print('Done. Next up: encoding the paragraphs.')
time.sleep(5)
search_paragraph = re.compile(r'\n([0-9]*)(.*)')
replace1 = search_paragraph.sub(r'<p n="\1">\2</p>',replace0)

# Remove empty paragraphs.
print('Done. Now let\'s kill any empty paragraphs caused by line breaks in the original document.')
time.sleep(3)
search_empty_paragraph = re.compile(r'<p n="">([\s]*)</p>')
replace2 = search_empty_paragraph.sub(r'', replace1)

# Search for (number) and reformat it as <seg n="number">(number).
print('Empty paragraphs have been killed. Handling segments now.')
time.sleep(5)
search_segment = re.compile(r'\(([0-9]*)\)')
replace3 = search_segment.sub(r'<seg n="\1">',replace2)

# Add the closing </seg>.
search_add_close_seg = re.compile(r'(<seg|</p>)')
replace4 = search_add_close_seg.sub(r'</seg>\1',replace3)

# Remove the orphan </seg> at the beginning of the paragraph.
search_remove_orphan_seg = re.compile(r'\s</seg>(<seg n="1">)\s')
replace5 = search_remove_orphan_seg.sub(r'\1',replace4)

# Remove space before and after <seg> markers.
search_remove_seg_space = re.compile(r'\s</seg><seg n="([0-9]*)">\s')
replace6 = search_remove_seg_space.sub(r'</seg> <seg n="\1">',replace5)

# Handle crux.
print('Now handling special symbols. First up: †crux†.')
time.sleep(3)
search_crux = re.compile(r'†([a-zA-Z]*)†')
replace7 = search_crux.sub(r'<sic>\1</sic>',replace6)

# Handle lacuna.
print('... now *** lacunae')
time.sleep(3)
search_lacuna = re.compile(r'\*\*\*')
replace8 = search_lacuna.sub(r'<gap reason="lost"/>', replace7)

# Handle editorial deletion.
print('... now {editorial deletions}.')
time.sleep(3)
search_deletion = re.compile(r'\[([a-zA-Z]*)\]')
replace9 = search_deletion.sub(r'<surplus>\1</surplus>',replace8)

# Go back and fix the first paragraph, for some reason.
search_first_p = re.compile(r'1<seg(.*)<p n="2"')
replace10 = search_first_p.sub(r'<p n="1"><seg\1</seg></p>\n\n<p n="2"',replace9)

# Write the TEI header.
print('Adding the TEI header and footer, just to show off.')
time.sleep(2)

header = '''<?xml-model
href="https://digitallatin.github.io/guidelines/critical-editions.rng" type="application/xml" 
  schematypens="http://relaxng.org/ns/structure/1.0"?>
<?xml-model
href="https://digitallatin.github.io/guidelines/critical-editions.rng" type="application/xml"
	schematypens="http://purl.oclc.org/dsdl/schematron"?>
<TEI xmlns="http://www.tei-c.org/ns/1.0">
   <teiHeader>
      <fileDesc>
         <titleStmt>
            <title>Title</title>
         </titleStmt>
         <publicationStmt>
            <p>Publication Information</p>
         </publicationStmt>
         <sourceDesc>
            <p>Information about the source</p>
         </sourceDesc>
      </fileDesc>
   </teiHeader>
   <text>
      <body>
      <div type="edition" xml:id="edition-text">
            <div type="textpart" n="1" xml:id="part1">'''

# Write the footer
footer = '''</div></div></body>
      <back>
         <!--
The content of the back matter will be determined in consultation between
        the editor and the staff of the DLL. Because LDLT editions are encoded, the
        matter traditionally found in the back of a printed critical edition may be
        generated by applications instead of having to be entered manually.
        Nevertheless, there is space here for notes, indices, and other kinds of
        information.
-->
      </back>
   </text>
</TEI>'''


# Combine all of the ingredients into one.
TEI = header + replace10 + footer

# Tell the script where to write the new file.
print('Making a new file ...')
time.sleep(2)
new_path = '/Users/sjhuskey/Documents/Sam-Py/DLL-Scripts/basetext.xml' 

# Open the new file.
new_source = codecs.open(new_path,'w','utf-8')

# Write the contents of altered source_text to new_source.
print('Writing the XML to the new file ...')
time.sleep(2)
new_source.write(str(TEI))

# Close the old and new source files.
print('Cleaning up our workspace...')
time.sleep(2)
source_file.close()
new_source.close()


print('Wow! That saved a lot of time!')
time.sleep(3)

print('Valid XML coming your way!')
time.sleep(2)

os.system("open "+ new_path)
