# # Pyxel from pyxel import *
import random
import pyxel
from pyxel import *

WIDTH = 160
HEIGHT = 120


# ------------------------

# ------------------------
class Player:
    def __init__(self):
        self.x = WIDTH // 2


class Apple:
    def __init__(self):
        self.x = random.randint(0, WIDTH - 8)
        self.y = 0
        self.type = random.choices(
            ["good", "bad", "gold"],
            weights=[75, 45, 6]
        )[0]


# PLAYER
player = Player()

# GAME STATE
state = "game"
minigame = None
cake_action = None
cake_progress = 0
mix_direction = "left"
cake_sequence = []
sequence_index = 0

# GAME VARS
apples = []
score = 0
lives = 2
speed = 1.3
spawn_timer = 0

# KUCHEN-PROGRESSION
# Stages: 0 = sammeln, 1 = zerschnipseln (30+), 2 = mischen (50+), 3 = kuchen fertig (100+)
cake_stage = 0
stage_banner_timer = 0   # zeigt Banner für kurze Zeit
STAGE_THRESHOLDS = {1: 30, 2: 50, 3: 100}
STAGE_LABELS = {
    1: "Aepfel zerschnipseln!",
    2: "Teig mischen!",
    3: "Kuchen fertig!"
}
STAGE_COLORS = {1: 10, 2: 9, 3: 10}  # pyxel-Farben

# MINIGAME VARS
timer = 0
success = False

# CONNECT GAME VARS
left_colors = [8, 11, 12, 10]
right_colors = [10, 8, 11, 12]
selected_left = None
selected_right = None
connections = []

# REACTION KEYS
possible_keys = [
    pyxel.KEY_A, pyxel.KEY_B, pyxel.KEY_C, pyxel.KEY_D, pyxel.KEY_E,
    pyxel.KEY_F, pyxel.KEY_G, pyxel.KEY_H, pyxel.KEY_I, pyxel.KEY_J,
    pyxel.KEY_K, pyxel.KEY_L, pyxel.KEY_M, pyxel.KEY_N, pyxel.KEY_O,
    pyxel.KEY_P, pyxel.KEY_Q, pyxel.KEY_R, pyxel.KEY_S, pyxel.KEY_T,
    pyxel.KEY_U, pyxel.KEY_V, pyxel.KEY_W, pyxel.KEY_X, pyxel.KEY_Y, pyxel.KEY_Z,
    pyxel.KEY_0, pyxel.KEY_1, pyxel.KEY_2, pyxel.KEY_3, pyxel.KEY_4,
    pyxel.KEY_5, pyxel.KEY_6, pyxel.KEY_7, pyxel.KEY_8, pyxel.KEY_9,
    pyxel.KEY_SPACE
]


key_names = {
    pyxel.KEY_A: "A", pyxel.KEY_B: "B", pyxel.KEY_C: "C",
    pyxel.KEY_D: "D", pyxel.KEY_E: "E", pyxel.KEY_F: "F",
    pyxel.KEY_G: "G", pyxel.KEY_H: "H", pyxel.KEY_I: "I",
    pyxel.KEY_J: "J", pyxel.KEY_K: "K", pyxel.KEY_L: "L",
    pyxel.KEY_M: "M", pyxel.KEY_N: "N", pyxel.KEY_O: "O",
    pyxel.KEY_P: "P", pyxel.KEY_Q: "Q", pyxel.KEY_R: "R",
    pyxel.KEY_S: "S", pyxel.KEY_T: "T", pyxel.KEY_U: "U",
    pyxel.KEY_V: "V", pyxel.KEY_W: "W", pyxel.KEY_X: "X",
    pyxel.KEY_Y: "Y", pyxel.KEY_Z: "Z",
    pyxel.KEY_0: "0", pyxel.KEY_1: "1", pyxel.KEY_2: "2",
    pyxel.KEY_3: "3", pyxel.KEY_4: "4", pyxel.KEY_5: "5",
    pyxel.KEY_6: "6", pyxel.KEY_7: "7", pyxel.KEY_8: "8",
    pyxel.KEY_9: "9",
    pyxel.KEY_SPACE: "SPACE"
}


current_key = pyxel.KEY_SPACE
wait_time = 60
can_click = False
secret = 1
attempts = 3


# ------------------------
# APPLE
# ------------------------
def spawn_apple():
    return Apple()


# ------------------------
# KUCHEN STAGE CHECK
# ------------------------
def check_cake_stage():
    global cake_stage, state, cake_action
    global cake_progress, mix_direction
    global cake_sequence, sequence_index

    if score >= 30 and cake_stage == 0:
        cake_stage = 1
        cake_action = "slice"
        cake_progress = 0
        state = "cake"

    elif score >= 50 and cake_stage == 1:
        cake_stage = 2
        cake_action = "mix"
        cake_progress = 0
        mix_direction = "left"
        state = "cake"

    elif score >= 100 and cake_stage == 2:
        cake_stage = 3
        cake_action = "bake"
        cake_sequence = [
            KEY_LEFT,
            KEY_RIGHT,
            KEY_LEFT,
            KEY_RIGHT,
            KEY_SPACE
        ]
        sequence_index = 0
        state = "cake"


