from typing import OrderedDict
import re


def process_file(filepath: str) -> OrderedDict[str, str]:
  """
  Open the file, and separate each div. If a div is broken up into different parts or across
  multiple folio pages, they are attached.
  Inputs:
    filepath: string representing the filepath of the file to be read in /ms-text/[version]
  Outputs:
    entries: a dictionary containing the text of each entry keyed by folio and div IDs.
  """

  entries = OrderedDict()
  # read file, extract text and folio ID
  with open(filepath, encoding="utf-8", errors="surrogateescape") as f:
    text = f.read()
    folio = filepath.split('/')[-1].split('_')[1][1:] # .../tl_p162v_preTEI.xml -> 162v

    text = text.replace('\n', '**NEWLINE**') # re.findall cannot scan over newlines.
    divs = re.findall(r'(<div([\w\s=";-]*)>(.*?)</div>)', text) # separate text by divs
    if divs:
      for i, div in enumerate(divs): # iterate through divs
        attributes = div[1] # text within div tag, between second parentheses in the regex.
        identity = re.findall(r'id="p([\w_]*)"', attributes) # find identity
        identity = identity[0] if identity else '' # unpack identity from regex
        key = f'{folio};{identity}' # create unique key for attaching 'continued' entries.
        if key in entries.keys(): # if this div is a part of another entry, attach them
          new_text = div[0].replace('**NEWLINE**', '\n').replace('\n\n\n', '\n\n')
          entries[key] = entries[key] + "\n\n" + new_text
        else: # otherwise create a new entry in the entries dict.
          entries[key] = div[0].replace('**NEWLINE**', '\n').replace('\n\n\n', '\n\n')
  return entries