#!/bin/python3

import argparse
import requests
import json
from datetime import datetime


API_URL = 'https://api.everypixel.com/v1/keywords'

argparser = argparse.ArgumentParser(description='Test AI Image Tagging | everypixel.com')


argparser.add_argument('-cf', '--client-file', default='', help='File with Client ID and Secret')
argparser.add_argument('-ci', '--client-id', default='', help='Client ID (if set, ignore --client-file)')
argparser.add_argument('-cs', '--client-secret', default='', help='Client Secret (if set, ignore --client-file)')
argparser.add_argument('-i', '--image-url', help='Image URL')
argparser.add_argument('-api', '--api-url', default=API_URL, help='API URL (default: {})'.format(API_URL))
argparser.add_argument('-nk', '--num-keywords', default='5', help='Number of keywords (default: 5)')


if __name__ == '__main__':
    args = argparser.parse_args()

    client_id = args.client_id
    client_secret = args.client_secret

    if args.client_file != '':
        with open(args.client_file, 'r') as f:
            content = f.read()
            parts = content.split('\n')
            if len(parts) > 1:
                c_id = parts[0].strip()
                c_s = parts[1].strip()
                if len(c_id) > 0:
                    client_id = c_id
                if len(c_s) > 0:
                    client_secret = c_s

    image = args.image_url
    print('Image URL:', image)

    num_keywords = int(args.num_keywords)

    start = datetime.now()
    response = requests.get(
        API_URL,
        auth=(client_id, client_secret),
        params={
            'url': image,
            'num_keywords': num_keywords,
        })
    took = datetime.now() - start
    print('Request took', took)

    if response.status_code != 200:
        print(response.text)
        exit(1)

    response = json.loads(response.text)
    print('Response:', json.dumps(response, indent=4))
