#!/bin/python3

import argparse
import requests
import json
from datetime import datetime


API_URL = 'https://api.imagga.com/v2/tags'

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


argparser.add_argument('-cf', '--client-file', default='', help='File with Client ID and Secret')
argparser.add_argument('-ak', '--api-key', default='', help='API Key (if set, ignore --client-file)')
argparser.add_argument('-as', '--api_secret', default='', help='API 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)')
argparser.add_argument('-l', '--languages', default='en', help='Languages (default: en)')


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

    api_key = args.api_key
    api_secret = args.api_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:
                    api_key = c_id
                if len(c_s) > 0:
                    api_secret = c_s

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

    num_keywords = int(args.num_keywords)
    langs = args.languages
    if langs == '':
        langs = 'en'

    start = datetime.now()
    response = requests.get(
        API_URL,
        auth=(api_key, api_secret),
        params={
            'image_url': image,
            'limit': num_keywords,
            'language': langs,
        })
    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))
