#!/usr/bin/env python3
"""Compare a finished export or downloaded upload with its approved master.

This is a technical integrity check, not visual review or publication approval.
"""
from __future__ import annotations

import argparse
import json
import math
from fractions import Fraction
from pathlib import Path
import subprocess
import sys


def probe(path: str) -> dict:
    result = subprocess.run([
        'ffprobe', '-v', 'error', '-count_frames', '-show_streams',
        '-show_format', '-of', 'json', path,
    ], capture_output=True, text=True, check=True)
    data = json.loads(result.stdout)
    video = next(s for s in data['streams'] if s['codec_type'] == 'video')
    audio = [s for s in data['streams'] if s['codec_type'] == 'audio']
    duration = float(video.get('duration') or data['format']['duration'])
    fps = float(Fraction(video['avg_frame_rate']))
    if not math.isfinite(duration) or duration <= 0 or fps <= 0:
        raise ValueError('Missing or invalid video timing')
    return {
        'path': str(Path(path).resolve()),
        'width': int(video['width']), 'height': int(video['height']),
        'sar': video.get('sample_aspect_ratio', '1:1'),
        'duration': duration, 'fps': fps, 'start': float(video.get('start_time') or 0),
        'frames': int(video['nb_read_frames']),
        'audio': [{'duration': float(s['duration']) if s.get('duration') else None,
                   'channels': s.get('channels'), 'start': float(s.get('start_time') or 0)} for s in audio],
    }


def compare(master: dict, delivered: dict, width: int, height: int) -> list[str]:
    failures = []
    tolerance = max(0.1, 2 / master['fps'])
    if (delivered['width'], delivered['height']) != (width, height):
        failures.append(f'Expected {width}x{height} encoded pixels')
    if delivered['sar'] not in ('1:1', 'N/A'):
        failures.append('Delivery must use square pixels')
    if abs(delivered['duration'] - master['duration']) > tolerance:
        failures.append('Video duration differs from approved master')
    if delivered['frames'] != master['frames']:
        failures.append('Decoded frame count differs from approved master')
    if abs(delivered['fps'] - master['fps']) > 0.001:
        failures.append('Frame rate differs from approved master')
    if len(delivered['audio']) != len(master['audio']):
        failures.append('Audio stream count differs from approved master')
    for original, actual in zip(master['audio'], delivered['audio']):
        original_offset = original.get('start', 0) - master.get('start', 0)
        actual_offset = actual.get('start', 0) - delivered.get('start', 0)
        if abs(actual_offset - original_offset) > 2 / master['fps']:
            failures.append('Audio/video start alignment differs from approved master')
        if actual['channels'] != original['channels']:
            failures.append('Audio channel count differs from approved master')
        if original['duration'] is None or actual['duration'] is None:
            failures.append('Cannot verify audio duration')
        elif abs(original['duration'] - actual['duration']) > tolerance:
            failures.append('Audio duration differs from approved master')
    return failures


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--master', required=True)
    parser.add_argument('--delivery', required=True)
    parser.add_argument('--resolution', required=True, help='Encoded WIDTHxHEIGHT')
    parser.add_argument('--report', required=True)
    args = parser.parse_args()
    if Path(args.report).resolve() in (Path(args.master).resolve(), Path(args.delivery).resolve()):
        parser.error('Report must not overwrite an input video')
    report = {'status': 'fail', 'visualReview': 'not_performed', 'failures': []}
    try:
        width, height = map(int, args.resolution.lower().split('x'))
        if min(width, height) <= 0:
            raise ValueError('Resolution must be positive')
        master, delivered = probe(args.master), probe(args.delivery)
        report.update(master=master, delivery=delivered)
        report['failures'] = compare(master, delivered, width, height)
        # Decode both audio and video: a successful container probe alone is insufficient.
        decoded = subprocess.run([
            'ffmpeg', '-v', 'error', '-xerror', '-i', args.delivery,
            '-map', '0:v:0', '-map', '0:a?', '-f', 'null', '-',
        ], capture_output=True, text=True)
        if decoded.returncode or decoded.stderr.strip():
            report['failures'].append('Full delivery decode failed')
        report['status'] = 'pass' if not report['failures'] else 'fail'
    except (OSError, ValueError, KeyError, StopIteration, subprocess.CalledProcessError) as error:
        report['failures'].append(f'Unable to verify delivery: {type(error).__name__}')
    Path(args.report).write_text(json.dumps(report, indent=2) + '\n')
    print(json.dumps(report))
    return 0 if report['status'] == 'pass' else 1


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