"""
pizza_turtle.py  -  Shelly the turtle draws your pizza!
========================================================
Reads last_order.json (written by pizza_bot.py) and draws the pizza that was
ordered.  If there is no saved order, it asks a couple of quick questions
instead so it always has something to draw.

Run:  python pizza_turtle.py
"""

import json
import math
import random
import turtle

# ---------- colours ----------
CRUST_NORMAL = "#d9a066"   # golden crust
CRUST_GF = "#c98a4b"       # gluten-free base is a little darker
SAUCE = "#c0392b"
CHEESE_NORMAL = "#f6d365"
CHEESE_VEGAN = "#fff3b0"   # dairy-free cheese is paler
MUSHROOM = "#c9b79c"
PEPPER = "#27ae60"
OLIVE = "#2c3e50"
PEPPERONI = "#8e2f1f"
HAM = "#e8a0a0"
BACON = "#a0522d"
BOARD = "#8b5a2b"


# ---------- get the order ----------

def load_order():
    """Load last_order.json, or ask a few questions if it isn't there."""
    try:
        with open("last_order.json") as f:
            return json.load(f)
    except FileNotFoundError:
        print("No saved order found - let's make a quick one for Shelly to draw.")
        order = {
            "name": input("Name? ").strip().title() or "Friend",
            "size": "large" if input("Small or Large? ").strip().lower().startswith("l") else "small",
            "gluten_free": input("Gluten-Free base? (yes/no) ").strip().lower().startswith("y"),
            "dairy_free": input("Dairy-Free cheese? (yes/no) ").strip().lower().startswith("y"),
            "vegetarian": input("Vegetarian toppings? (yes/no) ").strip().lower().startswith("y"),
            "garlic_bread": False,
            "delivery": False,
        }
        order["total_cost"] = (10 if order["size"] == "small" else 15) \
            + (3 if order["gluten_free"] else 0) + (2 if order["dairy_free"] else 0)
        return order


# ---------- drawing helpers ----------

def filled_circle(t, x, y, radius, colour):
    """Draw a filled circle centred on (x, y)."""
    t.penup()
    t.goto(x, y - radius)
    t.pendown()
    t.color(colour)
    t.begin_fill()
    t.circle(radius)
    t.end_fill()
    t.penup()


def scatter(t, count, max_radius, draw_one):
    """Call draw_one(x, y) at 'count' random spots inside the cheese circle."""
    for _ in range(count):
        angle = random.uniform(0, 2 * math.pi)
        dist = random.uniform(0, max_radius)
        draw_one(dist * math.cos(angle), dist * math.sin(angle))


def draw_pizza(t, order):
    radius = 180 if order["size"] == "large" else 120

    # chopping board
    filled_circle(t, 0, 0, radius + 40, BOARD)

    # crust, sauce, cheese
    filled_circle(t, 0, 0, radius, CRUST_GF if order["gluten_free"] else CRUST_NORMAL)
    filled_circle(t, 0, 0, radius - 18, SAUCE)
    filled_circle(t, 0, 0, radius - 26, CHEESE_VEGAN if order["dairy_free"] else CHEESE_NORMAL)

    topping_area = radius - 50

    if order["vegetarian"]:
        # mushrooms
        scatter(t, 6, topping_area, lambda x, y: filled_circle(t, x, y, 12, MUSHROOM))
        # green pepper strips (little arcs)
        def pepper(x, y):
            t.penup(); t.goto(x, y); t.setheading(random.randint(0, 360))
            t.pendown(); t.color(PEPPER); t.pensize(6); t.circle(18, 120); t.pensize(1)
        scatter(t, 6, topping_area, pepper)
        # olives (ring = circle with a hole)
        def olive(x, y):
            filled_circle(t, x, y, 8, OLIVE)
            filled_circle(t, x, y, 3, CHEESE_VEGAN if order["dairy_free"] else CHEESE_NORMAL)
        scatter(t, 8, topping_area, olive)
    else:
        # meat supreme: pepperoni, ham, bacon
        scatter(t, 8, topping_area, lambda x, y: filled_circle(t, x, y, 14, PEPPERONI))
        scatter(t, 5, topping_area, lambda x, y: filled_circle(t, x, y, 9, HAM))
        def bacon(x, y):
            t.penup(); t.goto(x, y); t.setheading(random.randint(0, 360))
            t.pendown(); t.color(BACON); t.pensize(5); t.forward(28); t.pensize(1)
        scatter(t, 5, topping_area, bacon)

    # slice lines
    t.color("#7a3b1e")
    t.pensize(2)
    for i in range(4):
        angle = math.radians(i * 45)
        t.penup()
        t.goto(-radius * math.cos(angle), -radius * math.sin(angle))
        t.pendown()
        t.goto(radius * math.cos(angle), radius * math.sin(angle))
    t.pensize(1)
    t.penup()


def draw_garlic_bread(t, x, y):
    t.penup(); t.goto(x, y); t.setheading(0); t.pendown()
    t.color("#e0b070"); t.begin_fill()
    for _ in range(2):
        t.forward(90); t.circle(20, 180)
    t.end_fill()
    t.penup(); t.goto(x + 10, y + 12); t.color("#fff5cc"); t.pendown(); t.pensize(4)
    t.forward(70); t.pensize(1); t.penup()


def write_label(t, order):
    t.penup()
    t.goto(0, -260 if order["size"] == "large" else -200)
    t.color("white")
    notes = []
    if order["gluten_free"]:
        notes.append("Gluten-Free")
    if order["dairy_free"]:
        notes.append("Dairy-Free")
    notes.append("Vegetarian" if order["vegetarian"] else "Meat Supreme")
    line1 = order["name"] + "'s " + order["size"].title() + " Pizza"
    line2 = " | ".join(notes) + "   Total: $" + str(order["total_cost"])
    t.write(line1, align="center", font=("Arial", 22, "bold"))
    t.goto(0, t.ycor() - 30)
    t.write(line2, align="center", font=("Arial", 14, "normal"))


# ---------- main ----------

def main():
    order = load_order()

    screen = turtle.Screen()
    screen.title("Mario's Pizzeria - Shelly draws " + order["name"] + "'s pizza")
    screen.bgcolor("#1e2a38")
    screen.setup(width=760, height=680)

    shelly = turtle.Turtle()
    shelly.shape("turtle")
    shelly.color("#2ecc71")
    shelly.shapesize(2, 2)
    shelly.speed(0)          # fastest drawing; change to 6 to watch her work
    shelly.hideturtle()

    draw_pizza(shelly, order)
    if order.get("garlic_bread"):
        draw_garlic_bread(shelly, 190, 220)
    write_label(shelly, order)

    # Shelly takes a bow
    shelly.goto(0, 0)
    shelly.showturtle()
    shelly.penup()
    for _ in range(36):
        shelly.right(10)

    print("Done! Close the window to finish.")
    screen.mainloop()


if __name__ == "__main__":
    main()
