#!/usr/bin/python3
"""Verify real package ownership and optionally exercise vendor binaries without administrator privileges."""
import argparse
import json
import os
from pathlib import Path
import subprocess
import sys
from tempfile import TemporaryDirectory
from artcraft import architecture,catalog,desktop,installed_native,installed_web,web_index


def main():
    parser=argparse.ArgumentParser()
    parser.add_argument('--exercise',action='store_true',help='Execute headless vendor binaries and render a sample image')
    options=parser.parse_args()
    if options.exercise and os.geteuid()==0:
        parser.error('Run the executable checks as the desktop user.')
    native=architecture()=='amd64'
    rows=[]
    with TemporaryDirectory() as tmp:
        env={**os.environ,'XDG_CONFIG_HOME':tmp+'/config','XDG_CACHE_HOME':tmp+'/cache','XDG_DATA_HOME':tmp+'/data'}
        for app in catalog():
            if not native:
                rows.append({'name':app['name'],'installed':installed_web(app),'type':'WebAssembly',
                             'index':str(web_index(app))})
                continue
            dst=desktop(app)
            present=installed_native(app) and bool(dst)
            row={'name':app['name'],'installed':present,'type':'native','desktop':str(dst or '')}
            if options.exercise and present:
                bins = [Path(s) for s in subprocess.check_output(
                    ['/usr/bin/dpkg-query','-L',app['package']],text=True).splitlines()
                    if s.startswith('/usr/bin/') and os.path.isfile(s) and os.access(s,os.X_OK)]
                binary=next((p for p in bins if p.name.endswith('-cli')),None)
                if binary is None:
                    binary=next((p for p in bins if p.name==app['package']),None)
                row['exercise']=False
                if binary:
                    row['tested_binary']=str(binary)
                    try:
                        result=subprocess.run([str(binary),'--version'],capture_output=True,text=True,timeout=25,env=env)
                        output=(result.stdout+' '+result.stderr).strip()
                        row.update(exercise=result.returncode==0 and bool(output),message=output[:240])
                    except (OSError,subprocess.TimeoutExpired) as exc:
                        row['message']=str(exc)
            rows.append(row)
        if native and options.exercise:
            target=Path(tmp)/'sample.png'
            try:
                proc=subprocess.run(['/usr/bin/materialcraft-cli','render','sample',str(target),'--size','64x64'],
                                    capture_output=True,text=True,env=env,timeout=60)
                rendered=proc.returncode==0 and target.is_file() and target.open('rb').read(8)==b'\x89PNG\r\n\x1a\n'
            except (OSError,subprocess.TimeoutExpired):
                rendered=False
        else:rendered=None
    print(json.dumps({'apps':rows,'materialcraft_rendered_png':rendered},ensure_ascii=False,indent=2))
    return int(any(not r['installed'] or r.get('exercise') is False for r in rows) or rendered is False)


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