import datetime
import json
import time
import traceback
import urllib.request


def callback(payload):
    data = json.dumps(payload).encode("utf-8")
    last_error = None
    for attempt in range(1, 4):
        request = urllib.request.Request(
            "{{CallbackUrl}}",
            data=data,
            headers={"Content-Type": "application/json"},
            method="POST",
        )
        try:
            urllib.request.urlopen(request, timeout=60).read()
            return
        except Exception as exc:
            last_error = exc
            print(f"Callback attempt {attempt} of 3 failed: {exc}")
            if attempt < 3:
                time.sleep(2 * attempt)
    raise RuntimeError(f"Callback failed after 3 attempts: {last_error}")


job_result = {}


try:
    print(datetime.datetime.now(datetime.timezone.utc).isoformat(), "job={{JobId}} started")
    # --- Eigene Befehle hier einfügen ---

    # --- Ende eigene Befehle ---
    payload = {"status": "success", "exit_code": 0, "completed": True, "message": "Job completed"}
    if isinstance(job_result, dict):
        payload.update(job_result)
    callback(payload)
except Exception as exc:
    try:
        callback({"status": "failed", "exit_code": 1, "completed": True, "message": str(exc), "stderr": traceback.format_exc()})
    finally:
        raise
