#!/usr/bin/env python3
"""Local, duration-preserving MP3 guides from an existing isolated vocal."""
import argparse
import hashlib
import json
import math
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile

SAMPLE_RATE = 44100
RECIPE_VERSION = 1


class GuideError(Exception):
    def __init__(self, code, message):
        super().__init__(message)
        self.code = code


def run(command):
    try:
        result = subprocess.run(command, capture_output=True, check=False)
    except OSError as exc:
        raise GuideError('env_var_missing', f'Cannot run {command[0]}: {exc}') from exc
    if result.returncode:
        raise GuideError('ffmpeg_failed', result.stderr.decode(errors='replace')[-2000:])
    return result.stdout


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


def inputs_for(args):
    if args.input:
        if args.windows:
            raise GuideError('invalid_flag_value', '--windows requires --project')
        source = Path(args.input).expanduser().resolve()
        if not source.is_file():
            raise GuideError('asset_not_found', f'Vocal input not found: {source}')
        return [source]
    project = Path(args.project).expanduser().resolve()
    plan_path = project / 'build/plan.json'
    if not plan_path.is_file():
        raise GuideError('asset_not_found', f'Plan not found: {plan_path}')
    plan = json.loads(plan_path.read_text())
    if plan.get('voiceSource') != 'stem':
        raise GuideError('invalid_flag_value',
                         'Project batch export requires a plan made with VOICE_SOURCE=stem. '
                         'Use --input for a separately prepared vocal stem.')
    selected = set(args.windows.split(',')) if args.windows else None
    sources, found = [], set()
    for job in plan.get('jobs', []):
        name = job.get('id', '')
        if selected is not None and name not in selected:
            continue
        if not job.get('voiceRef') or job.get('synced') is False:
            continue
        if job.get('voiceSource', 'stem') != 'stem':
            raise GuideError('invalid_flag_value', f'{name} uses a mix, not a vocal stem')
        source = Path(job['voiceRef'])
        if not source.is_absolute():
            source = project / source
        elif plan.get('projectDir'):
            # A copied/network project keeps paths from its authoring machine.
            # Relocate only references contained by the explicitly recorded project.
            try:
                relative = source.resolve().relative_to(Path(plan['projectDir']).resolve())
                source = project / relative
            except ValueError:
                pass
        source = source.resolve()
        if not source.is_file():
            raise GuideError('asset_not_found', f'Voice reference missing for {name}: {source}')
        found.add(name)
        if source not in sources:
            sources.append(source)
    if selected and selected - found:
        raise GuideError('invalid_flag_value',
                         f'No stem voice reference for windows: {", ".join(sorted(selected - found))}')
    if not sources:
        raise GuideError('asset_not_found', 'No planned stem voice references to export')
    return sources


def dependencies():
    try:
        import numpy as np
        import parselmouth
        from parselmouth.praat import call
    except ImportError as exc:
        requirements = Path(__file__).with_name('requirements-vocal-guides.txt')
        raise GuideError('env_var_missing',
                         f'Vocal guides need NumPy and praat-parselmouth in {sys.executable}. '
                         f'Install with: "{sys.executable}" -m pip install -r "{requirements}"') from exc
    return np, parselmouth, call


def prepare_export(source, args, versions):
    directory = Path(args.out_dir).expanduser().resolve() if args.out_dir else source.parent
    paths = {name: directory / f'{source.stem}-{name}.mp3'
             for name in ('flat-guide', 'pitch-shift')}
    manifest = directory / f'{source.stem}-vocal-guides.json'
    recipe = {'version': RECIPE_VERSION, 'sourceSha256': digest(source),
              'flatHz': args.flat_hz, 'semitones': args.semitones,
              'sampleRate': SAMPLE_RATE, 'bitrate': '320k', **versions}
    previous = None
    if manifest.exists():
        try:
            previous = json.loads(manifest.read_text())
        except (ValueError, OSError):
            pass
    owned = previous.get('outputs', {}) if isinstance(previous, dict) else {}
    intact = True
    for name, path in paths.items():
        recorded = owned.get(name, {})
        matches = (path.is_file() and recorded.get('sha256') == digest(path))
        intact = intact and matches
        if path.exists() and not matches and not args.force:
            raise GuideError('invalid_flag_value',
                             f'Refusing to overwrite untracked or modified export: {path}. '
                             'Choose --out-dir or use --force to replace it.')
    if intact and previous.get('recipe') == recipe and not args.force:
        return {'source': str(source), 'manifest': str(manifest), 'cached': True,
                'outputs': owned}, None
    return None, (directory, paths, manifest, recipe)


