#!/usr/bin/env python3
"""Measure take note endings before vocal-swap fitting; no provider or paid calls.

Usage: clip_ends.py --store artifacts/clip-transcripts.json --cache build/vocal-swap-demucs
                   --python <singer-diarize-venv>/bin/python [--cached-only]
Reuses full-content-bound separated vocals, or runs installed local Demucs. Missing
separation or an unobserved final decay leaves the take unmeasured for verification.
"""
from __future__ import annotations
import argparse
import json
import os
from clip_vocals import separated_vocal, fixture_vocal
from sync_evidence import file_hash
from transcribe_clips import measured_ends
from timing_edits import edit_id, persist


def measure_entry(entry, cache, python, cached_only=False):
    media = entry.get('path')
    digest = file_hash(media)
    if not digest or entry.get('sourceSha256') != digest:
        return {'status': 'verify', 'why': 'refresh the stale or unbound clip transcript'}
    vocal = separated_vocal(python, media, cache, cached_only=cached_only)
    if not vocal:
        for word in entry.get('words', []):
            if word.get('eFrom') == 'stem':
                word['e'], word['eFrom'] = word.get('whisperE', word['t']), 'whisper'
        row = {'status': 'verify', 'why': 'local separated vocal unavailable; install the singer-diarize runtime or supply a current cache, then rerun clip_ends.py'}
        entry['ends'] = row
        return row
    key = {'sourceSha256': digest, 'vocalSha256': file_hash(vocal),
           'onsetsSha256': edit_id([[w.get('t'), w.get('w')] for w in entry.get('words', [])]), 'method': 'rms-observed-decay-v1'}
    prior = entry.get('ends') or {}
    if all(prior.get(k) == v for k, v in key.items()):
        return {**prior, 'cached': True}
    # Remove only old automatic stem measurements; a changed separation must not
    # inherit its predecessor's measured label when this pass cannot observe an end.
    words = []
    for word in entry.get('words', []):
        word = dict(word)
        if word.get('eFrom') == 'stem':
            word['e'], word['eFrom'] = word.get('whisperE', word['t']), 'whisper'
        words.append(word)
    words = measured_ends(words, vocal, require_observed_end=True)
    entry['words'] = words
    ready = bool(words and words[-1].get('eFrom') in ('stem', 'manual', 'measured', 'gemini'))
    row = {**key, 'status': 'measured' if ready else 'verify', 'vocalPath': vocal,
           'componentKind': 'synthetic-fixture' if fixture_vocal(media) else 'demucs',
           'why': 'final note decay measured' if ready else 'final note decay was not observable; review the take ending'}
    entry['ends'] = row
    return row


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument('--store', required=True)
    ap.add_argument('--cache', required=True)
    ap.add_argument('--python', default='')
    ap.add_argument('--cached-only', action='store_true')
    ap.add_argument('--json', default='')
    a = ap.parse_args()
    store = json.load(open(a.store, encoding='utf-8'))
    rows = []
    for cid, entry in (store.get('clips') or {}).items():
        if not entry.get('words'):
            continue
        row = measure_entry(entry, a.cache, a.python, a.cached_only)
        rows.append({'clip': cid, **row})
        print(f"clip_ends: {cid}: {row['status']} — {row.get('why', '')}")
    persist(a.store, store)
    if a.json:
        persist(a.json, {'windows': rows})
    return 0


if __name__ == '__main__':
    raise SystemExit(main())
