"""Moteur de synchronisation : journal d'émission, transport signé, idempotence."""
from __future__ import annotations

import hashlib
import hmac
import json
import time
import urllib.error
import urllib.request
import uuid
from datetime import datetime, timedelta, timezone as dt_timezone

from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import transaction
from django.utils import timezone

from apps.core.models import Sequence

from .models import (InboxEvent, Node, OutboxEvent, SyncChange, SyncConflict,
                     SyncCursor, SyncNonce, SyncRun)

PROTOCOL = "fablabs-sync/1"


def _json_default(obj):
    if isinstance(obj, uuid.UUID):
        return str(obj)
    if isinstance(obj, datetime):
        return obj.astimezone(dt_timezone.utc).isoformat().replace("+00:00", "Z")
    if hasattr(obj, "isoformat"):
        return obj.isoformat()
    return str(obj)


def canonical(payload) -> str:
    return json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=_json_default)


def get_local_node() -> Node:
    node_id = settings.NODE_ID
    parsed = None
    if node_id:
        try:
            parsed = uuid.UUID(str(node_id))
        except ValueError:
            parsed = None
    if parsed:
        node, _ = Node.objects.get_or_create(
            node_id=parsed,
            defaults={"role": settings.NODE_ROLE.upper(), "name": f"Nœud {settings.NODE_ROLE}"},
        )
        return node
    node = Node.objects.order_by("created_at").first()
    if node is None:
        node = Node.objects.create(role=settings.NODE_ROLE.upper(), name="Nœud local")
    return node


def next_local_seq(node: Node) -> int:
    with transaction.atomic():
        seq, _ = Sequence.objects.select_for_update().get_or_create(
            agency_id=node.id, name="sync_outbox", year=0
        )
        seq.last_value += 1
        seq.save(update_fields=["last_value"])
        return seq.last_value


@transaction.atomic
def emit(*, entity, op_type: str = "UPDATE", actor=None, agency_id=None,
         payload: dict | None = None, entity_type: str | None = None,
         entity_id=None, version: int | None = None) -> OutboxEvent:
    """Écrit un événement de synchronisation dans la transaction en cours."""
    node = get_local_node()
    entity_type = entity_type or entity._meta.label
    entity_id = entity_id or entity.pk
    version = version if version is not None else getattr(entity, "version", 1)
    agency = agency_id or getattr(entity, "agency_id", None)
    if agency is None and getattr(entity, "agency", None) is not None:
        agency = entity.agency_id
    if payload is None:
        payload = {}
        for field in entity._meta.fields:
            if field.name in {"created_by", "updated_by", "deleted_by"}:
                continue
            value = getattr(entity, field.attname if field.is_relation else field.name)
            if hasattr(value, "name") and not isinstance(value, str):
                value = value.name or None
            payload[field.name] = value
    seq = next_local_seq(node)
    prev = OutboxEvent.objects.filter(node=node).order_by("-local_seq").values_list("hash", flat=True).first() or ""
    event = OutboxEvent(
        node=node, entity_type=entity_type, entity_id=entity_id, op_type=op_type,
        agency_id=agency, base_version=max(version - 1, 0), version=version,
        payload=payload, occurred_at=timezone.now(), local_seq=seq, prev_hash=prev,
    )
    body = {
        "op_id": str(event.op_id), "op_type": op_type, "entity_type": entity_type,
        "entity_id": str(entity_id), "agency_id": str(agency) if agency else None,
        "version": version, "base_version": event.base_version, "local_seq": seq,
        "occurred_at": event.occurred_at.isoformat(), "payload": payload,
    }
    event.hash = hashlib.sha256(f"{prev}|{canonical(body)}".encode("utf-8")).hexdigest()
    event.save()
    return event


def pending_events(limit: int = 200, agency_id=None):
    qs = OutboxEvent.objects.filter(status__in=["PENDING", "FAILED", "DEFERRED"],
                                    next_attempt_at__lte=timezone.now())
    if agency_id:
        qs = qs.filter(agency_id=agency_id)
    return qs.order_by("local_seq")[:limit]


# --- Transport ---
def sign_headers(method: str, path: str, body: bytes, *, secret: str, node: Node) -> dict:
    timestamp = str(int(time.time()))
    nonce = str(uuid.uuid4())
    digest = hashlib.sha256(body).hexdigest()
    message = f"{method}\n{path}\n{timestamp}\n{nonce}\n{digest}"
    signature = hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest()
    return {
        "X-Node-Id": str(node.node_id),
        "X-Install-Id": str(node.install_id),
        "X-Timestamp": timestamp,
        "X-Nonce": nonce,
        "X-Signature": signature,
        "X-Protocol-Version": PROTOCOL,
        "Content-Type": "application/json",
    }


