import hashlib
import json

from django.db import transaction
from django.db.models import F

from api.models import EngineResponseQuarantine


def quarantine_engine_response(*, payload, headers, reason) -> EngineResponseQuarantine:
    canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)
    digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
    fingerprint = hashlib.sha256(f"{reason}:{digest}".encode("utf-8")).hexdigest()
    request_id = payload.get("request_id") if isinstance(payload, dict) else None
    with transaction.atomic():
        record, created = EngineResponseQuarantine.objects.select_for_update().get_or_create(
            fingerprint=fingerprint,
            defaults={
                "request_id": request_id,
                "response_hash": digest,
                "reason": reason,
                "payload": payload,
                "headers": headers or {},
            },
        )
        if not created:
            EngineResponseQuarantine.objects.filter(pk=record.pk).update(
                occurrences=F("occurrences") + 1,
            )
            record.refresh_from_db()
        return record
