""" Week 3 Assignment: Process Data and Email Info"""

# filled in code related to max_sales and car_year_sales

import json
import locale
import sys
import os
import operator
import reports
import emails


# needed to do: export LC_ALL="en_US.UTF-8" in bash for this to work

def load_data(filename):
    """Loads the contents of filename as a JSON file."""
    with open(filename) as json_file:
        data = sorted(json.load(json_file), key=lambda x: x["total_sales"])
    return data


def format_car(car):
    """Given a car dictionary, returns a nicely formatted name."""
    return "{} {} ({})".format(car["car_make"], car["car_model"], car["car_year"])


def process_data(data):
    """Analyzes the data, looking for maximums.

    Returns a list of lines that summarize the information.
    """
    locale.setlocale(locale.LC_ALL, 'en_US.UTF8')
    max_revenue = {"revenue": 0}
    # addes the following two initializers
    max_sales = {"total_sales": 0}
    car_year_sales = {}

    for item in data:
        # sample item
        # {
        #     "id": 47,
        #     "car": {
        #             "car_make": "Lamborghini",
        #             "car_model": "Murciélago",
        #             "car_year": 2002
        #             },
        #     "price": "$13724.05",
        #     "total_sales": 149
        # }
        #
        # Calculate the revenue generated by this model (price * total_sales)
        # We need to convert the price from "$1234.56" to 1234.56
        item_price = locale.atof(item["price"].strip("$"))
        item_revenue = item["total_sales"] * item_price
        if item_revenue > max_revenue["revenue"]:
            # add a revenue (k, v) pair
            item["revenue"] = item_revenue
            max_revenue = item

        # ADDED: also handle max sales
        if item["total_sales"] > max_sales["total_sales"]:
            max_sales = item

        # ADDED: also handle most popular car_year
        car_year = item["car"]["car_year"]
        car_year_sales[car_year] = car_year_sales.get(car_year, 0) + item["total_sales"]

    # ADDED: popular_yr, and summary's text (apart from first sentence)
    popular_yr = sorted(car_year_sales.items(),
                        key=operator.itemgetter(1),
                        reverse=True)[0]
    summary = [
            "The {} generated the most revenue: ${}".format(
             format_car(max_revenue["car"]), max_revenue["revenue"]),
            "The {} had the most sales: {}".format(
             format_car(max_sales["car"]), max_sales["total_sales"]),
            "The most popular year was {} with {} sales".format(
             popular_yr[0], popular_yr[1])
            ]
    return summary


def cars_dict_to_table(car_data):
    """Turns the data in car_data into a list of lists."""
    table_data = [["ID", "Car", "Price", "Total Sales"]]
    for item in car_data:
        table_data.append([item["id"], format_car(item["car"]),
                           item["price"], item["total_sales"]])
    return table_data


def main(argv):
    """Process the JSON data and generate a full report out of it."""
    data = load_data("/car_sales.json")
    summary = process_data(data)
    print(summary)
    # ADDED: turn this into a PDF report
    pdfPath = "/tmp/cars.pdf"
    title = "Car Sales Report"
    additional_info = "<br/>".join(summary)
    table_data = cars_dict_to_table(data)
    reports.generate(pdfPath, title, additional_info, table_data)

    # ADDED: send the PDF report as an email attachment
    sender = "automation@example.com"
    user = os.environ.get('USER')
    recipient = "{}@example.com".format(user)
    subject = "Sales summary for last month"
    body = "\n".join(summary)
    attachment_path = pdfPath
    message = emails.generate(sender, recipient, subject, body, attachment_path)
    emails.send(message)


if __name__ == "__main__":
    main(sys.argv)
