import os
import json
import requests
import argparse

from create_index import API_KEY, API_SECRET, index_endpoint

DISTANCE_THRESHOLD = 1.4


def search_index(image_path):
    if not os.path.exists(image_path):
        print('Path is invalid:', image_path)
        return None

    search_result = None
    with open(image_path, 'rb') as image_file:
        response = requests.post(
            index_endpoint,
            params={'distance': DISTANCE_THRESHOLD},
            files={'image': image_file},
            auth=(API_KEY, API_SECRET))

    try:
        search_result = response.json()['result']
    except Exception as e:
        print('Exception occured during reading the search response')
        print(e, response.content, response.status_code)

    return search_result


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('image_path', help='Image to search for')

    args = parser.parse_args()

    result = search_index(args.image_path)
    if not result:
        print('No result obtained')

    print('Search result:')
    print(json.dumps(result, indent=4))


if __name__ == '__main__':
    main()
