"""Commercial API CLI. Credentials are read from a mode-0600 local JSON file."""
import argparse
from getpass import getpass
import hashlib
import json
import os
from pathlib import Path
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid


class APIError(RuntimeError):
    def __init__(self, status, data):
        self.status = status
        self.data = data
        super().__init__(f'{status}: '+data.get('message','Request failed'))


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


class Client:
    def __init__(self,path):
        path=Path(path)
        if path.stat().st_mode & 0o077: raise ValueError('Credential file must use permissions 0600')
        self.config=json.loads(path.read_text())
        if not self.config['apiUrl'].startswith('https://'): raise ValueError('HTTPS is required')

    def request(self,method,path,body=None):
        headers={'Authorization':'Bearer '+self.config['token'],'Content-Type':'application/json','X-Workspace-Id':self.config['workspaceId']}
        request=urllib.request.Request(self.config['apiUrl']+path,data=json.dumps(body).encode() if body is not None else None,headers=headers,method=method)
        try:
            opener = urllib.request.build_opener(NoRedirect()).open if body and {'apiKey','accessToken'} & body.keys() else urllib.request.urlopen
            with opener(request,timeout=45) as response:return json.load(response)
        except urllib.error.HTTPError as error:
            with error:
                try:
                    data=json.loads(error.read())
                except ValueError:
                    data={}
            raise APIError(error.code,data if isinstance(data,dict) else {}) from error

    def publish(self,sid,directory,revision,key,path=None,*,upload_key=None,protected_paths=(),media_collection=None):
        if path is not None and media_collection is not None:
            raise ValueError('Choose a path update or a private media collection.')
        directory=Path(directory).resolve()
        files={}
        for file in sorted(directory.rglob('*')):
            if file.is_symlink():raise ValueError('Do not publish symlinks')
            if file.is_file():
                relative=file.relative_to(directory)
                if any(part.startswith('.') for part in relative.parts):raise ValueError('Do not publish hidden files')
                files[relative.as_posix()]=file.read_bytes()
        root=(path or '').strip('/')
        if protected_paths and (path is None or any(f'{root}/{name}' in protected_paths for name in files)):
            raise ValueError('This deploy would replace a private download. Choose a path that preserves it.')
        manifest=[dict(path=p,size=len(data),sha256=hashlib.sha256(data).hexdigest()) for p,data in files.items()]
        body = dict(files=manifest, idempotencyKey=upload_key or key+'-upload')
        resource = 'releases'
        if path is not None:
            body.update(path=path, expectedRevision=revision)
            resource = 'path-releases'
        if media_collection is not None:
            body['mediaCollection'] = media_collection
        prepared = self.request('POST', f'/v1/sites/{sid}/{resource}', body)
        for upload in prepared['uploads']:
            relative=upload['path'][len(root)+1:] if root else upload['path']
            request=urllib.request.Request(upload['url'],data=files[relative],headers=upload['headers'],method='PUT')
            try:
                with urllib.request.urlopen(request,timeout=90) as response:response.read()
            except urllib.error.HTTPError as error:
                if error.code!=412:raise # signed immutable retry: already uploaded; worker verifies checksum
        return self.request('POST',f'/v1/sites/{sid}/publish',dict(releaseId=prepared['release']['id'],expectedRevision=revision,idempotencyKey=key))

    def deploy(self, sid, directory, target, key):
        """Publish finished files and wait for the durable job, including on CI retries."""
        if not re.fullmatch(r'[a-f0-9]{24}', sid):
            raise ValueError('Enter the BurstPage website ID.')
        if target != 'site' and not re.fullmatch(r'/(?:[A-Za-z0-9_-][A-Za-z0-9_.-]*/)+', target):
            raise ValueError('Choose site for a full release or a named path such as /quiz/.')
        prefix = f'/v1/sites/{sid}'
        path = None if target == 'site' else target
        # The publish API derives its job ID from the site and idempotency key.
        operation_key = 'deploy-' + hashlib.sha256(f'{target}:{key}'.encode()).hexdigest()
        job_id = hashlib.sha256(f'{sid}:{operation_key}'.encode()).hexdigest()[:24]
        job_path = f'{prefix}/jobs/{job_id}'
        try:
            job = self.request('GET', job_path)
        except APIError as error:
            if error.status != 404:
                raise
            site = self.request('GET', prefix)
            protected = set()
            if site.get('releaseId'):
                releases = self.request('GET', f'{prefix}/releases')
                current = next(release for release in releases if release['id'] == site['releaseId'])
                protected = {file['path'] for file in current['files'] if file.get('private')}
            revision = site['revision']
            job = self.publish(sid, directory, revision, operation_key, path,
                               upload_key=f'{operation_key}-{revision}-upload', protected_paths=protected)

        deadline = time.monotonic() + 180
        while job['status'] == 'queued' and time.monotonic() < deadline:
            time.sleep(4)
            job = self.request('GET', job_path)
        if job['status'] == 'failed':
            raise ValueError(f"BurstPage deployment {job_id} failed. {job.get('error') or 'Check the site release in BurstPage.'}")
        if job['status'] != 'complete':
            raise ValueError(f'BurstPage deployment {job_id} is still pending. Rerun this workflow to check the same job.')
        return dict(id=job_id, status=job['status'], revision=job['revision'])


