# -*- coding: utf-8 -*-
"""Point d'entrée pour l'hébergement (cPanel « Setup Python App » / Passenger).

Le back-office (admin.py) tourne en interne et cette passerelle WSGI lui transmet
chaque requête. Rien à configurer ici : tout se règle dans le back-office.
Voir DEPLOIEMENT-BO-EN-LIGNE.md pour l'installation pas à pas.
"""
import os, sys, threading, socket, http.client, secrets

BASE = os.path.dirname(os.path.abspath(__file__))
os.chdir(BASE)
sys.path.insert(0, BASE)
os.environ.setdefault("VFG_ONLINE", "1")

import admin  # noqa: E402  (n'ouvre aucun port à l'import)

# premier lancement : dist/ et compte admin de secours si users.json absent
os.makedirs(admin.DIST, exist_ok=True)
if not admin.load_users():
    pw = secrets.token_urlsafe(9)
    admin.upsert_user("contact@agence-beecom.fr", pw, "admin")
    admin.log(f"Compte admin créé automatiquement — contact@agence-beecom.fr / {pw} (changez-le)")
if not os.path.exists(os.path.join(admin.DIST, "index.html")):
    try: admin.do_build()
    except Exception: pass

# serveur interne sur un port libre de la boucle locale
_sock = socket.socket(); _sock.bind(("127.0.0.1", 0))
_PORT = _sock.getsockname()[1]; _sock.close()
_server = admin.HTTPServer(("127.0.0.1", _PORT), admin.Admin)
threading.Thread(target=_server.serve_forever, daemon=True).start()

_HOP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization",
        "te", "trailers", "transfer-encoding", "upgrade"}

def application(environ, start_response):
    method = environ.get("REQUEST_METHOD", "GET")
    path = environ.get("PATH_INFO", "/") or "/"
    if environ.get("QUERY_STRING"): path += "?" + environ["QUERY_STRING"]
    try:
        length = int(environ.get("CONTENT_LENGTH") or 0)
    except ValueError:
        length = 0
    body = environ["wsgi.input"].read(length) if length else b""
    headers = {}
    for k, v in environ.items():
        if k.startswith("HTTP_"):
            name = k[5:].replace("_", "-").title()
            if name.lower() not in _HOP: headers[name] = v
    if environ.get("CONTENT_TYPE"): headers["Content-Type"] = environ["CONTENT_TYPE"]
    if length: headers["Content-Length"] = str(length)
    headers.setdefault("Host", environ.get("HTTP_HOST", "localhost"))

    conn = http.client.HTTPConnection("127.0.0.1", _PORT, timeout=300)
    conn.request(method, path, body=body or None, headers=headers)
    resp = conn.getresponse()
    data = resp.read()
    out_headers = [(k, v) for k, v in resp.getheaders() if k.lower() not in _HOP]
    start_response(f"{resp.status} {resp.reason}", out_headers)
    conn.close()
    return [data]
