#  standard
import json
import re

# PyQGIS
from qgis.PyQt.QtCore import QByteArray, QUrl

# plugin
from oslandia.constants import UTM_CONTENT_ISSUEBROWSER
from oslandia.toolbelt import PlgLogger, PlgOptionsManager
from oslandia.toolbelt.network_manager import NetworkRequestsManager


class MarkdownRequestManager:
    def __init__(self):
        """Manager to use Gitlab API for markdown render"""
        self.log = PlgLogger().log
        self.ntwk_requester_blk = NetworkRequestsManager()
        self.plg_settings = PlgOptionsManager.get_plg_settings()

    def convert_markdown_to_html(
        self, text: str, project_path: str | None
    ) -> str | None:
        """Convert markdown to html with Gitlab API

        :param text: markdown text
        :type text: str
        :param project_path: project path. Needed to get redirection with gitlab format markdown
        :type project_path: Optional[str]
        :return: markdown converted to html. None if no reply from Gitlab API
        :rtype: Optional[str]
        """
        # encode data
        data = QByteArray()
        data_map = {
            "text": text,
            "gfm": self.plg_settings.use_gitlab_markdown_format,
        }
        if project_path:
            data_map["project"] = project_path
        data.append(json.dumps(data_map).encode("utf-8"))

        # send request
        req_reply = self.ntwk_requester_blk.post_url(
            url=QUrl(f"{self.plg_settings.gitlab_api_url_base}markdown"),
            config_id=self.plg_settings.authentification_config_id,
            data=data,
            content_type_header="application/json",
            caller=UTM_CONTENT_ISSUEBROWSER,
        )
        if req_reply:
            data = json.loads(req_reply.data().decode("utf-8"))
            return data["html"]
        else:
            return None

    @staticmethod
    def fix_gitlab_flavor_lazy_images(html: str) -> str:
        """Fix gitlab flavor html with lazy images load with src and data-src.
        Needed to use html with QTextBrowser other src will be asked and no image will be displayed

        :param html: html with lazy image
        :type html: str
        :return: converted html with data-src replaced by src
        :rtype: str
        """
        # Replace data-src="URL" with src="URL" for lazy images
        # Regexp generated with claude.ai
        html = re.sub(
            r'(<img[^>]*?)src="data:image/gif;base64,[^"]*"([^>]*?)data-src="([^"]*)"',
            r'\1src="\3"\2',
            html,
        )
        return html
