import argparse
from agromatrix_tools import tool_dictionary_review as review


def main():
    parser = argparse.ArgumentParser()
    sub = parser.add_subparsers(dest='cmd')

    p_list = sub.add_parser('list')
    p_list.add_argument('--category', default=None)
    p_list.add_argument('--limit', type=int, default=50)

    p_approve = sub.add_parser('approve')
    p_approve.add_argument('--ref', required=True)
    p_approve.add_argument('--map-to', default=None)
    p_approve.add_argument('--create-new', action='store_true')
    p_approve.add_argument('--category', default=None)
    p_approve.add_argument('--name', default=None)
    p_approve.add_argument('--id', dest='id_', default=None)

    p_reject = sub.add_parser('reject')
    p_reject.add_argument('--ref', required=True)
    p_reject.add_argument('--reason', required=True)

    p_apply = sub.add_parser('apply')
    p_stats = sub.add_parser('stats')

    p_auto = sub.add_parser('auto-approve')
    p_auto.add_argument('--min-score', type=float, default=0.97)
    p_auto.add_argument('--category', default=None)
    p_auto.add_argument('--dry-run', action='store_true')

    args = parser.parse_args()

    if args.cmd == 'list':
        items = review.list_pending(limit=args.limit, category=args.category)
        for i in items:
            print(i)
    elif args.cmd == 'approve':
        if args.map_to:
            action = {'type': 'map_to_existing', 'canonical_id': args.map_to}
        elif args.create_new:
            action = {'type': 'create_new_entry', 'canonical_id': args.id_ or '', 'canonical_name': args.name or ''}
        else:
            action = {'type': 'add_synonym', 'canonical_id': args.map_to}
        print(review.approve_pending(args.ref, action))
    elif args.cmd == 'reject':
        print(review.reject_pending(args.ref, args.reason))
    elif args.cmd == 'apply':
        print('applied', review.apply_resolutions())
    elif args.cmd == 'stats':
        print(review.stats())
    elif args.cmd == 'auto-approve':
        print(review.auto_approve(min_score=args.min_score, category=args.category, dry_run=args.dry_run))
    else:
        parser.print_help()


if __name__ == '__main__':
    main()
