import datetime

food_dict = {}

# ─────────────────────────────────────────────
# Add food item
# ─────────────────────────────────────────────

def add_food_item():
    name = ""
    while not name:
        name = input("Food name: ")

    while True:
        try:
            quantity = float(input("Quantity: "))
            if quantity > 0:
                break
            print("Quantity must be greater than 0.")
        except ValueError:
            print("Invalid quantity. Enter a number.")

    measure = ""
    while not measure:
        measure = input("Measure: ")

    while True:
        try:
            calories = int(input("Calories: "))
            if calories > 0:
                break
            print("Calories must be greater than 0.")
        except ValueError:
            print("Invalid calories. Enter a whole number.")

    timestamp = datetime.datetime.now().strftime("%Y-%m-%d,%H:%M:%S")
    food_dict[timestamp] = [name, quantity, measure, calories]

# ─────────────────────────────────────────────
# Filter last 7 days — detailed
# ─────────────────────────────────────────────

def last_days_details():
    today = datetime.datetime.now()
    last_days_dict = {}

    for n in range(0, 8):
        reference_day = (today - datetime.timedelta(days=n)).strftime("%Y-%m-%d")
        for key in food_dict:
            if reference_day == key.split(",")[0]:
                last_days_dict[key] = food_dict[key]

    return last_days_dict

# ─────────────────────────────────────────────
# Print detailed view
# ─────────────────────────────────────────────

def print_details():
    food_log = last_days_details()
    for key in food_log:
        print(f"{key.split(',')[0]} - {food_log[key][0]} - {food_log[key][1]}{food_log[key][2]} - {food_log[key][3]} kcal")

# ─────────────────────────────────────────────
# Weekly calorie sum with target comparison
# ─────────────────────────────────────────────

def last_days_sum():
    today_string = ""
    while not today_string:
        today_string = input("Reference date (YYYY-MM-DD, e.g. 2025-04-02): ")

    while True:
        try:
            calories_target = int(input("Your daily calories target: "))
            if calories_target > 0:
                break
            print("Target must be greater than 0.")
        except ValueError:
            print("Invalid calories target. Enter a whole number.")

    last_days_dict = {}

    for key in food_dict:
        if today_string == key.split(",")[0]:
            if key.split(",")[0] not in last_days_dict:
                last_days_dict[key.split(",")[0]] = 0
            last_days_dict[key.split(",")[0]] += food_dict[key][3]

    for key in last_days_dict:
        if last_days_dict[key] <= calories_target:
            cal_value = last_days_dict[key]
            last_days_dict[key] = [cal_value, "On target! Great job!"]
        else:
            cal_value = last_days_dict[key]
            cal_diff = cal_value - calories_target
            last_days_dict[key] = [cal_value, "Over target by " + str(cal_diff) + " kcal."]

    return last_days_dict

# ─────────────────────────────────────────────
# Print discipline analysis
# ─────────────────────────────────────────────

def print_target():
    food_log = last_days_sum()
    for key in sorted(food_log):
        print(f"Date: {key} - {food_log[key][0]} kcal consumed. {food_log[key][1]}")

# ─────────────────────────────────────────────
# Menu
# ─────────────────────────────────────────────

while True:
    option = input("\nChoose option (1-Add, 2-Show food details, 3-Discipline analysis, q-Quit): ")
    if option == "1":
        add_food_item()
        print("Food log added successfully!")
    elif option == "2":
        if len(last_days_details()):
            print_details()
        else:
            print("No data available.")
    elif option == "3":
        if len(last_days_sum()):
            print_target()
        else:
            print("No data available.")
    elif option == "q":
        break
    else:
        print("Invalid option!")