# ------------------------
# START MINIGAME
# ------------------------
def start_minigame():
    global state, minigame, timer, success, wait_time, can_click, current_key
    global secret, attempts, left_colors, right_colors, selected_left, selected_right, connections

    minigame = random.choice(["connect", "guess", "reaction"])
    timer = 0
    success = False

    if minigame == "reaction":
        wait_time = random.randint(30, 90)
        can_click = False
        current_key = random.choice(possible_keys)

    elif minigame == "guess":
        secret = random.randint(1, 5)
        attempts = 3

    elif minigame == "connect":
        left_colors = [8, 11, 12, 10]
        right_colors = left_colors.copy()
        random.shuffle(right_colors)
        selected_left = None
        selected_right = None
        connections = []

    state = "minigame"


# ------------------------
# UPDATE
# ------------------------
def update():
    global state

    if state == "game":
        update_game()
    elif state == "minigame":
        update_minigame()
    elif state == "result":
        update_result()
    elif state == "game_over":
        if btnp(KEY_R):
            reset_game()
    elif state == "win":
        if btnp(KEY_R):
            reset_game()
    elif state == "cake":
        update_cake()


def update_cake():
    global state
    global cake_action
    global cake_progress
    global mix_direction
    global sequence_index

    # -------------------
    # ÄPFEL SCHNEIDEN
    # -------------------
    if cake_action == "slice":

        if btnp(KEY_SPACE):
            cake_progress += 1

        if cake_progress >= 20:
            state = "game"

    # -------------------
    # TEIG MISCHEN
    # -------------------
    elif cake_action == "mix":

        if mix_direction == "left":

            if btnp(KEY_LEFT):
                cake_progress += 1
                mix_direction = "right"

        else:

            if btnp(KEY_RIGHT):
                cake_progress += 1
                mix_direction = "left"

        if cake_progress >= 15:
            state = "game"

    # -------------------
    # KUCHEN BACKEN
    # -------------------
    elif cake_action == "bake":

        if btnp(cake_sequence[sequence_index]):
            sequence_index += 1

            if sequence_index >= len(cake_sequence):
                state = "win"
            


def reset_game():
    global player_x, apples, score, lives, speed, spawn_timer
    global state, cake_stage, stage_banner_timer, timer, success
    player.x = WIDTH // 2
    apples = []
    score = 0
    lives = 2
    speed = 1.3
    spawn_timer = 0
    cake_stage = 0
    stage_banner_timer = 0
    timer = 0
    success = False
    state = "game"


def update_game():
    global spawn_timer, apples, score, lives, speed, state, stage_banner_timer

    if btn(KEY_LEFT):
        player.x -= 2
    if btn(KEY_RIGHT):
        player.x += 2

    player.x = max(0, min(WIDTH - 10, player.x))

    spawn_timer += 1
    if spawn_timer > 25:
        apples.append(spawn_apple())
        spawn_timer = 0

    if stage_banner_timer > 0:
        stage_banner_timer -= 1

    for apple in apples[:]:
        apple.y += speed

        # KOLLISION
        if abs(apple.x - player.x) < 6 and abs(apple.y - (HEIGHT - 10)) < 6:

            if apple.type == "good":
                score += 1
                pyxel.play(3, 0)

                if score % 10 == 0:
                    speed = min(speed + 0.2, 3)

                check_cake_stage()

            elif apple.type == "bad":
                pyxel.play(3, 1)
                start_minigame()

            elif apple.type == "gold":
                lives += 1
                pyxel.play(3, 2)

            apples.remove(apple)
            continue

        if apple.y > HEIGHT:
            apples.remove(apple)

    if lives <= 0:
        state = "game_over"


