#!/usr/bin/env python3
"""Repository-scoped enzim Store CLI for developers and coding agents."""
import argparse
import json
import os
import re
from pathlib import Path
import sys
import urllib.error
import urllib.parse
import urllib.request

ORIGIN='https://flatpak.enzim.dev/developer-api'
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--credentials',type=Path,default=Path(os.environ.get('XDG_CONFIG_HOME',Path.home()/'.config'))/'enzim-store/session.json')
commands=parser.add_subparsers(dest='command',required=True)
auth=commands.add_parser('auth');auth.add_argument('--token-stdin',action='store_true',required=True)
commands.add_parser('repositories')
setup=commands.add_parser('setup');setup.add_argument('--repository',type=int,required=True);setup.add_argument('--confirm',action='store_true')
selection=commands.add_parser('selection');selection.add_argument('--repository',type=int,required=True);selection.add_argument('--release',type=int,required=True)
draft=commands.add_parser('draft');draft.add_argument('--repository',type=int,required=True);draft.add_argument('--release',type=int,required=True);draft.add_argument('--app-id',required=True)
upload=commands.add_parser('upload');upload.add_argument('--kind',choices=['icon','screenshot'],required=True);upload.add_argument('file',type=Path)
submit=commands.add_parser('submit');submit.add_argument('file',type=Path)
for command in ('build','status'):
    command_parser=commands.add_parser(command);command_parser.add_argument('--submission',required=True)
args=parser.parse_args()
try:
    if args.command=='auth':
        token=sys.stdin.read(150).strip()
        if not re.fullmatch(r'enzim_[A-Za-z0-9_-]{40,80}',token):raise ValueError('Provide a repository-scoped dashboard agent token')
        args.credentials.parent.mkdir(mode=0o700,parents=True,exist_ok=True)
        fd=os.open(args.credentials,os.O_WRONLY|os.O_CREAT|os.O_TRUNC|os.O_NOFOLLOW,0o600)
        with os.fdopen(fd,'w') as output:json.dump({'token':token},output)
        args.credentials.chmod(0o600);print(json.dumps({'saved':str(args.credentials)}));sys.exit(0)
    token=os.environ.get('ENZIM_STORE_TOKEN') or json.loads(args.credentials.read_text())['token']
    if not isinstance(token,str) or not re.fullmatch(r'enzim_[A-Za-z0-9_-]{40,80}',token):raise ValueError('Invalid agent token; create repository-scoped access in the dashboard')
    method='GET';data=None;content_type='application/json'
    if args.command=='repositories':path='/repositories'
    elif args.command=='setup':path=f'/repositories/{args.repository}/'+('merge-setup' if args.confirm else 'setup');method='POST';data=b'{}'
    elif args.command in ('selection','draft'):path=f'/selection?repository_id={args.repository}&release_id={args.release}'
    elif args.command=='upload':
        limit=(2 if args.kind=='icon' else 8)*1024**2
        if args.file.stat().st_size>limit:raise ValueError('Upload exceeds the documented image limit')
        path='/uploads?kind='+args.kind;method='POST';data=args.file.read_bytes()
        content_type='image/svg+xml' if args.kind=='icon' and args.file.suffix.lower()=='.svg' else 'application/octet-stream'
    elif args.command=='submit':path='/submissions';method='POST';data=json.dumps(json.loads(args.file.read_text())).encode()
    else:path='/submissions/'+urllib.parse.quote(args.submission,safe='')+'/build';method='POST' if args.command=='build' else 'GET';data=b'{}' if method=='POST' else None
    request=urllib.request.Request(ORIGIN+path,data=data,method=method,headers={'Authorization':'Bearer '+token,'Content-Type':content_type,'User-Agent':'enzim-store-cli/1'})
    with urllib.request.urlopen(request,timeout=360) as response:payload=json.load(response)
    if args.command=='draft':
        selected=payload
        if selected['packaging']['state']!='ready':
            raise ValueError((selected['packaging']['message'] or 'This release has no Flatpak manifest.')+' See https://flatpak.enzim.dev/packaging')
        repo=selected['repository'];release=selected['release'];owner=repo['full_name'].split('/')[0]
        payload={'repository_id':args.repository,'release_id':args.release,'commit':selected['commit'],'manifest_path':selected['manifest_path'],'icon':'UPLOAD_ICON_ID','screenshots':[{'id':'UPLOAD_SCREENSHOT_ID','caption':'Describe the actual screenshot'}],'public_consent':False,'listing':{'id':args.app_id,'name':repo['name'],'summary':(repo.get('description') or '')[:150],'description':repo.get('description') or '', 'developer':owner,'version':release['tag_name'].removeprefix('v'),'license':(repo.get('license') or {}).get('spdx_id',''),'metadata_license':'CC0-1.0','homepage':repo.get('homepage') or 'https://github.com/'+repo['full_name'],'support_url':'https://github.com/'+repo['full_name']+'/issues','release_notes':release.get('body') or release['tag_name'],'privacy_policy':'','data_collection':'','permissions_justification':'','categories':['Utility']}}
    print(json.dumps(payload,indent=2))
except urllib.error.HTTPError as error:
    try:payload=json.load(error)
    except ValueError:payload={'error':'Server returned HTTP '+str(error.code)}
    print(json.dumps(payload),file=sys.stderr);sys.exit(1)
except (OSError,ValueError,KeyError) as error:
    print(json.dumps({'error':str(error)}),file=sys.stderr);sys.exit(1)
