import asyncio
import datetime
import logging
import sys

from creation_helpers import get_args
from db_calls import db_get, DB_URL, player_desc, db_patch

date = f'{datetime.datetime.now().year}-{datetime.datetime.now().month}-{datetime.datetime.now().day}'
log_level = logging.INFO
logging.basicConfig(
    filename=f'logs/{date}.log',
    format='%(asctime)s - check-cards - %(levelname)s - %(message)s',
    level=log_level
)


async def main(args):
    arg_data = get_args(args)

    print('Pulling batting cards...')
    bc_query = await db_get('battingcards')
    print('Pulling pitching cards...')
    pc_query = await db_get('pitchingcards')
    b_count, p_count = 0, 0

    now = datetime.datetime.now()
    for x in bc_query['cards']:
        today_url = f'{DB_URL}/v2/players/{x["player"]["player_id"]}/battingcard?d={now.year}-{now.month}-{now.day}'
        if 'batting' not in x['player']['image']:
            await db_patch('players', object_id=x["player"]["player_id"], params=[('image2', today_url)])
            print(f'Adding batting card for {player_desc(x["player"])}')
            b_count += 1

    run_time = datetime.datetime.now() - now
    print(f'\nTotal Batters: {b_count}\nBatter runtime: {round(run_time.total_seconds())} seconds\n\n########\n')
    now = datetime.datetime.now()
    for x in pc_query['cards']:
        today_url = f'{DB_URL}/v2/players/{x["player"]["player_id"]}/pitchingcard?d={now.year}-{now.month}-{now.day}'
        if 'pitching' not in x['player']['image']:
            await db_patch('players', object_id=x["player"]["player_id"], params=[('image2', today_url)])
            print(f'Adding pitching card for {player_desc(x["player"])}')
            p_count += 1

    run_time = datetime.datetime.now() - now
    print(f'\nTotal Pitchers: {p_count}\nPitcher runtime: {round(run_time.total_seconds())} seconds')


if __name__ == '__main__':
    asyncio.run(main(sys.argv[1:]))
