#!/usr/bin/env python3
"""Stolen Orbit Publisher CLI. Python 3.9+, standard library only."""
import argparse
import datetime as dt
import getpass
import http.client
import json
import os
import secrets
import ssl
import sys
import uuid
from pathlib import Path
from urllib.parse import urlparse, urlencode, quote

DEFAULT_URL = 'https://publisher.stolenorbit.com'
CONFIG = Path(os.environ.get('ORBIT_CONFIG', Path.home()/'.config/orbit-publisher/session.json'))

def request(path, method='GET', body=None, file=None, headers=None):
    url = urlparse(origin)
    if url.scheme != 'https' and not (url.scheme=='http' and url.hostname in ('127.0.0.1','localhost')):
        raise ValueError('Use HTTPS for hosted workspaces')
    conn = (http.client.HTTPSConnection if url.scheme=='https' else http.client.HTTPConnection)(url.hostname,url.port,timeout=90)
    h = dict(headers or {})
    if token:
        h['Authorization']='Bearer '+token
    if body is not None:
        h['Content-Type']='application/json'
    try:
        conn.request(method, '/api/'+path, body=file if file else (json.dumps(body) if body is not None else None), headers=h)
        r=conn.getresponse()
        raw=r.read()
        try: value=json.loads(raw)
        except ValueError: raise ValueError('Workspace returned HTTP '+str(r.status)) from None
        if r.status>=400: raise ValueError(value.get('error',str(r.status)))
        return value
    finally: conn.close()

def upload(path):
    p=Path(path)
    mime={'.jpg':'image/jpeg','.jpeg':'image/jpeg','.png':'image/png','.mp4':'video/mp4'}.get(p.suffix.lower())
    if not mime: raise ValueError('Use JPEG, PNG or MP4')
    size=str(p.stat().st_size)
    with p.open('rb') as f:
        return request('media','POST',file=f,headers={'Content-Type':mime,'Content-Length':size,'X-File-Size':size,'X-Filename':quote(p.name)})

def show(data): print(json.dumps(data,ensure_ascii=False,indent=2))
def parser():
    p=argparse.ArgumentParser(description=__doc__); p.add_argument('--url',help='Workspace HTTPS origin')
    sub=p.add_subparsers(dest='cmd',required=True)
    sub.add_parser('login',help='Redeem a one-time invite or device code')
    for c in ('accounts','queue','logout','device','open'): sub.add_parser(c)
    m=sub.add_parser('upload');m.add_argument('path')
    for c in ('publish','schedule','draft','edit'):
        a=sub.add_parser(c)
        if c=='edit':
            a.add_argument('job');a.add_argument('--version',type=int,required=True);a.add_argument('--draft',action='store_true')
        a.add_argument('--media',action='append',default=[],help='File or staged asset ID, repeat in carousel order')
        a.add_argument('--to',action='append',default=[],metavar='NETWORK:@HANDLE:PLACEMENT')
        a.add_argument('--caption',default='');a.add_argument('--instagram-caption');a.add_argument('--tiktok-caption')
        a.add_argument('--cover');a.add_argument('--frame-ms',type=int)
        a.add_argument('--at',required=c=='schedule',help='ISO date and time with offset')
        a.add_argument('--trial-strategy',choices=['MANUAL','SS_PERFORMANCE'],default='MANUAL')
        for f in ('own-brand','paid','ai','feed','disable-comment','disable-duet','disable-stitch','yes'):
            a.add_argument('--'+f,action='store_true')
        a.add_argument('--key',help='Stable submission key; reuse on network retries')
    for c in ('show','cancel','reschedule'):
        a=sub.add_parser(c);a.add_argument('job')
        if c!='show':a.add_argument('--version',type=int,required=True)
        if c=='reschedule':a.add_argument('--at',required=True)
    sub.add_parser('retry').add_argument('delivery')
    a=sub.add_parser('stats');a.add_argument('what',choices=['posts','totals','history']);a.add_argument('--accounts',default='all')
    for f in ('platform','project','kind','post','published-since','published-until','limit','sort'):a.add_argument('--'+f)
    a.add_argument('--json',action='store_true');a.add_argument('--refresh',action='store_true')
    return p

