from pathlib import Path

import cv2
import numpy as np

repo = Path.home() / 'TibiaPilotNG'
image = cv2.imread(str(repo / '.obs-tibia.png'), cv2.IMREAD_COLOR)
crop = image[6:710, 305:1265]
b, g, r = cv2.split(crop)
green = (g > 90) & (g > r * 1.35) & (g > b * 1.35)
red = (r > 90) & (r > g * 1.35) & (r > b * 1.35)

for label, mask in (('green', green), ('red', red)):
    runs = []
    for y, row in enumerate(mask):
        padded = np.pad(row.astype(np.int8), (1, 1))
        changes = np.diff(padded)
        starts = np.where(changes == 1)[0]
        ends = np.where(changes == -1)[0]
        for start, end in zip(starts, ends):
            if end - start >= 12:
                runs.append((y, int(start), int(end), int(end - start)))
    print(label, runs[:100])

gray = cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY)
for y in range(197, 206):
    print('gray', y, list(map(int, gray[y, 140:180])))

candidates = []
for y in range(gray.shape[0] - 2):
    for x in range(gray.shape[1] - 30):
        area = gray[y:y + 3, x:x + 31]
        if np.any(area[:, 0]) or np.any(area[:, -1]):
            continue
        inside = area[:, 1:-1]
        if all(np.count_nonzero(row) >= 2 and len(np.unique(row)) <= 4 for row in inside):
            candidates.append((y, x, [sorted(map(int, np.unique(row))) for row in inside]))
print('candidates', candidates[:100])
