"""One declarative timing edit per selected clip, with immutable source bytes."""
from __future__ import annotations

import hashlib
import json
import os
import shutil
from sync_evidence import file_hash

VERSION = 1


def edit_id(value):
    return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':')).encode()).hexdigest()


def source_problem(edit):
    source = edit.get('source') or {}
    if not source.get('sha256') or file_hash(source.get('path')) != source['sha256']:
        return 'immutable original is missing or changed'
    origin = source.get('originPath')
    if origin and os.path.exists(origin) and file_hash(origin) != source['sha256']:
        return 'original take changed; rebuild the selection and transcribe the new take'
    return None


def capture_source(path, window, root, duration):
    digest = file_hash(path)
    if not digest:
        raise ValueError('original take cannot be read')
    folder = os.path.join(root, '.sources')
    os.makedirs(folder, exist_ok=True)
    dest = os.path.join(folder, digest + os.path.splitext(path)[1])
    if file_hash(dest) != digest:
        temporary = dest + '.tmp'
        shutil.copyfile(path, temporary)
        os.replace(temporary, dest)
    return {'version': VERSION, 'source': {'originPath': os.path.abspath(path),
            'path': os.path.abspath(dest), 'sha256': digest, 'durationSec': duration,
            'headSec': float(window.get('headSec') or 0), 'tailSec': float(window.get('tailSec') or 0)}}


def output_current(operation):
    return bool(operation and operation.get('outputSha256')
                and file_hash(operation.get('path')) == operation['outputSha256'])


def apply_window(window, operation):
    for key in ('headSec', 'tailSec', 'realEndSec', 'syntheticSpans'):
        if key in operation:
            window[key] = operation[key]


def persist(path, document):
    temporary = path + '.tmp'
    with open(temporary, 'w', encoding='utf-8') as stream:
        json.dump(document, stream, indent=1)
    os.replace(temporary, path)


def selected_transcript(selection, perf, store, window):
    """Resolve by content, then carry word onsets/ends through the verified edit."""
    record = next((c for c in selection.get('clips', []) if c.get('id') == perf), None)
    entries = store.get('clips') or {}
    if record is None:
        return entries.get(perf)  # legacy hand-built test/audit selection, no media binding
    current_hash = file_hash(record.get('path'))
    direct = next((entry for entry in entries.values()
                   if current_hash and entry.get('sourceSha256') == current_hash), None)
    rate, inset, pad = 1.0, float(window.get('headSec') or 0), 0.0
    if direct is None:
        edit = record.get('timingEdit') or {}
        shifted = edit.get('shift') or {}
        if ((store.get("song") or {}).get("sourceSha256")
                and shifted.get("request", {}).get("songSha256") != store["song"]["sourceSha256"]):
            return None
        if not shifted.get('verified') or record.get('path') != shifted.get('path') \
                or not output_current(shifted) or source_problem(edit):
            return None
        direct = next((entry for entry in entries.values()
                       if entry.get('sourceSha256') == edit['source']['sha256']), None)
        if direct is None:
            return None
        rate = float((edit.get('rate') or {}).get('rate', 1.0))
        inset, pad = shifted.get('inSec', 0), shifted.get('padHeadSec', 0)
    words = []
    duration = float(record.get('durationSec') or (float(window['end']) - float(window['start'])))
    for item in direct.get('words') or []:
        result = dict(item)
        for key in ('t', 'e', 'end', 'endSec'):
            if isinstance(result.get(key), (int, float)):
                result[key] = result[key] / rate - inset + pad
        if 0 <= result.get('t', -1) < duration:
            words.append(result)
    return {**direct, 'words': words, 'text': direct.get('text') or ' '.join(w['w'] for w in words)}


def video_seconds(path):
    """Video coverage, independently of a longer audio/container duration."""
    import subprocess
    from fractions import Fraction
    from sync_evidence import number
    result = subprocess.run(['ffprobe', '-v', 'error', '-select_streams', 'v:0',
        '-show_entries', 'stream=duration,nb_frames,avg_frame_rate', '-of', 'json', path], capture_output=True, text=True)
    try:
        stream = json.loads(result.stdout)['streams'][0]
        fps = float(Fraction(stream.get('avg_frame_rate') or '0'))
        seconds = number(stream.get('duration'))
        if seconds is None and fps > 0 and number(stream.get('nb_frames')) is not None:
            seconds = float(stream['nb_frames']) / fps
        return seconds, (1.0 / fps if fps > 0 else 0.0)
    except (ValueError, KeyError, IndexError, ZeroDivisionError):
        return None, 0.0


def restore_previous(record, window, edit):
    """Roll back the whole provisional transaction, including its transcript map."""
    import copy
    previous = edit.get('previousSelection')
    if not previous or (edit.get('rate') or {}).get('verified'):
        return False
    if file_hash(previous.get('path')) == previous.get('sha256'):
        record['path'] = previous['path']
        if previous.get('durationSec') is not None:
            record['durationSec'] = previous['durationSec']
        for name, value in previous.get('window', {}).items():
            if value is None:
                window.pop(name, None)
            else:
                window[name] = value
        if previous.get('timingEdit'):
            record['timingEdit'] = copy.deepcopy(previous['timingEdit'])
        else:
            record.pop('timingEdit', None)
    elif file_hash(edit['source'].get('path')) == edit['source'].get('sha256'):
        # The original filename may have been overwritten since the request. The
        # preserved bytes remain a safe fallback; the report still requires review.
        record.update(path=edit['source']['path'], durationSec=edit['source']['durationSec'])
        record.pop('timingEdit', None)
        apply_window(window, {**edit['source'], 'realEndSec': edit['source']['durationSec'], 'syntheticSpans': []})
    else:
        return False
    record['rejectedTimingEdit'] = edit
    return True
