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

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

from src.gameplay.core.tasks.setChatOff import SetChatOffTask
from src.repositories.chat.core import getChatStatus
from src.utils.core import getScreenshot
from src.utils.ino import _bridgeRequest, _cursorPosition, isArduinoAvailable, sendCommandArduino

before = getChatStatus(getScreenshot())
cursor_before = _cursorPosition()
available = isArduinoAvailable()
attempts = []


def move_to(target_x, target_y):
    for _ in range(80):
        current_x, current_y = _cursorPosition()
        dx, dy = target_x - current_x, target_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
        _bridgeRequest(f'move,{command_x},{command_y}')
        sleep(0.02)
    return False


after = before
for target_y in (1052, 1060, 1068, 1044, 1036):
    for target_x in (1498, 1510, 1524, 1540, 1553):
        moved = move_to(target_x, target_y)
        clicked = sendCommandArduino('leftClick')
        sleep(0.2)
        after = getChatStatus(getScreenshot())
        attempts.append((target_x, target_y, moved, clicked, _cursorPosition(), after))
        if not after[1]:
            break
    if not after[1]:
        break
(repo / '.chat-off-live.json').write_text(
    json.dumps({
        'before': before,
        'cursorBefore': cursor_before,
        'available': available,
        'attempts': attempts,
        'after': after,
    }), encoding='utf-8'
)
