"""Punctul de pornire pentru cPanel/Passenger.

Dacă aplicația nu poate porni, eroarea completă este salvată în
instance/startup_error.log, iar browserul afișează instrucțiuni sigure.
"""
from __future__ import annotations

import html
import os
import sys
import traceback
from pathlib import Path

APP_ROOT = Path(__file__).resolve().parent
INSTANCE_DIR = APP_ROOT / "instance"
INSTANCE_DIR.mkdir(parents=True, exist_ok=True)

# Asigură importul fișierelor aplicației chiar dacă Passenger pornește din alt folder.
for path in (APP_ROOT, APP_ROOT / "vendor"):
    if path.exists() and str(path) not in sys.path:
        sys.path.insert(0, str(path))

os.chdir(APP_ROOT)


def _write_startup_error(details: str) -> None:
    try:
        (INSTANCE_DIR / "startup_error.log").write_text(details, encoding="utf-8")
    except Exception:
        pass


try:
    from app import create_app

    application = create_app()
except Exception:
    error_details = traceback.format_exc()
    _write_startup_error(error_details)

    def application(environ, start_response):
        body = """<!doctype html>
<html lang=\"ro\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">
<title>MenV4 Imobiliare – configurare necesară</title>
<style>body{font-family:system-ui;background:#0c1110;color:#eef7f1;margin:0;padding:40px}main{max-width:760px;margin:auto;background:#151d1a;border:1px solid #2d3b35;border-radius:18px;padding:28px}h1{color:#67e8a5}code{background:#0b100e;padding:3px 7px;border-radius:6px}li{margin:10px 0}</style></head>
<body><main><h1>Aplicația nu a putut porni</h1>
<p>Eroarea completă a fost salvată în <code>imobiliare_app/instance/startup_error.log</code>.</p>
<ol><li>Verifică dacă <code>app.py</code>, <code>models.py</code> și <code>passenger_wsgi.py</code> sunt direct în <code>imobiliare_app</code>.</li>
<li>În Setup Python App rulează Pip Install pentru <code>requirements.txt</code>.</li>
<li>Rulează <code>diagnostic.py</code>, apoi repornește aplicația.</li></ol>
</main></body></html>""".encode("utf-8")
        start_response(
            "500 Internal Server Error",
            [("Content-Type", "text/html; charset=utf-8"), ("Content-Length", str(len(body)))],
        )
        return [body]
