#!/usr/bin/env python3
"""Two-pass H.264 compression below 20 decimal MB, with a 1080p cap and preserved frame timing.
Requires Python 3.10+, FFmpeg and ffprobe on PATH. Compression is lossy.
"""
import argparse
import json
import shutil
import subprocess
import tempfile
from pathlib import Path


LIMIT = 20_000_000


def run(command):
    result = subprocess.run(command, capture_output=True, text=True, errors='replace')
    if result.returncode:
        raise ValueError(result.stderr[-5000:] or 'Command failed')
    return result.stdout


def run_progress(command, frame_count, label):
    """Show FFmpeg's encoded-frame progress without buffering its error pipe."""
    command = command[:1] + ['-progress', 'pipe:1', '-nostats'] + command[1:]
    print(f'{label}:   0.0%', end='', flush=True)
    # A file avoids a stderr pipe deadlock if FFmpeg reports many errors.
    with tempfile.TemporaryFile(mode='w+', encoding='utf-8', errors='replace') as errors:
        with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=errors,
                              text=True, errors='replace') as process:
            try:
                for line in process.stdout:
                    key, _, value = line.strip().partition('=')
                    if key == 'frame':
                        percent = min(99.9, max(0.0, int(value) * 100 / frame_count))
                        print(f'\r{label}: {percent:5.1f}%', end='', flush=True)
                code = process.wait()
            except BaseException:
                process.kill()
                process.wait()
                print(flush=True)
                raise
        if code:
            print(flush=True)
            errors.seek(0)
            raise ValueError(errors.read()[-5000:] or 'Command failed')
    print(f'\r{label}: 100.0%', flush=True)


def probe(path):
    # Metadata does not require decoding the entire video.
    return json.loads(run(['ffprobe', '-v', 'error', '-show_streams',
                          '-show_format', '-of', 'json', str(path)]))


def timestamps(path, stream_index):
    # This scan supplies both timing and frame count, avoiding a separate decode.
    raw = run(['ffprobe', '-v', 'error', '-select_streams', str(stream_index),
               '-show_entries', 'frame=best_effort_timestamp_time',
               '-of', 'json', str(path)])
    values = [float(f['best_effort_timestamp_time'])
              for f in json.loads(raw).get('frames', [])]
    return [x - values[0] for x in values] if values else []


