import cv2
import time
import numpy as np
from helper import (
    tap,
    look_for_templates,
    first_template,
    capture_current_screen,
    get_current_screen,
)

# templates
templates = {
    "to_battle": cv2.imread("templates/dungeon/to_battle.png"),
    "attack": cv2.imread("templates/dungeon/attack.png"),
    "auto_battle": cv2.imread("templates/dungeon/auto_battle.png"),
    "ok": cv2.imread("templates/dungeon/ok.png"),
    "lock": cv2.imread("templates/dungeon/lock.png"),
    "collect": cv2.imread("templates/dungeon/collect.png"),
}

tpl_mixed = cv2.imread("templates/dungeon/mixed.png")
tpl_water = cv2.imread("templates/dungeon/water.png")
tpl_earth = cv2.imread("templates/dungeon/earth.png")
tpl_angus = cv2.imread("templates/dungeon/angus.png")
tpl_moloch = cv2.imread("templates/dungeon/moloch.png")
tpl_angus2 = cv2.imread("templates/dungeon/angus2.png")
tpl_moloch2 = cv2.imread("templates/dungeon/moloch2.png")


def low_health(element, name):
    left = element[0] - 113
    right = element[0] + 108
    top = element[1] + 158
    bottom = top + 11

    screen = read_screen()

    health_bar = screen[top:bottom, left:right]
    cv2.imwrite("test/health_bar.png", health_bar)

    health_bar_hsv = cv2.cvtColor(health_bar, cv2.COLOR_BGR2HSV)
    green_lower = np.array([40, 40, 40])  # Lower end of green in HSV
    green_upper = np.array([80, 255, 255])  # Upper end of green in HSV

    mask = cv2.inRange(health_bar_hsv, green_lower, green_upper)

    total_length = mask.shape[1]
    current_length = total_length - np.argmax(np.flip(mask[0]) > 0)
    health_percentage = (current_length / total_length) * 100

    print(f"Remaining Health ({name}): {health_percentage:.2f}%")

    return health_percentage < 60


def read_screen():
    data = get_current_screen()
    image_data = np.frombuffer(data, dtype=np.uint8)

    return cv2.imdecode(image_data, cv2.IMREAD_COLOR)


print("watching the screen...")
is_mixed = False
while True:
    try:
        capture_current_screen()

        name, locations = look_for_templates(templates)
        if name is not None:
            if name in ["to_battle", "auto_battle", "ok", "lock", "collect"]:
                if name in ["auto_battle"]:
                    if is_mixed:
                        moloch = first_template(tpl_moloch)
                        if moloch and moloch[1] < 1000 and low_health(moloch, "moloch"):
                            angus = first_template(tpl_angus2)
                            if angus:
                                tap(angus)
                                time.sleep(0.5)
                                tap(angus[0] + 500, angus[1])
                            else:
                                print(
                                    "######### seems like angus is dead already. stopping"
                                )
                                break
                        else:
                            angus = first_template(tpl_angus)
                            if angus and angus[1] < 1000 and low_health(angus, "angus"):
                                moloch = first_template(tpl_moloch2)
                                if moloch:
                                    tap(moloch)
                                    time.sleep(0.5)
                                    tap(moloch[0] - 500, moloch[1])
                                else:
                                    print(
                                        "######### seems like moloch is dead already. stopping"
                                    )
                                    break
                        time.sleep(0.5)
                tap(*locations[0])
                if name in ["auto_battle", "ok"]:
                    time.sleep(1.5)
            if name == "attack":
                if len(locations) == 1:
                    element = first_template(tpl_mixed)
                    is_mixed = element is not None
                    tap(*locations[0])
                elif len(locations) == 2:
                    element = first_template(tpl_mixed)
                    if element:
                        is_mixed = True
                    else:
                        is_mixed = False
                        element = first_template(tpl_water)
                        if element is None:
                            element = first_template(tpl_earth)

                    tap(element[0], locations[0][1])

        print("...")
    except Exception as e:
        print(f"error: {e}")
