"""本主题专属离线算法，仅读取同目录合成JSON，不联网、不控制设备。"""
import csv, json, math, re, struct
from pathlib import Path
from fractions import Fraction
BASE=Path(__file__).resolve().parent
data=json.loads((BASE/'input.json').read_text(encoding='utf-8'))['data']
import subprocess, shutil
ffmpeg=shutil.which('ffmpeg');ffprobe=shutil.which('ffprobe')
if not ffmpeg or not ffprobe:raise RuntimeError('需要本地FFmpeg与ffprobe；本脚本不下载软件')
media_version=subprocess.run([ffmpeg,'-version'],capture_output=True,text=True,encoding='utf-8',errors='replace',check=True).stdout.splitlines()[0]
def make_png(source,graph,filename):
 target=BASE/filename
 command=[ffmpeg,'-hide_banner','-nostdin','-y','-filter_threads','1','-f','lavfi','-i',source,'-vf',graph,'-frames:v','1','-c:v','png','-threads','1',str(target)]
 run=subprocess.run(command,capture_output=True,text=True,encoding='utf-8',errors='replace')
 if run.returncode:raise RuntimeError(run.stderr)
 probe_command=[ffprobe,'-v','error','-select_streams','v:0','-show_entries','stream=width,height,pix_fmt','-of','json',str(target)]
 probe=subprocess.run(probe_command,capture_output=True,text=True,encoding='utf-8',check=True)
 return {'file':filename,'command':command,'probe_command':probe_command,'stream':json.loads(probe.stdout)['streams'][0],'exit_code':run.returncode}

import itertools
permutations=[''.join(p) for p in itertools.permutations(data['labels'])];assert len(set(permutations))==6
body=[]
for i,label in enumerate(data['labels']):
 value=data['samples'][label];body.append(f'<rect x="{i*256}" y="0" width="256" height="240" fill="rgb({value[0]},{value[1]},{value[2]})"/><rect x="{i*256}" y="240" width="256" height="80" fill="white"/><text x="{i*256+30}" y="290" font-size="30">{label} {value}</text>')
(BASE/'labeled-rgb.svg').write_text('<svg xmlns="http://www.w3.org/2000/svg" width="768" height="320" viewBox="0 0 768 320">'+''.join(body)+'</svg>',encoding='utf-8')
media=make_png('rgbtestsrc=size=768x384:rate=1','format=rgb24','rgbtestsrc.png')
assert (media['stream']['width'],media['stream']['height'])==(768,384)
result={'channel_permutations':permutations,'input_samples':data['samples'],'media_version':media_version,'actual_media_run':media,'real_screen_color_order':None}
(BASE/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps(result,ensure_ascii=False))