def update_minigame():
    global timer, success, state, lives, can_click, attempts

    timer += 1

    # REACTION
    if minigame == "reaction":
        if timer > wait_time:
            can_click = True

        if btnp(current_key):
            if can_click and timer < wait_time + 20:
                success = True
            else:
                success = False
                lives -= 1

            state = "result"
            timer = 0

    # GUESS
    elif minigame == "guess":
        for i in range(1, 6):
            if btnp(getattr(__import__("pyxel"), f"KEY_{i}")):
                if i == secret:
                    success = True
                    state = "result"
                else:
                    attempts -= 1
                    if attempts <= 0:
                        success = False
                        lives -= 1
                        state = "result"

    # CONNECT
    elif minigame == "connect":
        global selected_left, selected_right, connections

        if btnp(KEY_1): selected_left = 0
        if btnp(KEY_2): selected_left = 1
        if btnp(KEY_3): selected_left = 2
        if btnp(KEY_4): selected_left = 3

        if btnp(KEY_Q): selected_right = 0
        if btnp(KEY_W): selected_right = 1
        if btnp(KEY_E): selected_right = 2
        if btnp(KEY_R): selected_right = 3

        if selected_left is not None and selected_right is not None:
            if selected_left in [c[0] for c in connections] or \
               selected_right in [c[1] for c in connections]:
                selected_left = None
                selected_right = None
                return

            if left_colors[selected_left] == right_colors[selected_right]:
                connections.append((selected_left, selected_right))
            else:
                lives -= 1
                success = False
                state = "result"

            selected_left = None
            selected_right = None

        if len(connections) == 4:
            success = True
            state = "result"


def update_result():
    global timer, state
    timer += 1
    if timer > 60:
        state = "game"


# ------------------------
# DRAW
# ------------------------
def draw():
    cls(0)

    if state == "game":
        draw_game()
    elif state == "minigame":
        draw_minigame()
    elif state == "result":
        draw_result()
    elif state == "game_over":
        draw_game_over()
    elif state == "win":
        draw_win()
    elif state == "cake":
        draw_cake_action()
        
def draw_cake_action():

    cls(1)

    if cake_action == "slice":

        text(35,20,"AEPFEL SCHNEIDEN!",10)

        rect(60,40,40,40,8)

        line(60,40,100,80,7)
        line(100,40,60,80,7)

        text(25,95,"SPACE HAEMMERN!",7)

        rect(20,110,120,4,5)
        rect(20,110,cake_progress*6,4,11)

    elif cake_action == "mix":

        text(45,20,"TEIG MISCHEN",9)

        circ(80,60,25,6)

        if mix_direction == "left":
            text(65,55,"<-",10)
        else:
            text(80,55,"->",10)

        text(20,95,"LINKS / RECHTS ABWECHSELND",7)

        rect(20,110,120,4,5)
        rect(20,110,cake_progress*8,4,10)

    elif cake_action == "bake":

        text(35,15,"KUCHEN DEKORIEREN!",10)

        rect(45,50,70,25,9)
        rect(45,40,70,10,8)

        controls = {
            KEY_LEFT:"LEFT",
            KEY_RIGHT:"RIGHT",
            KEY_SPACE:"SPACE"
        }

        current = controls[cake_sequence[sequence_index]]

        text(40,90,f"DRUECKE: {current}",7)


def draw_cake_progress():
    """Zeichne Kuchen-Fortschrittsleiste unten"""
    # Nächstes Ziel bestimmen
    next_stage = None
    next_threshold = None
    for stage in [1, 2, 3]:
        if cake_stage < stage:
            next_stage = stage
            next_threshold = STAGE_THRESHOLDS[stage]
            break

    if next_stage is None:
        return  # alle stages erreicht

    # Fortschrittsleiste
    bar_x = 5
    bar_y = HEIGHT - 6
    bar_w = WIDTH - 10
    bar_h = 3

    prev_threshold = STAGE_THRESHOLDS.get(next_stage - 1, 0)
    progress = min(score - prev_threshold, next_threshold - prev_threshold)
    fill = int(bar_w * max(0, progress) / (next_threshold - prev_threshold))

    rect(bar_x, bar_y, bar_w, bar_h, 5)
    rect(bar_x, bar_y, fill, bar_h, STAGE_COLORS.get(next_stage, 10))

    # Stage-Icons links vom Balken
    stage_icons = {1: "Schn.", 2: "Mix.", 3: "Cake"}
    text(bar_x, bar_y - 7, f"{stage_icons[next_stage]} {score}/{next_threshold}", 13)


