"""
MaixCAM Pro RGB recognition and UART output.

Wiring:
    MaixCAM 6Pin TX / A16 / UART0_TX -> XIAO ESP32-C6 D7 / GPIO17 / RX
    MaixCAM GND                      -> XIAO ESP32-C6 GND

    If using XIAO ESP32-C3 instead:
    MaixCAM 6Pin TX / A16 / UART0_TX -> XIAO ESP32-C3 D7 / GPIO20 / RX
    MaixCAM GND                      -> XIAO ESP32-C3 GND

UART protocol (one ASCII character per line):
    r = red, g = green, b = blue, p = purple, y = yellow
    n = no color
"""

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


FRAME_WIDTH = 320
FRAME_HEIGHT = 240

MIN_PIXELS = 800
MIN_AREA = 1200
STABLE_FRAMES = 3
LOST_FRAMES = 3
UART_BAUD = 115200
UART_REPEAT_MS = 200

# LAB thresholds: (L min, L max, A min, A max, B min, B max).
# Use MaixVision's Threshold Editor / Find Blobs tool to tune these values
# when the ambient light or target material 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),
    ("p", (0, 75, 25, 100, -70, -5), image.COLOR_BLUE),
    ("y", (20, 100, -20, 45, 35, 127), image.COLOR_YELLOW),
)


def find_largest_color(img):
    best_letter = None
    best_blob = None
    best_draw_color = image.COLOR_WHITE
    best_area = 0

    for letter, threshold, draw_color in COLORS:
        blobs = img.find_blobs(
            [threshold],
            pixels_threshold=MIN_PIXELS,
            area_threshold=MIN_AREA,
        )
        for blob in blobs:
            area = blob[2] * blob[3]
            if area > best_area:
                best_letter = letter
                best_blob = blob
                best_draw_color = draw_color
                best_area = area

    return best_letter, best_blob, best_draw_color


def open_uart():
    # The white 6-pin connector uses UART0: A16=TX and A17=RX.
    err.check_raise(
        pinmap.set_pin_function("A17", "UART0_RX"),
        "Failed to map A17 to UART0_RX",
    )
    err.check_raise(
        pinmap.set_pin_function("A16", "UART0_TX"),
        "Failed to map A16 to UART0_TX",
    )
    return uart.UART("/dev/ttyS0", UART_BAUD)


def send_state(serial, state):
    serial.write_str(state + "\n")


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

candidate = None
candidate_frames = 0
lost_frames = 0
current_state = "n"
last_sent_state = None
last_send_ms = 0

print("RGB recognition started; UART0 TX=A16/6Pin TX, baud=115200")

while not app.need_exit():
    img = cam.read()
    letter, blob, draw_color = find_largest_color(img)

    if blob:
        x, y, w, h = blob[0], blob[1], blob[2], blob[3]
        img.draw_rect(x, y, w, h, draw_color, thickness=3)
        img.draw_string(x, max(0, y - 18), letter, draw_color)

        lost_frames = 0
        if letter == candidate:
            candidate_frames += 1
        else:
            candidate = letter
            candidate_frames = 1

        if candidate_frames >= STABLE_FRAMES:
            current_state = letter
    else:
        candidate = None
        candidate_frames = 0
        lost_frames += 1
        if lost_frames >= LOST_FRAMES:
            current_state = "n"

    now = time.ticks_ms()
    state_changed = current_state != last_sent_state
    repeat_due = now - last_send_ms >= UART_REPEAT_MS
    if state_changed or repeat_due:
        send_state(serial, current_state)
        last_send_ms = now
        if state_changed:
            print(current_state)
            last_sent_state = current_state

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