import argparse
import logging

import utils

parser = argparse.ArgumentParser()

parser.add_argument("-d", "--dry-run", type=bool, default=False, nargs="?", const=True)
parser.add_argument("-p", "--production", type=bool, default=False, nargs="?", const=True)

args = parser.parse_args()

utils.configure_logging('4066/4066.log')

if args.production:
    conn = utils.common_prod_connection()
    campaign_order = 7
    big_order_id = 43
    filename = '4066/4066.txt'
else:
    conn = utils.common_testing_connection()
    campaign_order = 845
    big_order_id = 45
    filename = '4066/4066_test.txt'

advance_tickets = set()
advance_file = open(filename)
for line in advance_file.readlines():
    ticket = line.strip()
    advance_tickets.add(ticket)

dispenser = utils.Dispenser(args.production, 'common')
reqs = dispenser.get_requests(status=['CONFIRMED'], campaignOrder=campaign_order, service='dbaas')

for req in reqs.body:
    ticket = req['trackerIssueKey']
    changes = []
    req_key = f"{req['id']} {ticket}"
    for change in req['changes']:
        if change['service']['key'] == 'dbaas' and \
            change['order']['id'] == big_order_id and \
            change['amount']['value'] > 0 and \
            change['amountReady']['value'] < change['amount']['value']:
            changes.append(change)
    if not changes:
        logging.info(f"Skipping request {req_key}")
        continue

    has_advance = ticket in advance_tickets

    if changes:
        changes_to_update_ready = []
        for change in changes:
            body = {
                "serviceKey": change['service']['key'],
                "resourceKey": change['resource']['key'],
                "segmentKeys": change['segmentKeys'],
                "bigOrderId": change['order']['id'],
                "amountReady": {
                    "unit": change['amount']['unit'],
                    "value": change['amount']['value']
                }
            }
            if has_advance:
                body["amountAllocated"] = {
                    "unit": change['amount']['unit'],
                    "value": change['amount']['value']
                }
            changes_to_update_ready.append(body)

        update_ready_request = {
            "updates": [
                {
                    "requestId": req['id'],
                    "changes": changes_to_update_ready
                }
            ]
        }

        logging.info(f"Body for {req_key}: {update_ready_request}")

        if not args.dry_run:
            logging.info(f"Updating ready amount for request {req_key}")
            r = dispenser.set_quota_state(update_ready_request)
            if r.status != 200:
                logging.error(f"Couldn't update ready amount for request {req_key}, status={r.status}: {r.body}")
                continue
