#!/usr/bin/python3

import argparse
import os
import sys
import subprocess

from erimp import Erimp
from oporp import Oporp

desc = 'take oprop'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('-v', action='store_true', help='raise verbosity')
parser.add_argument('-o', action='store_true', help='overwrite existing')
parser.add_argument('-r', action='store_true', help='reparse form')
parser.add_argument('-a', action='store_true', help='do all')
parser.add_argument('repcode', type=str, nargs='?',
                    help='suggested repcode')
parser.add_argument('stafid', type=str, nargs='?',
                    help='suggested editor handle')
args = parser.parse_args()

# # this assumes the impna as the environment
impna = os.environ['IMPNA']
bapis = [impna]
e = Erimp(bapis, do_verbose=args.v)

oporp = Oporp(e, do_verbose=args.v)
if not e.impna:
    print("I need an impna")

if args.r:
    oporp.reparse()
    sys.exit()

# # if we don't give a repcode, just show the title
if args.repcode is None:
    title = oporp.title_from_latest_fufi()
    print(title)
    sys.exit()

if args.stafid is None:
    print("I now need an editor handle")
    sys.exit()

repcode = args.repcode
if '-' not in repcode:
    repcode = impna + '-' + repcode
oporp.files_from_latest_fufi(repcode, args.stafid, do_renew=args.o)

# #  run update_schemas with the new codes. update_schemas fires up filids
# # and adds the repcode and the edicode as valid codes. It
# # will then generate new .rnc files in ernad/opt/schema used
# # to edit the files

s = e.dirs['bin'] + '/schemas '
s += f" {args.repcode}" + f" {args.stafid}"
# print(s)
subprocess.run(s, shell=True, check=True)

### fire up emacs
s = e.dirs['bin'] + '/edit'
s += f" {args.repcode} {args.stafid}"
subprocess.run(s, shell=True, check=True)
