"""Owned HLS AES-128 fixture. Requires cryptography and ffmpeg.

Creates two short MPEG-TS segments, encrypts with separate test keys,
uses implicit/explicit IVs, then checks the recovered plaintext hashes.
"""
import hashlib
import subprocess
import tempfile
from pathlib import Path
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.padding import PKCS7


def encrypt(data, key, iv):
    padder = PKCS7(128).padder()
    padded = padder.update(data) + padder.finalize()
    worker = Cipher(algorithms.AES(key), modes.CBC(iv)).encryptor()
    return worker.update(padded) + worker.finalize()


def decrypt(data, key, iv):
    worker = Cipher(algorithms.AES(key), modes.CBC(iv)).decryptor()
    padded = worker.update(data) + worker.finalize()
    unpadder = PKCS7(128).unpadder()
    return unpadder.update(padded) + unpadder.finalize()


with tempfile.TemporaryDirectory(prefix="sreverse-owned-hls-") as directory:
    root = Path(directory)
    source = root / "source.ts"
    subprocess.run(["ffmpeg", "-v", "error", "-f", "lavfi", "-i",
                    "color=c=blue:s=160x90:r=10", "-t", "1", "-c:v", "mpeg2video",
                    "-f", "mpegts", str(source)], check=True, timeout=30)
    original = source.read_bytes()
    recovered = []
    for sequence, key, explicit in [(7, bytes(range(16)), None),
                                     (8, bytes(range(16, 32)), bytes.fromhex("00" * 15 + "2a"))]:
        iv = explicit if explicit is not None else sequence.to_bytes(16, "big")
        encrypted = encrypt(original, key, iv)
        plain = decrypt(encrypted, key, iv)
        assert hashlib.sha256(plain).digest() == hashlib.sha256(original).digest()
        assert plain[0] == 0x47 and len(plain) % 188 == 0
        recovered.append(plain)
    output = root / "restored.ts"
    output.write_bytes(b"".join(recovered))
    subprocess.run(["ffmpeg", "-v", "error", "-i", str(output), "-f", "null", "-"],
                   check=True, timeout=30)
    print("PASS: two AES-128 segments, rotated keys, implicit/explicit IVs, matching hashes and decode")
