import json
import os
import sys
import traceback
from pathlib import Path

import cv2
import win32gui


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

from src.repositories.gameWindow.config import gameWindowSizes
from src.repositories.gameWindow.core import getCoordinate as get_game_window
from src.repositories.radar.core import getCoordinate, getFloorLevel
from src.repositories.radar.locators import getRadarToolsPosition
from src.utils.core import getScreenshot


result = {'windows': []}


def collect_windows(hwnd, _):
    if not win32gui.IsWindowVisible(hwnd):
        return
    title = win32gui.GetWindowText(hwnd)
    if title:
        result['windows'].append({
            'title': title,
            'rect': win32gui.GetWindowRect(hwnd),
        })


try:
    win32gui.EnumWindows(collect_windows, None)
    screenshot = getScreenshot()
    result['screenshot'] = None if screenshot is None else list(screenshot.shape)
    if screenshot is not None:
        cv2.imwrite(str(repo / '.primary-runtime.png'), screenshot)
        result['radarTools'] = getRadarToolsPosition(screenshot)
        result['floor'] = getFloorLevel(screenshot)
        result['coordinate'] = getCoordinate(screenshot)
        result['gameWindow'] = get_game_window(screenshot, gameWindowSizes[1080])
except Exception:
    result['error'] = traceback.format_exc()

(repo / '.primary-runtime.json').write_text(
    json.dumps(result, ensure_ascii=False), encoding='utf-8'
)