def export(source, args, prepared, modules):
    np, parselmouth, call = modules
    directory, paths, manifest, recipe = prepared
    directory.mkdir(parents=True, exist_ok=True)
    media = json.loads(run([args.ffprobe, '-v', 'error', '-show_entries',
                           'format=duration:stream=codec_type,duration', '-of', 'json', str(source)]))
    duration = None
    if any(s.get('codec_type') == 'video' for s in media.get('streams', [])):
        duration = float(media.get('format', {}).get('duration', 'nan'))
        if not math.isfinite(duration) or duration <= 0:
            raise GuideError('invalid_audio_format', f'Cannot determine clip duration: {source}')
    # Analyse and encode locally; repeatedly reading WAV scratch files over an
    # SMB share is much slower. Only finished exports are staged beside targets.
    with tempfile.TemporaryDirectory(prefix='vocal-guides-') as scratch:
        tmp = Path(scratch)
        wav = tmp / 'source.wav'
        command = [args.ffmpeg, '-v', 'error', '-i', str(source), '-map', '0:a:0',
                   '-ac', '1', '-ar', str(SAMPLE_RATE)]
        if duration is not None:
            command += ['-af', 'apad', '-t', str(duration)]
        run(command + ['-c:a', 'pcm_s16le', str(wav)])
        sound = parselmouth.Sound(str(wav))
        count = sound.values.shape[1]
        if count == 0:
            raise GuideError('invalid_audio_format', 'The input has no audio samples')
        has_voice = False
        if sound.duration >= .06:
            source_pitch = sound.to_pitch_ac(time_step=.005, pitch_floor=65, pitch_ceiling=600)
            has_voice = bool(np.any(source_pitch.selected_array['frequency'] > 0))
        outputs = {}
        for name, destination in paths.items():
            if has_voice:
                manipulation = call(sound, 'To Manipulation', .005, 65, 600)
                tier = call(manipulation, 'Extract pitch tier')
                if name == 'flat-guide':
                    call(tier, 'Remove points between', sound.xmin, sound.xmax)
                    call(tier, 'Add point', sound.xmin + sound.duration / 2, args.flat_hz)
                else:
                    call(tier, 'Multiply frequencies', sound.xmin, sound.xmax, 2 ** (args.semitones / 12))
                call([tier, manipulation], 'Replace pitch tier')
                changed = call(manipulation, 'Get resynthesis (overlap-add)')
            else:
                changed = sound.copy()
            if changed.values.shape[1] != count:
                raise GuideError('audio_sync_drift', 'Pitch processing changed the sample count')
            peak = float(np.max(np.abs(changed.values)))
            changed.values[:] *= min(1., .94 / max(peak, 1e-12))
            master = tmp / f'{name}.wav'
            encoded = tmp / destination.name
            changed.save(str(master), 'WAV')
            run([args.ffmpeg, '-v', 'error', '-i', str(master), '-c:a', 'libmp3lame',
                 '-b:a', '320k', str(encoded)])
            decoded = run([args.ffmpeg, '-v', 'error', '-i', str(encoded), '-ac', '1',
                           '-ar', str(SAMPLE_RATE), '-f', 's16le', '-'])
            if len(decoded) // 2 != count:
                raise GuideError('audio_sync_drift', 'MP3 decoding changed the audio duration')
            outputs[name] = {'path': str(destination), 'sha256': digest(encoded),
                             'durationSec': count / SAMPLE_RATE, 'samples': count}
        report = {'schemaVersion': 1, 'source': str(source), 'recipe': recipe,
                  'method': 'Praat overlap-add, unchanged duration tier',
                  'voicedPitchDetected': has_voice, 'outputs': outputs,
                  'lipSyncVerified': False}
        (tmp / 'manifest.json').write_text(json.dumps(report, indent=2) + '\n')
        if digest(source) != recipe['sourceSha256']:
            raise GuideError('invalid_flag_value', 'Source changed during export; rerun against a stable input')
        with tempfile.TemporaryDirectory(prefix='.vocal-guides-', dir=directory) as staging:
            staged = Path(staging)
            for destination in paths.values():
                shutil.copyfile(tmp / destination.name, staged / destination.name)
            shutil.copyfile(tmp / 'manifest.json', staged / 'manifest.json')
            for destination in paths.values():
                os.replace(staged / destination.name, destination)
            os.replace(staged / 'manifest.json', manifest)
    return {'source': str(source), 'manifest': str(manifest), 'cached': False,
            'voicedPitchDetected': has_voice, 'outputs': outputs}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--input', help='Existing vocal audio or voice-reference video')
    group.add_argument('--project', help='Project directory with a stem-based build/plan.json')
    parser.add_argument('--windows', help='Comma-separated plan window IDs; defaults to all voiced windows')
    parser.add_argument('--out-dir', help='Default: beside each input voice reference')
    parser.add_argument('--flat-hz', type=float, default=150)
    parser.add_argument('--semitones', type=float, default=4)
    parser.add_argument('--force', action='store_true', help='Replace existing or edited guide exports')
    parser.add_argument('--ffmpeg', default='ffmpeg')
    parser.add_argument('--ffprobe', default='ffprobe')
    args = parser.parse_args()
    try:
        if not math.isfinite(args.flat_hz) or not 65 <= args.flat_hz <= 600:
            raise GuideError('invalid_flag_value', '--flat-hz must be between 65 and 600')
        if not math.isfinite(args.semitones) or not -12 <= args.semitones <= 12:
            raise GuideError('invalid_flag_value', '--semitones must be between -12 and 12')
        if args.windows and not re.fullmatch(r'w\d+(,w\d+)*', args.windows):
            raise GuideError('invalid_flag_value', '--windows must contain IDs such as w00,w01')
        sources = inputs_for(args)
        modules = dependencies()
        versions = {'parselmouth': modules[1].__version__, 'numpy': modules[0].__version__,
                    'ffmpeg': run([args.ffmpeg, '-version']).decode().splitlines()[0]}
        # Check every destination before processing so a batch cannot clobber another input.
        keys = [(str(Path(args.out_dir).resolve() if args.out_dir else p.parent), p.stem) for p in sources]
        if len(set(keys)) != len(keys):
            raise GuideError('invalid_flag_value', 'Inputs have colliding output names; use separate directories')
        plans = [prepare_export(source, args, versions) for source in sources]
        for cached, prepared in plans:
            destinations = prepared[1].values() if prepared else [Path(v['path']) for v in cached['outputs'].values()]
            if any(path.resolve() in sources for path in destinations):
                raise GuideError('invalid_flag_value', 'An export would overwrite another input source')
        results = []
        for source, (cached, prepared) in zip(sources, plans):
            print(f'vocal guides: {source.name}', file=sys.stderr)
            results.append(cached or export(source, args, prepared, modules))
        print(json.dumps({'action': 'vocal-guides', 'localOnly': True, 'files': results}))
    except GuideError as exc:
        print(json.dumps({'error': {'code': exc.code, 'message': str(exc)}}))
        return 1 if exc.code in ('invalid_flag_value', 'asset_not_found', 'invalid_audio_format') else 2
    except (OSError, ValueError, RuntimeError) as exc:
        print(json.dumps({'error': {'code': 'adapter_command_failed', 'message': str(exc)}}))
        return 2
    return 0


if __name__ == '__main__':
    sys.exit(main())