def draw_stage_banner():
    """Zeige Banner wenn neuer Stage erreicht"""
    if stage_banner_timer <= 0:
        return
    label = STAGE_LABELS.get(cake_stage, "")
    color = STAGE_COLORS.get(cake_stage, 7)
    # Blinken in letzten 40 frames
    if stage_banner_timer > 40 or (stage_banner_timer // 5) % 2 == 0:
        rectb(15, 50, WIDTH - 30, 20, color)
        rect(16, 51, WIDTH - 32, 18, 0)
        # Zentrieren (grob)
        tx = WIDTH // 2 - len(label) * 2
        text(tx, 57, label, color)


def draw_game():
    bltm(0, 0, 0, 0, 0, WIDTH, HEIGHT)
    blt(player.x, HEIGHT - 32, 0, 0, 128, 16, 32, 0)

    for apple in apples:
        if apple.type == "good":
            blt(apple.x, apple.y, 0, 8, 56, 8, 8, 0)
        elif apple.type == "bad":
            blt(apple.x, apple.y, 0, 16, 56, 8, 8, 0)
        elif apple.type == "gold":
            blt(apple.x, apple.y, 0, 0, 56, 8, 8, 0)

    text(5, 5, f"Score: {score}", 7)
    text(5, 15, f"Leben: {lives}", 7)

    # Kuchen-Fortschritt
    draw_cake_progress()
    draw_stage_banner()


def draw_minigame():
    cls(1)

    if minigame == "reaction":
        if not can_click:
            text(40, 50, "Warte...", 7)
        else:
            text(20, 50, f"PRESS {key_names[current_key]}", 10)

    elif minigame == "guess":
        text(10, 40, "Zahl 1-5 erraten", 7)
        text(10, 60, f"Versuche: {attempts}", 7)

    elif minigame == "connect":
        text(20, 5, "1-4 links | Q-R rechts", 7)
        for i, color in enumerate(left_colors):
            rect(20, 20 + i * 20, 10, 10, color)
        for i, color in enumerate(right_colors):
            rect(120, 20 + i * 20, 10, 10, color)
        for l, r in connections:
            line(30, 25 + l * 20, 120, 25 + r * 20, 7)


def draw_result():
    if success:
        text(50, 50, "GESCHAFFT!", 11)
    else:
        text(50, 50, "VERLOREN!", 8)


def draw_game_over():
    cls(0)
    text(40, 50, "GAME OVER", 8)
    text(30, 70, "Druecke R", 7)


def draw_win():
    cls(0)

    # Kuchen-Animation: einfache ASCII-Darstellung mit Pyxel-Farben
    text(35, 15, "GEBURTSTAGS-", 10)
    text(45, 23, "KUCHEN!", 10)

    # Kuchenform
    rect(45, 55, 70, 25, 9)   # Kuchen-Koerper (braun/orange)
    rect(45, 45, 70, 12, 8)   # Sahne (rot = Glasur)
    rect(45, 43, 70, 4, 7)    # Sahne-Kante (weiss)

    # Kerzen
    for i in range(5):
        cx = 52 + i * 13
        rect(cx, 36, 3, 8, 10)   # Kerze
        pset(cx + 1, 35, 10)     # Flamme

    text(30, 90, f"Score: {score} Aepfel!", 7)
    text(30, 100, "Druecke R", 13)


# ------------------------
# START
# ------------------------

pyxel.init(WIDTH, HEIGHT, title="Fangpomme - Kuchenzeit!")
pyxel.load("res23.pyxres")




# ------------------------
# SOUNDS
# ------------------------

# Apfel einsammeln
pyxel.sound(0).set(
    "c3e3g3c4",
    "p",
    "7",
    "n",
    6
)

# Schlechter Apfel
pyxel.sound(1).set(
    "c2a1f1",
    "n",
    "7",
    "f",
    6
    
)

# Goldener Apfel
pyxel.sound(2).set(
    "c4g4c4",
    "t",
    "7",
    "n",
    7
)

# ------------------------
# HINTERGRUNDMUSIK
# ------------------------

# Melodie
#pyxel.sound(3).set(
   # "c3e3g3e3a3g3e3c3"
  #  "d3f3a3f3g3f3d3c3",
   # "p",
   # "4",
   # "n",
   # 7
#)

# Bass
#pyxel.sound(4).set(
   # "c2c2g1g1a1a1g1g1"
   # "f1f1c2c2g1g1c2c2",
   # "s",
   # "4",
   # "n",
   # 7
#)

# Begleitung
#pyxel.sound(5).set(
    #"g2g2e2e2f2f2e2e2"
   # "c2c2d2d2g1g1c2c2",
   # "t",
   # "4",
    #"n",
   # 7
#)

# Musik starten
#pyxel.music(0).set([3], [4], [5])
#pyxel.playm(0, loop=True)
#pyxel.run(update, draw)

# ------------------------
# HINTERGRUNDMUSIK
# ------------------------

# Sanfte Melodie
pyxel.sound(3).set(
    "c3c3c3c3"
    "d3d3d3d3"
    "e3e3e3e3"
    "d3f3a3f3",
    "t",
    "4",
    "n",
    14
)

# Gleichmäßiger Hintergrundton
pyxel.sound(4).set(
    "c2c2c2c2"
    "c2c2c2c2"
    "c2c2c2c2"
    "c2c2c2c2",
    "s",
    "2",
    "n",
    15
)

# Leichte Begleitung
pyxel.sound(5).set(
    "g2g2e2e2"
    "g2g2e2e2"
    "g2g2e2e2"
    "f2f2d2d2",
    "p",
    "3",
    "n",
    16
)

# Musik starten
pyxel.music(0).set([3], [4], [5])
pyxel.playm(0, loop=True)

pyxel.run(update, draw)