# SPDX-FileCopyrightText: 2025 XLeitstelle Planen und Bauen <xleitstelle@gv.hamburg.de>
# SPDX-FileContributor: Anton Jacobsson <anton.jacobsson@init.de>
#
# SPDX-License-Identifier: EUPL-1.2-or-later

import json
import logging

import requests
from qgis.PyQt import QtCore

from xmas_plugin.util.metadata import PLUGIN_DIR_NAME

logger = logging.getLogger(PLUGIN_DIR_NAME)


class PostWorker(QtCore.QThread):
    finished_ok = QtCore.pyqtSignal(dict)
    failed = QtCore.pyqtSignal(str)

    def __init__(self, url: str, json_payload: dict, timeout: int = 60):
        super().__init__()
        self.url = url
        self.payload = json_payload
        self.timeout = timeout

    def run(self):
        try:
            # DEBUG: log target + short preview of payload
            try:
                preview = json.dumps(self.payload)[:800]
            except Exception:
                preview = "<unserializable>"
            logger.info(
                "[POST] %s | timeout=%ss | payload=%s", self.url, self.timeout, preview
            )

            headers = {
                "Accept": "application/json",
                "Content-Type": "application/json",
            }
            r = requests.post(
                self.url, json=self.payload, timeout=self.timeout, headers=headers
            )

            logger.info("[POST] %s -> %s %s", self.url, r.status_code, r.reason)
            body_preview = (r.text or "")[:1000]
            logger.debug("[POST] response body (trunc 1000): %s", body_preview)

            # Accept both 200 OK and 201 Created
            if r.status_code not in (200, 201):
                self.failed.emit(f"{r.status_code}: {body_preview}")
                logger.error("Request failed (%s): %s", r.status_code, body_preview)
                return

            try:
                data = r.json()
            except Exception:
                logger.exception("Failed to parse JSON response")
                self.failed.emit(f"{r.status_code}: {body_preview}")
                return

            self.finished_ok.emit(data)

        except requests.exceptions.RequestException as e:
            # Network/timeout/DNS/connection errors
            logger.exception("HTTP error calling %s", self.url)
            self.failed.emit(str(e))
        except Exception as e:
            logger.exception("Unexpected error in PostWorker.run()")
            self.failed.emit(str(e))
