"""Content-bound timing evidence shared by the repair and review helpers."""
from __future__ import annotations

import hashlib
import math
import os


def file_hash(path):
    try:
        digest = hashlib.sha256()
        with open(path, 'rb') as stream:
            for chunk in iter(lambda: stream.read(1024 * 1024), b''):
                digest.update(chunk)
        return digest.hexdigest()
    except (OSError, TypeError):
        return None


def number(value):
    if isinstance(value, bool):
        return None
    try:
        value = float(value)
        return value if math.isfinite(value) else None
    except (ValueError, TypeError):
        return None


def evidence(clip, song, start, end, head_sec=0.0):
    return {'version': 1, 'clipPath': os.path.abspath(clip), 'clipSha256': file_hash(clip),
            'songPath': os.path.abspath(song), 'songSha256': file_hash(song),
            'startSec': float(start), 'endSec': float(end), 'headSec': float(head_sec)}


def is_current(row, clip, start, end, song=None, head_sec=0.0):
    """A matching filename or passing label alone cannot retire an old failure."""
    item = (row or {}).get('evidence') or {}
    if item.get('version') != 1 or not clip:
        return False
    for key, expected in (('startSec', start), ('endSec', end)):
        actual = number(item.get(key))
        if actual is None or abs(actual - expected) > 0.001:
            return False
    if number(item.get('headSec', 0.0)) != float(head_sec):
        return False
    clip_hash, song_hash = item.get('clipSha256'), item.get('songSha256')
    return bool(clip_hash and song_hash and file_hash(clip) == clip_hash
                and file_hash(song or item.get('songPath')) == song_hash)