def verify_request(request, body: bytes, secret: str) -> tuple[bool, str, Node | None]:
    node_id = request.headers.get("X-Node-Id", "")
    timestamp = request.headers.get("X-Timestamp", "")
    nonce = request.headers.get("X-Nonce", "")
    signature = request.headers.get("X-Signature", "")
    if not all([node_id, timestamp, nonce, signature]):
        return False, "En-têtes d'authentification manquants", None
    node = Node.objects.filter(node_id=node_id).first()
    if node is None:
        return False, "NODE_UNKNOWN", None
    if node.status != "ACTIVE":
        return False, "NODE_SUSPENDED", node
    try:
        ts = int(timestamp)
    except ValueError:
        return False, "CLOCK_SKEW", node
    if abs(time.time() - ts) > 300:
        return False, "CLOCK_SKEW", node
    try:
        nonce_uuid = uuid.UUID(nonce)
    except ValueError:
        return False, "REPLAY", node
    if SyncNonce.objects.filter(nonce=nonce_uuid).exists():
        return False, "REPLAY", node
    digest = hashlib.sha256(body).hexdigest()
    message = f"{request.method}\n{request.path}\n{timestamp}\n{nonce}\n{digest}"
    expected = hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, signature):
        return False, "BAD_SIGNATURE", node
    SyncNonce.objects.create(node=node, nonce=nonce_uuid)
    node.last_seen_at = timezone.now()
    node.save(update_fields=["last_seen_at"])
    return True, "OK", node


# --- Application côté central ---
@transaction.atomic
def ingest_event(event: dict, node: Node) -> dict:
    op_id = event.get("op_id")
    if not op_id:
        return {"op_id": None, "status": "REJECTED", "reason": "MISSING_OP_ID"}
    try:
        op_uuid = uuid.UUID(str(op_id))
    except ValueError:
        return {"op_id": str(op_id), "status": "REJECTED", "reason": "INVALID_OP_ID"}
    if InboxEvent.objects.filter(op_id=op_uuid).exists():
        return {"op_id": str(op_uuid), "status": "DUPLICATE"}
    agency_id = event.get("agency_id")
    if node.agency_id and str(node.agency_id) != str(agency_id):
        return {"op_id": str(op_uuid), "status": "REJECTED", "reason": "OUT_OF_SCOPE"}
    entity_type = event.get("entity_type", "")
    entity_id = event.get("entity_id")
    version = int(event.get("version") or 1)
    payload_hash = hashlib.sha256(canonical(event.get("payload", {})).encode()).hexdigest()
    conflict = None
    previous = SyncChange.objects.filter(entity_type=entity_type, entity_id=entity_id).order_by("-seq").first()
    if previous and previous.version > int(event.get("base_version") or 0) and str(previous.origin_node) != str(node.node_id):
        conflict = SyncConflict.objects.create(
            entity_type=entity_type, entity_id=entity_id, agency_id=agency_id, node=node,
            conflict_type="FIELD_LEVEL_MERGE", local_version=previous.version,
            remote_version=version, details={"remote_payload": event.get("payload", {})},
            op_id=op_uuid,
        )
    inbox = InboxEvent.objects.create(
        op_id=op_uuid, node=node, status="CONFLICT" if conflict else "APPLIED",
        applied_at=timezone.now() if not conflict else None,
        payload_hash=payload_hash, payload=event.get("payload", {}),
        error="Conflit de version" if conflict else "",
    )
    if not conflict:
        SyncChange.objects.create(
            entity_type=entity_type, entity_id=entity_id, agency_id=agency_id,
            version=version, change_type=event.get("op_type", "UPDATE"),
            deleted=event.get("op_type") == "DELETE",
            snapshot=event.get("payload", {}), origin_node=node.node_id,
        )
    node.last_push_at = timezone.now()
    node.save(update_fields=["last_push_at"])
    return {"op_id": str(op_uuid), "status": "CONFLICT" if conflict else "APPLIED",
            "conflict_id": str(conflict.id) if conflict else None}


@transaction.atomic
def push_batch(node: Node, events: list[dict]) -> dict:
    results = []
    for event in sorted(events, key=lambda e: int(e.get("local_seq") or 0)):
        try:
            results.append(ingest_event(event, node))
        except Exception as exc:  # un événement ne doit pas annuler le lot
            results.append({"op_id": event.get("op_id"), "status": "REJECTED", "reason": str(exc)[:160]})
    SyncRun.objects.create(node=node, direction="PUSH", finished_at=timezone.now(),
                           received=len(events), applied=sum(1 for r in results if r["status"] == "APPLIED"),
                           conflicts=sum(1 for r in results if r["status"] == "CONFLICT"),
                           errors=sum(1 for r in results if r["status"] == "REJECTED"), status="DONE")
    return {"results": results}


# --- Client ---
def _url(path: str) -> str:
    base = settings.CENTRAL_SYNC_URL.rstrip("/")
    return f"{base}{path}"


