import logging
import time
import requests
from PyQt6.QtCore import QObject, pyqtSignal, QUrl
from PyQt6.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply

logger = logging.getLogger(__name__)

_network_manager = None


def get_network_manager():
    global _network_manager
    if _network_manager is None:
        _network_manager = QNetworkAccessManager()
    return _network_manager


class ImageFetcher(QObject):
    finished = pyqtSignal(bytes)

    def __init__(self, url: str):
        super().__init__()
        self.url = url
        self._stopped = False
        self._reply = None
        self._start_time = None

    def stop(self):
        self._stopped = True
        if self._reply is not None:
            self._reply.abort()

    def start(self):
        if self._stopped:
            return

        self._start_time = time.time()
        manager = get_network_manager()

        request = QNetworkRequest(QUrl(self.url))
        request.setRawHeader(b"User-Agent", b"Mozilla/5.0")

        self._reply = manager.get(request)
        self._reply.finished.connect(self._on_finished)

    def _on_finished(self):
        if self._stopped or self._reply is None:
            if self._reply:
                self._reply.deleteLater()
            return

        reply = self._reply
        self._reply = None

        try:
            if reply.error() == QNetworkReply.NetworkError.NoError:
                data = reply.readAll().data()
                if self._start_time:
                    download_time = (time.time() - self._start_time) * 1000
                    logger.debug(
                        f"Downloaded {len(data)} bytes from {self.url} in {download_time:.2f}ms"
                    )
                if not self._stopped:
                    self.finished.emit(data)
            else:
                logger.debug(
                    f"Failed to fetch image from {self.url}: {reply.errorString()}"
                )
                if not self._stopped:
                    self.finished.emit(b"")
        finally:
            reply.deleteLater()

    def run(self):
        self.start()

    @staticmethod
    def get_header_image_url(app_id):
        return f"https://shared.akamai.steamstatic.com/store_item_assets/steam/apps/{app_id}/header.jpg"