def run(a):
    global token
    c=a.cmd
    if c=='login':
        data=request('login','POST',{'code':getpass.getpass('One-time team code: ').strip(),'cli':True})
        CONFIG.parent.mkdir(mode=0o700,parents=True,exist_ok=True)
        tmp=CONFIG.with_name(CONFIG.name+'.'+secrets.token_hex(6))
        with os.fdopen(os.open(tmp,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600),'w') as f: json.dump({'origin':origin,'token':data['token']},f)
        os.replace(tmp,CONFIG);return {'signed_in':data['email'],'workspace':origin}
    if c=='logout':
        r=request('logout','POST',{});CONFIG.unlink(missing_ok=True);return r
    if c=='open':
        import webbrowser
        code=request('device','POST',{})['code']
        webbrowser.open(origin+'/#device='+code)
        return {'opened':origin}
    if c=='device':return request('device','POST',{})
    if c=='accounts':return request('accounts')
    if c=='queue':return request('jobs')
    if c=='upload':return upload(a.path)
    if c=='show':return request('jobs/'+a.job)
    if c=='cancel':return request('jobs/'+a.job,'DELETE',{'version':a.version})
    if c=='retry':return request('deliveries/'+a.delivery+'/retry','POST',{})
    if c=='reschedule':
        job=request('jobs/'+a.job);return request('jobs/'+a.job,'PATCH',{'version':a.version,'action':'schedule','at':a.at,'key':str(uuid.uuid4()),'spec':job['spec']})
    if c=='stats':
        if a.refresh:
            while request('sync','POST',{'account':a.accounts}).get('remaining'):pass
        q={'account':a.accounts,'platform':a.platform,'project':a.project,'kind':a.kind,'post':a.post,'since':a.published_since,'until':a.published_until,'limit':a.limit,'sort':a.sort}
        query=urlencode({k:v for k,v in q.items() if v})
        if a.what=='history':return request('observations?'+query)
        r=request('stats?'+query)
        if a.what=='totals':r.pop('posts')
        if a.json:return r
        for p in r.get('posts',[]):print(p['platform'], '@'+p['handle'],p['metrics'][r['metric']],p['link'] or 'URL unavailable',dt.datetime.fromtimestamp(p['observed']/1000,dt.timezone.utc).isoformat() if p['observed'] else 'pending',sep='\t')
        return {k:v for k,v in r.items() if k!='posts'}
    accounts=request('accounts');dest=[]
    for target in a.to:
        parts=target.split(':')
        if len(parts)!=3:raise ValueError('Destination format is network:@handle:placement')
        net,handle,placement=parts
        hits=[x for x in accounts if x['network']==net and (x['id']==handle or x['handle'].lower()==handle.lstrip('@').lower())]
        if len(hits)!=1:raise ValueError('Unknown or ambiguous destination '+target)
        d={'account':hits[0]['id'],'placement':placement,'caption':getattr(a,net+'_caption'),'strategy':a.trial_strategy}
        if net=='tiktok':
            for k in ('own_brand','paid','ai','disable_comment','disable_duet','disable_stitch'):d[k]=getattr(a,k)
        else:d['feed']=a.feed
        dest.append(d)
    def asset(x):return upload(x)['id'] if Path(x).is_file() else x
    spec={'media':[asset(x) for x in a.media],'destinations':dest,'caption':a.caption,'frame_ms':a.frame_ms,'cover':asset(a.cover) if a.cover else None}
    body={'action':'draft' if c=='draft' or getattr(a,'draft',False) else 'schedule','at':a.at,'spec':spec,'key':a.key or str(uuid.uuid4())}
    if c=='edit':body.update(id=a.job,version=a.version)
    preview=request('preview','POST',body)
    print(json.dumps({'release_utc':dt.datetime.fromtimestamp(preview['due']/1000,dt.timezone.utc).isoformat(),'destinations':[x['network']+':@'+x['handle'] for x in preview['accounts']],'ordered_files':[x['name'] for x in preview['media']],'cover':(preview['cover'] or {}).get('name'),'settings':preview['spec'],'submission_key':body['key']},ensure_ascii=False,indent=2),file=sys.stderr)
    if not a.yes and input('Confirm [yes/no]? ').strip().lower()!='yes':raise ValueError('Cancelled')
    return request('jobs/'+a.job if c=='edit' else 'jobs','PATCH' if c=='edit' else 'POST',body)

if __name__=='__main__':
    args=parser().parse_args()
    try:
        cfg=json.loads(CONFIG.read_text()) if CONFIG.exists() else {}
        origin=(args.url or os.environ.get('ORBIT_URL') or cfg.get('origin') or DEFAULT_URL).rstrip('/')
        token=cfg.get('token') if origin==cfg.get('origin') else None
        show(run(args))
    except (ValueError,OSError,http.client.HTTPException,EOFError) as e:
        sys.exit(str(e))