def color_plan(video):
    transfer = video.get('color_transfer')
    primaries = video.get('color_primaries')
    hdr = transfer in ('smpte2084', 'arib-std-b67')
    wide = primaries == 'bt2020'
    if not hdr and not wide:
        return ('format=yuv420p' if video.get('pix_fmt') not in ('yuv420p', 'yuvj420p') else ''), []
    tin = transfer if hdr else {'bt2020-10': '14', 'bt2020-12': '15'}.get(transfer, 'bt709')
    pin = 'bt709' if primaries == 'bt709' else 'bt2020'
    matrix = 'bt709' if video.get('color_space') == 'bt709' else 'bt2020nc'
    rng = 'full' if video.get('color_range') == 'pc' else 'limited'
    incoming = f'pin={pin}:tin={tin}:min={matrix}:rin={rng}'
    if hdr:
        vf = f'zscale={incoming}:t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=2,zscale=t=bt709:m=bt709:r=limited:dither=error_diffusion,format=yuv420p'
    else:
        vf = f'zscale={incoming}:p=bt709:t=bt709:m=bt709:r=limited:dither=error_diffusion,format=yuv420p'
    vf += ',sidedata=mode=delete:type=MASTERING_DISPLAY_METADATA,sidedata=mode=delete:type=CONTENT_LIGHT_LEVEL'
    return vf, ['-color_primaries', 'bt709', '-color_trc', 'bt709', '-colorspace', 'bt709', '-color_range', 'tv']


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument('input', nargs='?', type=Path)
    ap.add_argument('output', nargs='?', type=Path)
    ap.add_argument('--preset', choices=['ultrafast', 'superfast', 'veryfast', 'faster', 'fast', 'medium', 'slow', 'slower', 'veryslow'], default='veryfast',
                    help='x264 speed/quality tradeoff (default: veryfast; slow gives better quality per byte)')
    args = ap.parse_args()
    for tool in ('ffmpeg', 'ffprobe'):
        if not shutil.which(tool):
            ap.error(f'{tool} must be installed and on PATH')
    entered = args.input or Path(input('Drag your video here, then press Enter: ').strip().strip('"'))
    source = entered.expanduser().resolve()
    dest = (args.output or source.with_name(source.stem + '_anti_lag.mp4')).expanduser().resolve()
    report_path = dest.with_suffix('.compression.json')
    if not source.is_file() or source == dest or dest.exists() or report_path.exists() or dest.suffix.lower() != '.mp4':
        ap.error('Use an existing input and a NEW .mp4 output filename')
    if not dest.parent.is_dir():
        ap.error('Output folder does not exist')
    before = probe(source)
    videos = [v for v in before['streams'] if v['codec_type'] == 'video' and not v.get('disposition', {}).get('attached_pic')]
    if len(videos) != 1:
        ap.error('Requires exactly one ordinary video stream')
    video = videos[0]
    audio = next((s for s in before['streams'] if s['codec_type'] == 'audio'), None)
    color_filter, color_flags = color_plan(video)
    scale = min(1, 1920 / max(video['width'], video['height']), 1080 / min(video['width'], video['height']))
    width, height = max(2, int(video['width'] * scale / 2) * 2), max(2, int(video['height'] * scale / 2) * 2)
    filters = ([f'scale={width}:{height}:flags=lanczos'] if (width, height) != (video['width'], video['height']) else []) + ([color_filter] if color_filter else [])
    if 'zscale' in color_filter:
        available = run(['ffmpeg', '-hide_banner', '-filters'])
        if 'zscale' not in available or 'tonemap' not in available:
            ap.error('HDR conversion needs FFmpeg with zscale/libzimg and tonemap.')
    duration = max(float(s.get('duration') or before['format']['duration']) for s in [video] + ([audio] if audio else []))
    if not 0 < duration < float('inf'):
        ap.error('Input has no valid finite duration')
    first = timestamps(source, video['index'])
    frame_count = len(first)
    if frame_count <= 0:
        ap.error('Could not count source frames; use an original decodable export')
    # Reserve container overhead and encoding variation; allocate the rest to pictures/audio.
    audio_rate = 128_000 if audio else 0
    video_rate = int(19_000_000 * 8 / duration) - audio_rate
    if video_rate < 50_000:
        ap.error('Video is too long for this 20 MB profile; split or trim it first')
    print(f'{duration:.2f} seconds, {video["width"]}x{video["height"]}, source FPS {video["avg_frame_rate"]}.', flush=True)
    print('Two-pass lossy encoding; resolution, timestamps and frame count will be checked.', flush=True)
    with tempfile.TemporaryDirectory(prefix='under20mb-', dir=dest.parent) as folder:
        temp = Path(folder)
        target = temp / 'encoded.mp4'
        for attempt in range(3):
            log = temp / f'pass-{attempt}'
            common = ['ffmpeg', '-hide_banner', '-v', 'error', '-nostdin', '-y', '-noautorotate', '-i', str(source),
                      '-map', f'0:{video["index"]}', '-c:v', 'libx264', '-preset', args.preset,
                      '-b:v', str(video_rate), '-pix_fmt', 'yuv420p', '-fps_mode', 'passthrough',
                      '-enc_time_base', str(video.get('time_base') or '0').replace('/', ':'),
                      '-passlogfile', str(log)] + (['-vf', ','.join(filters)] if filters else []) + color_flags
            run_progress(common + ['-pass', '1', '-an', '-f', 'null', '-'],
                         frame_count, f'Attempt {attempt + 1}, pass 1/2')
            audio_args = ['-map', f'0:{audio["index"]}', '-c:a', 'aac', '-b:a', str(audio_rate)] if audio else ['-an']
            run_progress(common + ['-pass', '2'] + audio_args + ['-map_metadata', '0', '-map_chapters', '-1', '-movflags', '+faststart', str(target)],
                         frame_count, f'Attempt {attempt + 1}, pass 2/2')
            if target.stat().st_size < LIMIT:
                break
            video_rate = int(video_rate * (18_500_000 / target.stat().st_size) * 0.95)
            print('Reducing bitrate to meet the size limit...', flush=True)
        else:
            raise ValueError('Could not meet size limit; no final output saved')
        print('Verifying frame timing and decoding...', flush=True)
        after = probe(target)
        result_video = next(s for s in after['streams'] if s['codec_type'] == 'video')
        if bool(audio) != any(x['codec_type'] == 'audio' for x in after['streams']):
            raise ValueError('Output audio is missing')
        second = timestamps(target, result_video['index'])
        if (result_video['width'], result_video['height'], len(second)) != (width, height, frame_count):
            raise ValueError('Resolution/frame count changed; no final output saved')
        # Compare every display timestamp relative to the first; a constant mux offset is harmless.
        if len(first) != len(second) or any(abs(a-b) > 0.001 for a,b in zip(first, second)):
            raise ValueError('Frame timing changed by more than 1 ms; no final output saved')
        run(['ffmpeg', '-v', 'error', '-xerror', '-nostdin', '-i', str(target), '-map', '0:v:0', '-map', '0:a?', '-f', 'null', '-'])
        report = {'source': str(source), 'output': str(dest), 'size_bytes': target.stat().st_size,
                  'limit_bytes_exclusive': LIMIT, 'resolution_preserved': (width, height) == (video['width'], video['height']), 'frame_count': frame_count,
                  'frame_timing_verified_tolerance_ms': 1, 'strict_decode_passed': True,
                  'video_bitrate_target': video_rate, 'encoder_preset': args.preset, 'source_probe': before, 'output_probe': after,
                  'lossless': False, 'note': 'Preserves source frame cadence; does not guarantee full visual quality. First video/audio only.'}
        with dest.open('xb') as handle, target.open('rb') as encoded:
            try:
                shutil.copyfileobj(encoded, handle)
            except BaseException:
                handle.close()
                dest.unlink(missing_ok=True)
                raise
        with report_path.open('x', encoding='utf-8') as handle:
            json.dump(report, handle, indent=2)
    print(f'Saved: {dest} ({report["size_bytes"]/1_000_000:.2f} MB)\nReport: {report_path}')


if __name__ == '__main__':
    try:
        main()
    except (OSError, ValueError, KeyError) as exc:
        raise SystemExit(f'Compression failed: {exc}')
