"""Bounded server-only measurements of the frozen 0.7.2a1 SDK image.

Fresh process + two resident repeats, with complete mark/sign/read-back and
independent verify. No production certificate/TSA or concurrent jobs.
"""
from datetime import datetime,timezone
import hashlib,json,os,platform,resource,subprocess,sys,time
from pathlib import Path
from ariadne_mark.pipeline import SDK
from ariadne_mark.signing import SigningIdentity,create_development_identity
from ariadne_mark.registry import Registry
from ariadne_mark.watermark import LazyWatermarker
from ariadne_mark.videoq import VideoWatermarker
from ariadne_mark.provenance import ProvenanceRecord,GenerativeSystem,MediaKind,Action
from ariadne_mark.version import sdk_version

root=Path('/bench');kind=sys.argv[1];out=root/kind;out.mkdir(exist_ok=False)
create_development_identity(out/'identity')
identity=SigningIdentity.from_directory(out/'identity',allow_dev=True)
source=root/'input.png' if kind=='image' else root/'input.mp4'
def cpu():
    values=dict(line.split() for line in Path('/sys/fs/cgroup/cpu.stat').read_text().splitlines())
    return int(values['usage_usec'])/1e6
def peak():return int(Path('/sys/fs/cgroup/memory.peak').read_text())/1024**2
def measured(operation,fn):
    before=cpu();start=time.monotonic();result=fn()
    return result,{'operation':operation,'wall_seconds':round(time.monotonic()-start,4),'cpu_seconds':round(cpu()-before,4),'session_cgroup_peak_mib':round(peak(),2)}
rows=[]
init=time.monotonic()
with SDK(marker=LazyWatermarker(threads=2),identity=identity,registry=Registry(out/'registry.sqlite3'),
    trust_anchors=out/'identity/trust.pem',video_marker=VideoWatermarker(threads=2,profile='economy_5s' if kind=='image' else kind)) as sdk:
    init_seconds=time.monotonic()-init
    for iteration in range(3):
        record=ProvenanceRecord.create(publisher='Ariadne benchmark fixture',system=GenerativeSystem('Synthetic fixture','1'),media_kind=MediaKind.IMAGE if kind=='image' else MediaKind.VIDEO,action=Action.CREATED,created_at=datetime.now(timezone.utc))
        destination=out/f'export-{iteration}{source.suffix}'
        receipt,timing=measured('export',lambda:sdk.mark(source,destination,record,audio_kind='none',video_profile=None if kind=='image' else kind))
        report,verification=measured('verify',lambda:sdk.verify(destination))
        ok=report.get('watermark',{}).get('token')==receipt['token']
        assert ok,report
        row={'profile':kind,'iteration':iteration,'worker':'first_job' if iteration==0 else 'resident_repeat','export':timing,'verify':verification,'token_recovered':ok,'label':report['label'],'output_bytes':destination.stat().st_size}
        rows.append(row);print(json.dumps(row),flush=True)
    report={'sdk_version':sdk_version(),'image_id':os.environ['BENCH_IMAGE_ID'],'platform':platform.platform(),'threads':2,'container_cpu_limit':2,'memory_limit_gib':4,'profile':kind,'sdk_construction_seconds':round(init_seconds,4),'input_sha256':hashlib.sha256(source.read_bytes()).hexdigest(),'input_bytes':source.stat().st_size,'source_probe':json.loads(subprocess.check_output(['ffprobe','-v','quiet','-show_format','-show_streams','-of','json',str(source)])) if kind!='image' else {'width':1024,'height':683},'peak_cgroup_mib':round(peak(),2),'scope':'Single public synthetic/AI fixture per modality. Session cgroup peak includes cache and child processes, not per-job RSS. First job means fresh process, not cold OS cache. Development signing, no production TSA. Not throughput, durability, SLA or legal qualification.','rows':rows}
    (out/'measurements.json').write_text(json.dumps(report,indent=2)+'\n')
