#!/usr/bin/env python3
"""Install the locally built FFmpeg into a NEW runtime copy only."""
import ctypes
import json
import shutil
import subprocess
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
BUILD = ROOT / 'build/legal-runtime'
RUNTIME = BUILD / 'Runtime'
TARGET = RUNTIME / 'site-packages/av/.dylibs'
SOURCE = BUILD / 'ffmpeg-install/lib'
MARKER = BUILD / 'ffmpeg-installed.json'

if MARKER.exists():
    raise SystemExit('Already installed; preserve this build and use a fresh copy.')
assert RUNTIME.is_dir() and SOURCE.is_dir()
old = BUILD / 'original-av-libraries'
if old.exists():
    raise SystemExit('Backup already exists; inspect the interrupted installation.')
TARGET.rename(old)
TARGET.mkdir()
files = list(SOURCE.glob('*.dylib'))
for path in files:
    if path.is_symlink():
        (TARGET / path.name).symlink_to(path.readlink())
    else:
        shutil.copy2(path, TARGET / path.name)
        subprocess.run(['codesign', '--force', '--sign', '-', str(TARGET / path.name)], check=True)
checks = {}
for stem in ('avutil', 'avcodec', 'avformat', 'avfilter', 'avdevice', 'swresample', 'swscale'):
    lib = ctypes.CDLL(str(TARGET / ('lib' + stem + '.dylib')))
    fn = getattr(lib, stem + '_license'); fn.restype = ctypes.c_char_p
    license_name = fn().decode()
    fn = getattr(lib, stem + '_configuration'); fn.restype = ctypes.c_char_p
    configuration = fn().decode()
    assert license_name == 'LGPL version 2.1 or later', (stem, license_name)
    assert '--enable-gpl' not in configuration and '--enable-nonfree' not in configuration
    assert '--enable-libx264' not in configuration and '--enable-libx265' not in configuration
    checks[stem] = dict(license=license_name, configuration=configuration)
MARKER.write_text(json.dumps(checks, indent=2) + '\n')
print('Seven FFmpeg libraries verified: LGPL-2.1-or-later; no x264/x265.')
