"""MaixCAM RGB detection for the XIAO ESP32-C3 Input / Output assignment."""

from maix import app, camera, display, err, image, pinmap, time, uart


FRAME_WIDTH = 320
FRAME_HEIGHT = 240
UART_BAUD = 115200
MIN_PIXELS = 800
MIN_AREA = 1200
STABLE_FRAMES = 3
LOST_FRAMES = 3

# Tune these LAB thresholds in MaixVision if lighting changes.
COLORS = (
    ("r", (0, 80, 40, 100, 10, 90), image.COLOR_RED),
    ("g", (0, 85, -128, -10, -20, 90), image.COLOR_GREEN),
    ("b", (0, 80, 10, 100, -128, -35), image.COLOR_BLUE),
)


def open_uart():
    err.check_raise(pinmap.set_pin_function("A16", "UART0_TX"), "Cannot map A16 to UART0_TX")
    return uart.UART("/dev/ttyS0", UART_BAUD)


def find_largest_colour(img):
    largest = None
    largest_letter = "n"
    largest_draw_colour = image.COLOR_WHITE
    largest_area = 0

    for letter, threshold, draw_colour in COLORS:
        for blob in img.find_blobs([threshold], pixels_threshold=MIN_PIXELS, area_threshold=MIN_AREA):
            area = blob[2] * blob[3]
            if area > largest_area:
                largest = blob
                largest_letter = letter
                largest_draw_colour = draw_colour
                largest_area = area

    return largest_letter, largest, largest_draw_colour


serial = open_uart()
cam = camera.Camera(FRAME_WIDTH, FRAME_HEIGHT)
screen = display.Display()

candidate = "n"
candidate_frames = 0
lost_frames = 0
state = "n"
sent_state = None
last_send_ms = 0

print("RGB detector started: A16 TX -> C3 D7/GPIO20, 115200 baud")

while not app.need_exit():
    img = cam.read()
    colour, blob, draw_colour = find_largest_colour(img)

    if blob:
        x, y, width, height = blob[0], blob[1], blob[2], blob[3]
        img.draw_rect(x, y, width, height, draw_colour, thickness=3)
        img.draw_string(x, max(0, y - 18), colour.upper(), draw_colour)
        lost_frames = 0

        if colour == candidate:
            candidate_frames += 1
        else:
            candidate = colour
            candidate_frames = 1

        if candidate_frames >= STABLE_FRAMES:
            state = colour
    else:
        candidate = "n"
        candidate_frames = 0
        lost_frames += 1
        if lost_frames >= LOST_FRAMES:
            state = "n"

    now = time.ticks_ms()
    if state != sent_state or now - last_send_ms >= 200:
        serial.write_str(state + "\n")
        print(state)
        sent_state = state
        last_send_ms = now

    screen.show(img)
    time.sleep_ms(10)
