#!/usr/bin/python3

import argparse
import datetime
import os

from erimp import Erimp

desc = 'scan for reports to be close'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('-v', action='store_true', help='raise verbosity')
parser.add_argument('-n', action='store_true', help='dry run')
parser.add_argument('bapis', metavar='bnp', type=str, nargs='*',
                    help='bits and pieces arguments')
args = parser.parse_args()

e = Erimp(args.bapis, do_verbose=args.v)
if 'death_by_issuegap' not in e.conf:
    print("I don't have a death_by_issuegap configured for " + e.impna + '.')
    quit()

do_verbose = args.v
today = datetime.datetime.today()
# # death by issuegap is in issues, convert to days
last_action_gap = 7 * int(e.conf['death_by_issuegap'])

issues_dir = e.dirs['issues']
for repcode in e.live:
    sent_dir = e.report[repcode].dirs['sent']
    ##
    last_sent_fufi = e.d.very_last(sent_dir)
    if last_sent_fufi is None:
        if do_verbose:
            print(f"{repcode} has not sent no last sent date")
        continue
    ## fixMe. This should be the time on the rif name
    last_sent_time = datetime.datetime.fromtimestamp(
        os.path.getmtime(last_sent_fufi))
    last_sent_duration = today - last_sent_time
    # print(str(last_sent_duration.days) + ' ' + str(last_action_gap))
    if last_sent_duration.days < last_action_gap:
        message = f"{repcode}: {last_sent_duration} is less "
        message += "then {last_action_gap}"
        print(message)
        continue
    source_dir = e.report[repcode].dirs['source']
    # # never brought out an issue
    if len(e.d.dates(sent_dir)) == 0:
        continue
    issues_gap = e.d.count_gap_issues(sent_dir)
    if issues_gap is None or issues_gap < int(e.conf['death_by_issuegap']):
        print(f"{repcode} has isses gap {issues_gap}")
        continue
    link = e.dirs['etc'] + '/reports/enabled/' + repcode \
        + e.abovo.constants['ext_amf']
    if not os.path.islink(link):
        continue
    if args.n:
        print("I need to remove " + link)
        continue
    if args.v:
        print("death_by_issuegap removes " + link)
    os.remove(link)
