# -*- coding: utf-8 -*-
"""Test minim, de unica folosinta: confirma daca PySide6/Qt poate randa o
imagine fara fereastra ("offscreen") pe acest server, inainte sa construim
restul aplicatiei web Ofertare pe aceasta baza. Nu depinde de niciun alt
fisier din proiect - e complet de sine statator, ca sa izoleze exact
intrebarea "merge Qt aici?" de orice altceva.

Daca randarea reuseste, raspunde cu o imagine PNG (text rosu pe fond alb).
Daca Qt nu poate porni (lipseste o libraria de sistem, de exemplu), raspunde
cu eroarea completa, ca text simplu - utila pentru diagnostic, nu pentru
public.
"""

from __future__ import annotations

import os
import sys
import traceback

os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")


def _render_test_png() -> bytes:
    from PySide6.QtCore import QBuffer, QByteArray, QIODevice, QRectF, Qt
    from PySide6.QtGui import QColor, QFont, QImage, QPainter
    from PySide6.QtWidgets import QApplication

    app = QApplication.instance() or QApplication(sys.argv)

    image = QImage(480, 140, QImage.Format_ARGB32)
    image.fill(QColor("white"))

    painter = QPainter(image)
    painter.setPen(QColor("#7A0000"))
    painter.setFont(QFont("DejaVu Sans", 16))
    painter.drawText(
        QRectF(12, 12, 456, 116),
        int(Qt.AlignLeft | Qt.AlignVCenter | Qt.TextWordWrap),
        "Qt offscreen OK - Ofertare smoke test 2026-11-19",
    )
    painter.end()

    buffer = QByteArray()
    qbuffer = QBuffer(buffer)
    qbuffer.open(QIODevice.WriteOnly)
    image.save(qbuffer, "PNG")
    qbuffer.close()

    return bytes(buffer)


def application(environ, start_response):
    try:
        png_bytes = _render_test_png()
        start_response(
            "200 OK",
            [
                ("Content-Type", "image/png"),
                ("Content-Length", str(len(png_bytes))),
                ("Cache-Control", "no-store"),
            ],
        )
        return [png_bytes]
    except Exception as exc:  # diagnostic deliberat larg - vrem orice eroare, in text
        detail = (
            "Qt offscreen FAILED\n\n"
            + repr(exc)
            + "\n\n"
            + traceback.format_exc()
        ).encode("utf-8")
        start_response(
            "200 OK",
            [
                ("Content-Type", "text/plain; charset=utf-8"),
                ("Content-Length", str(len(detail))),
                ("Cache-Control", "no-store"),
            ],
        )
        return [detail]
