import datetime

food_dict = {}

# ─────────────────────────────────────────────
# Load from file — runs at start and after each add
# ─────────────────────────────────────────────

def load_from_txt():
    try:
        with open("food_log.txt", "r", encoding="utf-8") as f:
            for line in f:
                row = line.strip().split(";")
                food_dict[row[0]] = [row[1], float(row[2]), row[3], int(row[4])]
    except FileNotFoundError:
        pass    # first run — no file yet

# ─────────────────────────────────────────────
# Add food item — writes to file, reloads dict
# ─────────────────────────────────────────────

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")
    with open("food_log.txt", "a", encoding="utf-8") as f:
        f.write(f"{timestamp};{name};{quantity};{measure};{calories}\n")
    load_from_txt()

# ─────────────────────────────────────────────
# 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]}")

# ─────────────────────────────────────────────
# General report — grouped by day, filtered by period
# ─────────────────────────────────────────────

def general_report():
    rep_dict = {}

    start_string = ""
    while not start_string:
        start_string = input("Start date (YYYY-MM-DD, e.g. 2025-04-01): ")

    stop_string = ""
    while not stop_string:
        stop_string = input("Stop date (YYYY-MM-DD, e.g. 2025-04-07): ")

    for key in food_dict:
        if start_string <= key.split(",")[0] <= stop_string:
            if key.split(",")[0] not in rep_dict:
                rep_dict[key.split(",")[0]] = [food_dict[key][3], {key.split(",")[1]: [food_dict[key][0], food_dict[key][1], food_dict[key][2], food_dict[key][3]]}]
            else:
                rep_dict[key.split(",")[0]][0] += food_dict[key][3]
                rep_dict[key.split(",")[0]][1][key.split(",")[1]] = [food_dict[key][0], food_dict[key][1], food_dict[key][2], food_dict[key][3]]

    return rep_dict

# ─────────────────────────────────────────────
# Export general report to txt file
# ─────────────────────────────────────────────

def export_general():
    food_log = general_report()

    start_string = min(food_log.keys())
    stop_string  = max(food_log.keys())
    filename = f"report_{start_string}_{stop_string}.txt"

    with open(filename, "w", encoding="utf-8") as f:
        for key in sorted(food_log):
            f.write("=" * 20 + "\n")
            f.write(f"Date: {key} - {food_log[key][0]} kcal consumed.\n")
            f.write("=" * 20 + "\n")
            day_dict = food_log[key][1]
            for subkey in sorted(day_dict):
                f.write(f"Time: {subkey} - {day_dict[subkey][0]}, {day_dict[subkey][1]}{day_dict[subkey][2]} - {day_dict[subkey][3]} kcal.\n")

    print(f"Report saved: {filename}")

# ─────────────────────────────────────────────
# Load on start
# ─────────────────────────────────────────────

load_from_txt()

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

while True:
    option = input("\nChoose option (1-Add, 2-Show food details, 3-Discipline analysis, 4-General report, 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 == "4":
        if len(general_report()):
            export_general()
        else:
            print("No data available.")
    elif option == "q":
        break
    else:
        print("Invalid option!")
