"""Exact-content grouping across capture sessions and copied sensor files."""

from __future__ import annotations

from collections import defaultdict
from dataclasses import replace
import hashlib
import json
import os
from pathlib import Path


def _digest(path):
    sha = hashlib.sha256()
    with Path(path).open("rb") as source:
        for chunk in iter(lambda: source.read(4 * 1024 * 1024), b""):
            sha.update(chunk)
    return sha.hexdigest()


def hash_sensor_files(records, cache_path):
    """Hash canonical PCD or raster sources once and persist a resumable index."""
    cache_path = Path(cache_path)
    cache = json.loads(cache_path.read_text()) if cache_path.exists() else {}
    changed = 0
    for record in records:
        path = record.paths.get("pcd") or record.paths.get("depth") or record.paths.get("intensity")
        if path is None:
            continue
        path = Path(path)
        key = str(path)
        stat = path.stat()
        previous = cache.get(key)
        if previous and previous["size"] == stat.st_size and previous["mtime_ns"] == stat.st_mtime_ns:
            continue
        cache[key] = {"size": stat.st_size, "mtime_ns": stat.st_mtime_ns,
                      "sha256": _digest(path), "frame_id": record.frame_id}
        changed += 1
        if changed % 100 == 0:
            _save_index(cache_path, cache)
    _save_index(cache_path, cache)
    return cache


def _save_index(path, cache):
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(path.name + ".tmp")
    temporary.write_text(json.dumps(cache, sort_keys=True))
    os.replace(temporary, path)


def unify_duplicate_groups(records, file_index):
    """Give byte-identical captures the same group, including across dates."""
    parent = {record.group_id: record.group_id for record in records}

    def find(group):
        while parent[group] != group:
            parent[group] = parent[parent[group]]
            group = parent[group]
        return group

    def union(a, b):
        a, b = find(a), find(b)
        if a != b:
            parent[max(a, b)] = min(a, b)

    seen = {}
    for record in records:
        path = record.paths.get("pcd") or record.paths.get("depth") or record.paths.get("intensity")
        item = file_index.get(str(path)) if path else None
        if not item:
            continue
        digest = item["sha256"]
        if digest in seen:
            union(record.group_id, seen[digest])
        else:
            seen[digest] = record.group_id
    return [replace(record, group_id=find(record.group_id)) for record in records]
