import json
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.radar.config import floorsImgs
from src.repositories.radar.core import getCoordinate, getFloorLevel
from src.repositories.radar.extractors import getRadarImage
from src.repositories.radar.locators import getRadarToolsPosition

data = json.loads((repo / 'file.json').read_text(encoding='utf-8-sig'))
waypoints = data['_default']['1']['config']['ng_cave']['waypoints']['items']
screenshot = cv2.imread(str(repo / '.pilotng-live.png'), cv2.IMREAD_GRAYSCALE)
tools = getRadarToolsPosition(screenshot)
floor = getFloorLevel(screenshot)
radar = getRadarImage(screenshot, tools)
scaled = cv2.resize(radar, None, fx=0.25, fy=0.25,
                    interpolation=cv2.INTER_NEAREST)
match = cv2.matchTemplate(floorsImgs[floor], scaled, cv2.TM_CCOEFF_NORMED)
_, score, _, position = cv2.minMaxLoc(match)
print(json.dumps({
    'shape': screenshot.shape,
    'tools': tools,
    'floor': floor,
    'rawQuarterMatch': {
        'score': float(score),
        'position': position,
        'coordinate': [
            31744 + position[0] + scaled.shape[1] // 2,
            30976 + position[1] + scaled.shape[0] // 2,
            floor,
        ],
    },
    'global': getCoordinate(screenshot),
    'route': getCoordinate(screenshot, waypoints=waypoints),
}))
