import json
import os
import sys
from pathlib import Path
from time import sleep

repo = Path.home() / 'TibiaPilotNG'
sys.path.insert(0, str(repo))
os.environ['TIBIAPILOT_OUTPUT_IDX'] = '2'

from src.repositories.radar.core import getCoordinate
from src.repositories.radar.locators import getRadarToolsPosition
from src.utils.core import getScreenshot
from src.utils.ino import _bridgeRequest, _cursorPosition, sendCommandArduino
from src.utils.keyboard import _focusTibia


def move_to(x, y):
    for _ in range(80):
        current_x, current_y = _cursorPosition()
        dx, dy = x - current_x, y - current_y
        if abs(dx) <= 2 and abs(dy) <= 2:
            return True
        command_x = max(-40, min(40, round(dx / 3)))
        command_y = max(-40, min(40, round(dy / 3)))
        if dx and not command_x:
            command_x = 1 if dx > 0 else -1
        if dy and not command_y:
            command_y = 1 if dy > 0 else -1
        if _bridgeRequest(f'move,{command_x},{command_y}') != 'OK':
            return False
        sleep(0.02)
    return False


_focusTibia()
screenshot = getScreenshot()
tools = getRadarToolsPosition(screenshot)
target = None if tools is None else (
    tools[0] + tools[2] // 2,
    tools[1] + tools[3] + 22,
)
before = _cursorPosition()
moved = target is not None and move_to(*target)
after = _cursorPosition()
clicked = sendCommandArduino('leftClick') if moved else False
sleep(0.7)
coordinate = getCoordinate(getScreenshot())
events = [{
    'target': target,
    'before': before,
    'after': after,
    'clicked': clicked,
}]

(repo / '.zoom-minimap-result.json').write_text(json.dumps({
    'attempts': 1,
    'coordinate': coordinate,
    'events': events,
}), encoding='utf-8')
