import os
import tempfile
from dataclasses import dataclass

from .magick import run_bytes
from .ocr import read_queue_number, resolve_crop
from .portal import capture_portal_window


@dataclass
class QueueReadResult:
    number: str
    details: list
    crop: tuple | None = None
    portal_info: dict | None = None


def read_image_once(args, image_path):
    crop = resolve_crop(
        image_path,
        args.crop,
        args.reference_crop,
        args.reference_size,
        args.scale_mode,
        args.cropped,
    )
    number, details = read_queue_number(
        image_path,
        crop,
        args.template_set,
        args.font,
        args.pointsize,
        args.cropped,
    )
    return QueueReadResult(number=number, details=details, crop=crop)


def read_portal_window_once(args):
    fd, image_path = tempfile.mkstemp(prefix="reforger-queue-", suffix=".png")
    os.close(fd)
    try:
        portal_info = capture_portal_window(
            image_path,
            args.portal_restore_token,
            args.portal_reselect,
            args.portal_timeout,
        )
        if args.save_input:
            run_bytes(["magick", image_path, "+repage", args.save_input])
        result = read_image_once(args, image_path)
        result.portal_info = portal_info
        return result
    finally:
        try:
            os.unlink(image_path)
        except OSError:
            pass