def push_to_central(limit: int = 200, timeout: int = 15) -> dict:
    node = get_local_node()
    events = list(pending_events(limit=limit))
    if not events:
        return {"pushed": 0, "results": []}
    payload = {"protocol": PROTOCOL, "node_id": str(node.node_id), "batch_id": str(uuid.uuid4()),
               "sent_at": timezone.now().isoformat(),
               "events": [_serialize_outbox(e) for e in events]}
    body = canonical(payload).encode()
    # Le chemin signé doit être exactement celui que le central vérifie (request.path).
    from django.urls import reverse
    push_path = reverse("sync:api_push")
    headers = sign_headers("POST", push_path, body, secret=settings.SYNC_HMAC_KEY, node=node)
    run = SyncRun.objects.create(node=node, direction="PUSH")
    try:
        request = urllib.request.Request(_url(push_path), data=body, headers=headers, method="POST")
        with urllib.request.urlopen(request, timeout=timeout) as response:
            data = json.loads(response.read().decode())
    except (urllib.error.URLError, TimeoutError, OSError, ValueError) as exc:
        run.status = "FAILED"
        run.message = str(exc)[:255]
        run.finished_at = timezone.now()
        run.save()
        for event in events:
            event.attempts += 1
            event.status = "FAILED" if event.attempts < 10 else "DEAD"
            event.next_attempt_at = timezone.now() + timedelta(seconds=min(300, 2 ** event.attempts))
            event.last_error = str(exc)[:255]
            event.save(update_fields=["attempts", "status", "next_attempt_at", "last_error"])
        return {"pushed": 0, "results": [], "error": str(exc)}
    status_by_op = {r["op_id"]: r for r in data.get("results", [])}
    for event in events:
        result = status_by_op.get(str(event.op_id), {})
        status = result.get("status")
        if status in {"APPLIED", "DUPLICATE", "STALE"}:
            event.status = "ACKED"
            event.last_synced_at = timezone.now() if hasattr(event, "last_synced_at") else None
        elif status == "CONFLICT":
            event.status = "CONFLICT"
        elif status == "DEFERRED":
            event.status = "DEFERRED"
            event.attempts += 1
            event.next_attempt_at = timezone.now() + timedelta(seconds=min(300, 2 ** event.attempts))
        else:
            event.status = "DEAD"
            event.last_error = str(result.get("reason", ""))[:255]
        event.save()
    run.sent = len(events)
    run.applied = sum(1 for e in events if e.status == "ACKED")
    run.conflicts = sum(1 for e in events if e.status == "CONFLICT")
    run.status = "DONE"
    run.finished_at = timezone.now()
    run.save()
    return {"pushed": len(events), "results": data.get("results", [])}


def _serialize_outbox(event: OutboxEvent) -> dict:
    return {
        "op_id": str(event.op_id), "op_type": event.op_type, "entity_type": event.entity_type,
        "entity_id": str(event.entity_id), "agency_id": str(event.agency_id) if event.agency_id else None,
        "node_id": str(event.node.node_id), "version": event.version,
        "base_version": event.base_version, "local_seq": event.local_seq,
        "occurred_at": event.occurred_at.isoformat(), "payload": event.payload,
        "prev_hash": event.prev_hash, "hash": event.hash,
    }


def pull_changes(limit: int = 200) -> dict:
    node = get_local_node()
    cursor, _ = SyncCursor.objects.get_or_create(node=node, stream="entity")
    qs = SyncChange.objects.filter(seq__gt=cursor.last_seq)
    if node.agency_id:
        qs = qs.filter(agency_id=node.agency_id)
    changes = list(qs.order_by("seq")[:limit])
    if changes:
        cursor.last_seq = changes[-1].seq
        cursor.save(update_fields=["last_seq"])
        node.last_pull_at = timezone.now()
        node.save(update_fields=["last_pull_at"])
        SyncRun.objects.create(node=node, direction="PULL", finished_at=timezone.now(),
                               received=len(changes), applied=len(changes), status="DONE")
    return {"pulled": len(changes), "next_cursor": cursor.last_seq,
            "changes": [{"seq": c.seq, "entity_type": c.entity_type, "entity_id": str(c.entity_id),
                         "version": c.version, "change_type": c.change_type,
                         "snapshot": c.snapshot} for c in changes]}


def outbox_stats(agency_id=None) -> dict:
    qs = OutboxEvent.objects.all()
    if agency_id:
        qs = qs.filter(agency_id=agency_id)
    return {
        "pending": qs.filter(status__in=["PENDING", "FAILED", "DEFERRED"]).count(),
        "acked": qs.filter(status="ACKED").count(),
        "conflict": qs.filter(status="CONFLICT").count(),
        "dead": qs.filter(status="DEAD").count(),
    }
