import sys
from pathlib import Path

import cv2
import numpy as np

repo = Path.home() / 'TibiaPilotNG'
sys.path.insert(0, str(repo))

from src.repositories.battleList.extractors import getContent

screenshot = cv2.imread(str(repo / '.obs-tibia.png'), cv2.IMREAD_GRAYSCALE)
content = getContent(screenshot)
template = cv2.imread(
    str(repo / 'src/repositories/battleList/images/monsters/Cave Rat.png'),
    cv2.IMREAD_GRAYSCALE,
)

def mask(image):
    return np.isin(image, (192, 247)).astype(np.uint8)

reference = mask(template[:, :115])
print('content', content.shape, 'template', template.shape)
for slot in range(3):
    raw = content[slot * 22:(slot + 1) * 22, 23:138]
    live = mask(raw)
    scores = []
    for live_y in range(live.shape[0]):
        for ref_y in range(reference.shape[0]):
            for shift in range(-8, 9):
                shifted = np.roll(reference[ref_y], shift)
                if shift < 0:
                    shifted[shift:] = 0
                elif shift > 0:
                    shifted[:shift] = 0
                if live[live_y].sum() and reference[ref_y].sum():
                    scores.append((
                        int(np.count_nonzero(live[live_y] != shifted)),
                        live_y,
                        ref_y,
                        shift,
                        int(live[live_y].sum()),
                        int(reference[ref_y].sum()),
                    ))
    print('slot', slot, 'best', sorted(scores)[:8])
    print('slot', slot, 'unique', sorted(map(int, np.unique(raw))))
    current_row = mask(content[8 + slot * 24:9 + slot * 24, 23:138])[0]
    row_matches = []
    for path in (repo / 'src/repositories/battleList/images/monsters').glob('*.png'):
        candidate = mask(cv2.imread(str(path), cv2.IMREAD_GRAYSCALE)[4:5, :115])[0]
        row_matches.append((
            int(np.count_nonzero(current_row != candidate)), path.stem,
        ))
    print('slot', slot, 'row4', sorted(row_matches)[:8])
