#-*- coding:utf-8 -*-
"""make_change_a.py
"""
import sys,re,codecs

class Lnum(object):
 def __init__(self,line):
  line = line.rstrip('\r\n')
  parts = line.split('\t')  # tab-delimited
  self.ilinestr,self.meta,self.ls = parts
  self.iline = int(self.ilinestr)
  
  
def init_lsnums(filein):
 with codecs.open(filein,"r","utf-8") as f:
  recs = [Lnum(x) for x in f]
 print(len(recs),'numeric ls read from',filein)
 # git dictionary based on iline. Take into account 'duplicates'
 d = {}
 for rec in recs:
  iline = rec.iline
  if iline not in d:
   d[iline] = []
  d[iline].append(rec)
 return recs,d

def mark_lsnums_0(lines,lsnums): 
 newlines = []
 for line in lines:
  newlines.append(line)
 # revise newlines based on lsnums
 for rec in lsnums:
  iline = rec.iline
  ls = rec.ls
  old = newlines[iline]
  new = old.replace(ls,'**'+ls)
  new1 = new.replace('**<ls>','<ls n="">')
  newlines[iline] = new1
  if False: # dbg
   print('iline=%s, ls=%s' % (iline,ls))
   print('old:%s' % old)
   print()
   print('new:%s' % new)
   exit(1)
 return newlines

def mark_lsnums_1(lines,lsnums): 
 newlines = []
 for line in lines:
  newlines.append(line)
 # 
 for rec in lsnums:
  iline = rec.iline
  ls = rec.ls
  old = newlines[iline]
  lscount = len(re.findall(r'<ls',old))
  if lscount != 1:  # can only handle 1
   continue
  # prev line
  ilineprev = iline - 1
  oldprev = newlines[ilineprev] # preceding line
  ls_all_prev = re.findall(r'<ls',oldprev)
  if len(ls_all_prev) != 1:  # cannot handle more than 1 in prev line
   continue
  m = re.search(r'<ls([^>]*)>([^<]*)</ls>',oldprev)
  if m == None:
   # Can happen if there is '<is>' or other markup in lsprev
   continue
   print('iline=%s'% iline)
   print('oldprev=',oldprev)
   print(ls_all_prev)
   exit(1)
  new = old.replace(ls,'**'+ls)
  new1 = new.replace('**<ls>','<ls n="">')
  newlines[iline] = new1
  if False: # dbg
   print('iline=%s, ls=%s' % (iline,ls))
   print('old:%s' % old)
   print()
   print('new:%s' % new)
   exit(1)
 return newlines

lsnames_approved = {
 "PAÑCAT.","MBH.","ṚV.","M.","N.","TS.","SUŚR.","VOP.","KATHĀS.","HIT.",
 "ŚAT. BR.","KĀTY. ŚR.","BHĀG. P.","ŚĀK.","R.","NIR.",
 }
def mark_lsnums_2(lines,lsnums): 
 newlines = []
 for line in lines:
  newlines.append(line)
 #
 nchg = 0
 for rec in lsnums:
  iline = rec.iline
  ls = rec.ls
  old = newlines[iline]
  lscount = len(re.findall(r'<ls',old))
  if lscount != 1:  # can only handle 1
   continue
  # prev line
  ilineprev = iline - 1
  oldprev = newlines[ilineprev] # preceding line
  ls_all_prev = re.findall(r'<ls',oldprev)
  if len(ls_all_prev) != 1:  # cannot handle more than 1 in prev line
   continue
  if re.search(r'[()]',oldprev):
   # exclude cases where the ls in previous line is parenthetical
   continue
  m = re.search(r'<ls([^>]*)>([^<]*)</ls>',oldprev)
  if m == None:
   # Can happen if there is '<is>' or other markup in lsprev
   continue
   print('iline=%s'% iline)
   print('oldprev=',oldprev)
   print(ls_all_prev)
   exit(1)
  # further restrictions
  mprev = re.search(r'^<ls([^>]*)>([^<]*)</ls>',oldprev)
  if mprev == None:
   continue
  mold = re.search(r'^<ls>[0-9]',old)
  if mold == None:
   continue
  # further require prev line starts with <ls>X. [0-9]
  # where X is string of non-digit characters
  mprev1 = re.search(r'^<ls>([^0-9]+\.) [0-9]',oldprev)
  if mprev1 == None:
   continue
  lsname = mprev1.group(1)
  if lsname not in lsnames_approved:
   continue
  lsnew = '<ls n="?%s">' %lsname  # ? for identification of this substitution
  new = old.replace('<ls>',lsnew)
  newlines[iline] = new
  nchg = nchg + 1
  if False: # dbg
   print('iline=%s, ls=%s' % (iline,ls))
   print('old:%s' % old)
   print()
   print('new:%s' % new)
   exit(1)
 print("make_change_a changes %s lines" %nchg)
 return newlines

if __name__=="__main__":
 filein = sys.argv[1] #  xxx.txt (path to digitization of xxx)
 filelnum = sys.argv[2] # lsunknown file generated by lsextract_all
 fileout = sys.argv[3] # marked revision of xxx.txt
 
 lsnums,dlsnums = init_lsnums(filelnum)
 with codecs.open(filein,"r","utf-8") as f:
  lines = [x.rstrip('\r\n') for x in f]
 newlines = mark_lsnums_2(lines,lsnums)
 # write newlines
 with codecs.open(fileout,"w","utf-8") as f:
  for out in newlines:
   f.write(out+'\n')
 print(len(newlines),"lines written to",fileout)

 