def main():
    p=argparse.ArgumentParser(description='BurstPage commercial publisher')
    p.add_argument('--config',default=os.environ.get('DTL_PLATFORM_CONFIG'))
    sub=p.add_subparsers(dest='command',required=True)
    for name in ('sites','usage','members','journey'):sub.add_parser(name)
    sub.add_parser('publishing-guidance', help='Read shared and website brand and publishing guidance').add_argument('site')
    guidance = sub.add_parser('set-publishing-guidance', help='Save guidance for a website from a JSON file')
    guidance.add_argument('site')
    guidance.add_argument('--body-file', required=True, help='JSON with brandGuide, sharedPrompt, and expectedRevision')
    create=sub.add_parser('create');create.add_argument('name');create.add_argument('--public',action='store_true');create.add_argument('--key',required=True);create.add_argument('--host-label')
    rename=sub.add_parser('rename');rename.add_argument('site');rename.add_argument('name')
    upgrade=sub.add_parser('upgrade',help='Get the workspace link for reviewing or changing your plan')
    upgrade.add_argument('--plan',choices=['launch','scale','grow'])
    tracking=sub.add_parser('set-tracking',help='Update website-wide tracking from a JSON settings file')
    tracking.add_argument('site');tracking.add_argument('--body-file',required=True)
    meta=sub.add_parser('meta-conversions',help='Read the website’s Meta Conversions API status')
    meta.add_argument('site')
    meta_set=sub.add_parser('set-meta-conversions',help='Enable or pause server Lead events')
    meta_set.add_argument('site');meta_set.add_argument('--revision',type=int,required=True)
    meta_set.add_argument('--disable',action='store_true')
    meta_set.add_argument('--prompt-token',action='store_true',help='Enter a token without echo')
    for name in ('get','analytics','releases','data','submissions','paths','domains','tracking','custom-events'):
        command=sub.add_parser(name);command.add_argument('site')
    custom_set=sub.add_parser('set-custom-event');custom_set.add_argument('site');custom_set.add_argument('--body-file',required=True)
    custom_test=sub.add_parser('test-custom-event');custom_test.add_argument('site');custom_test.add_argument('name')
    publish=sub.add_parser('publish');publish.add_argument('site');publish.add_argument('directory');publish.add_argument('--revision',type=int,required=True);publish.add_argument('--key',required=True)
    destination = publish.add_mutually_exclusive_group()
    destination.add_argument('--path',help='Update underneath a path and retain neighboring pages')
    destination.add_argument('--media-collection',help='Publish files into a named collection on a live private website')
    deploy = sub.add_parser('deploy', help='Publish a CI build and wait for its release to go live')
    deploy.add_argument('site')
    deploy.add_argument('directory')
    deploy.add_argument('--target', required=True, help='A named path such as /quiz/, or site for a complete replacement')
    deploy.add_argument('--key', required=True, help='Stable ID for the CI run')
    for name in ('connect-domain','check-domain'):
        command=sub.add_parser(name);command.add_argument('site');command.add_argument('domain')
    privacy=sub.add_parser('privacy');privacy.add_argument('site');privacy.add_argument('visibility',choices=['public','private']);privacy.add_argument('--revision',type=int,required=True);privacy.add_argument('--key',required=True)
    invite=sub.add_parser('invite');invite.add_argument('email');invite.add_argument('--role',choices=['admin','editor','viewer'],default='viewer')
    remove=sub.add_parser('remove-member');remove.add_argument('user')
    raw=sub.add_parser('request');raw.add_argument('method',choices=['GET','POST','PUT','DELETE']);raw.add_argument('path');raw.add_argument('--body-file',help='JSON request body, not credentials')
    for resource in ('email-delivery','lead-destination'):
        read=sub.add_parser(resource);read.add_argument('site')
        if resource == 'lead-destination':read.add_argument('--file',help='Published HTML file path')
        update=sub.add_parser('set-'+resource);update.add_argument('site');update.add_argument('--body-file',required=True)
        update.add_argument('--prompt-key',action='store_true',help='Enter a new provider API key without echo')
    route=sub.add_parser('set-lead-form');route.add_argument('site');route.add_argument('form');route.add_argument('--body-file',required=True)
    retry=sub.add_parser('retry-lead-sync');retry.add_argument('site');retry.add_argument('job')
    github_status = sub.add_parser('github-status', help='Read a GitHub connection and its last deployment')
    github_status.add_argument('site')
    github_connect = sub.add_parser('github-connect', help='Prepare a GitHub setup link to review and authorize in your browser')
    github_connect.add_argument('site')
    github_connect.add_argument('--repo', help='GitHub repository in owner/name format')
    github_connect.add_argument('--branch', help='Branch name when providing all settings. Defaults to main.')
    github_connect.add_argument('--folder', help='Folder containing a finished index.html, or . for the repository root')
    github_connect.add_argument('--target', help='A named path such as /quiz/, or site for a complete replacement')
    github_connect.add_argument('--automatic', action='store_true', help='Publish when a commit is pushed to the selected branch')
    for name, help_text in (('github-deploy','Publish from the connected GitHub repository'),
                            ('github-disconnect','Disconnect GitHub and keep the published files')):
        command = sub.add_parser(name, help=help_text)
        command.add_argument('site')
        command.add_argument('--revision', required=True, help='Connection revision from github-status')
    args=p.parse_args()
    if not args.config:p.error('Set --config or DTL_PLATFORM_CONFIG to a credential file')
    client=Client(args.config);wid=client.config['workspaceId']
    if args.command in ('sites','usage','members','journey'):result=client.request('GET',f'/v1/workspaces/{wid}/{args.command}')
    elif args.command=='publishing-guidance':
        result = client.request('GET', f'/v1/sites/{args.site}/customization?include=shared')
    elif args.command=='set-publishing-guidance':
        result = client.request('PUT', f'/v1/sites/{args.site}/customization', json.loads(Path(args.body_file).read_text()))
    elif args.command=='create':result=client.request('POST',f'/v1/workspaces/{wid}/sites',dict(name=args.name,visibility='public' if args.public else 'private',idempotencyKey=args.key,hostLabel=args.host_label))
    elif args.command=='rename':result=client.request('PUT',f'/v1/sites/{args.site}',dict(name=args.name))
    elif args.command=='upgrade':
        origin=client.request('GET','/v1/config')['appOrigin'].rstrip('/')
        suffix=f'&plan={args.plan}' if args.plan else ''
        result=dict(billingUrl=f'{origin}/workspace/billing?workspace={wid}{suffix}')
    elif args.command=='set-tracking':
        result=client.request('PUT',f'/v1/sites/{args.site}/tracking',json.loads(Path(args.body_file).read_text()))
    elif args.command in ('email-delivery','lead-destination'):
        file = getattr(args, 'file', None)
        suffix = '?'+urllib.parse.urlencode(dict(file=file)) if file else ''
        result=client.request('GET', f'/v1/sites/{args.site}/{args.command}'+suffix)
    elif args.command in ('set-email-delivery','set-lead-destination','set-lead-form'):
        body = json.loads(Path(args.body_file).read_text())
        if not isinstance(body,dict) or 'apiKey' in body:p.error('Keep provider keys out of settings files. Use --prompt-key.')
        if getattr(args,'prompt_key',False):
            if not sys.stdin.isatty():p.error('Run --prompt-key in an interactive terminal.')
            body['apiKey']=getpass('Provider API key: ')
        resource = args.command[4:] if args.command != 'set-lead-form' else 'lead-destination/'+urllib.parse.quote(args.form,safe='')
        if resource == 'email-delivery':body['mode']='provider'
        result=client.request('PUT', f'/v1/sites/{args.site}/{resource}', body)
    elif args.command=='retry-lead-sync':
        result=client.request('POST',f'/v1/sites/{args.site}/lead-destination/'+urllib.parse.quote(args.job,safe=''),{})
    elif args.command=='meta-conversions':
        result=client.request('GET',f'/v1/sites/{args.site}/tracking/meta')
    elif args.command=='set-meta-conversions':
        if args.disable and args.prompt_token:p.error('Choose whether to pause events or save a token.')
        body=dict(enabled=not args.disable,expectedRevision=args.revision)
        if args.prompt_token:body['accessToken']=getpass('Meta Conversions API token: ').strip()
        result=client.request('PUT',f'/v1/sites/{args.site}/tracking/meta',body)
    elif args.command=='github-status':
        result=client.request('GET',f'/v1/sites/{args.site}/github')
    elif args.command=='github-connect':
        body = {}
        if any((args.repo, args.branch, args.folder, args.target, args.automatic)):
            if not all((args.repo, args.folder, args.target)):
                p.error('Use only the site ID for guided GitHub setup, or provide --repo, --folder and --target.')
            body = dict(repo=args.repo, branch=args.branch or 'main', folder=args.folder, target=args.target, automatic=args.automatic)
        result=client.request('POST',f'/v1/sites/{args.site}/github/connect',body)
    elif args.command in ('github-deploy','github-disconnect'):
        result=client.request('POST',f'/v1/sites/{args.site}/github/'+args.command.removeprefix('github-'),dict(revision=args.revision))
    elif args.command in ('get','analytics','releases','data','submissions','paths','domains','tracking','custom-events'):result=client.request('GET',f'/v1/sites/{args.site}'+('/'+args.command if args.command!='get' else ''))
    elif args.command=='set-custom-event':result=client.request('PUT',f'/v1/sites/{args.site}/custom-events',json.loads(Path(args.body_file).read_text()))
    elif args.command=='test-custom-event':result=client.request('POST',f'/v1/sites/{args.site}/custom-events/test',dict(name=args.name))
    elif args.command=='publish':result=client.publish(args.site,args.directory,args.revision,args.key,args.path,media_collection=args.media_collection)
    elif args.command=='deploy':
        try:
            result=client.deploy(args.site,args.directory,args.target,args.key)
        except ValueError as error:
            p.exit(1, f'{error}\n')
    elif args.command=='connect-domain':result=client.request('POST',f'/v1/sites/{args.site}/domains',dict(domain=args.domain))
    elif args.command=='check-domain':result=client.request('POST',f'/v1/sites/{args.site}/domains/{args.domain}',{})
    elif args.command=='privacy':result=client.request('POST',f'/v1/sites/{args.site}/privacy',dict(visibility=args.visibility,expectedRevision=args.revision,idempotencyKey=args.key))
    elif args.command=='invite':result=client.request('POST',f'/v1/workspaces/{wid}/invites',dict(email=args.email,role=args.role))
    elif args.command=='remove-member':result=client.request('DELETE',f'/v1/workspaces/{wid}/members/{args.user}')
    else:result=client.request(args.method,args.path,json.loads(Path(args.body_file).read_text()) if args.body_file else None)
    print(json.dumps(result,indent=2))


if __name__=='__main__':
    try:
        main()
    except APIError as error:
        print(json.dumps(dict(error.data,status=error.status),indent=2),file=sys.stderr)
        raise SystemExit(1) from None
