import json
import requests


def get_narratives_json(demo_json=None):
    """
    Main handler to deliver sample narratives to the landing page.

    To demo a local json file, pass in a file path via the 'demo_json' kwarg
    """

    if demo_json:
        with open(demo_json, 'r') as f:
            res_json = json.loads(f.read())
        return res_json

    s3json = "http://files.consumerfinance.gov/ccdb/narratives.json"
    try:
        res_json = requests.get(s3json).json()
    except requests.exceptions.RequestException as e:
        print("get_narratives_json:requests.exceptions.RequestException")
        print("There is a problem with getting data from the URL")
        print(e)
        res_json = {}
    except ValueError as e:
        print("get_narratives_json:ValueError")
        print("The text from the response doesn't follow "
              "the correct format to be parse as json")
        print(e)
        res_json = {}
    return res_json