#!/usr/bin/env python3
"""Complete Website2Zip API setup without opening the administrator UI.

Credentials are read from W2Z_ADMIN_PASSWORD and optional W2Z_ADMIN_OTP.
Sessions remain in memory and are signed out automatically.
"""
import argparse
import http.cookiejar
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request

BASE='https://website2zip.com/temp-mail/admin/api/v1'
ORIGIN='https://website2zip.com'


class APIError(RuntimeError):pass


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self,*args,**kwargs):return None


class Administrator:
    def __init__(self,password=None,otp=None):
        self.password=password if password is not None else os.environ.get('W2Z_ADMIN_PASSWORD','')
        self.otp=otp if otp is not None else os.environ.get('W2Z_ADMIN_OTP','')
        if not self.password:raise ValueError('Set W2Z_ADMIN_PASSWORD to the administrator password.')
        self.cookies=http.cookiejar.CookieJar()
        self.http=urllib.request.build_opener(NoRedirect(),urllib.request.HTTPCookieProcessor(self.cookies))
        self.csrf=''

    def request(self,path,method='GET',body=None,headers=None):
        if not path.startswith('/')or path.startswith('//'):raise ValueError('Use an API-relative path.')
        fields={'Accept':'application/json','User-Agent':'Mozilla/5.0 (compatible; Website2Zip-SetupClient/1.1)',**(headers or {})}
        payload=None if body is None else json.dumps(body,allow_nan=False).encode()
        if payload is not None:fields['Content-Type']='application/json'
        if method!='GET':
            fields['Origin']=ORIGIN
            if self.csrf:fields['X-CSRF-Token']=self.csrf
        request=urllib.request.Request(BASE+path,data=payload,headers=fields,method=method)
        try:
            with self.http.open(request,timeout=60)as response:return json.load(response)
        except urllib.error.HTTPError as exc:
            try:error=json.load(exc)
            except ValueError:error={}
            details=error.get('error',{})
            raise APIError(str(exc.code)+' '+details.get('code','http_error')+': '+details.get('message','Request failed')+
                           (' '+json.dumps(details['details'])if details.get('details')else ''))from None

    def __enter__(self):
        result=self.request('/auth/login','POST',{'password':self.password,'otp':self.otp})
        self.csrf=result['data']['csrf_token']
        self.password=self.otp=None
        return self

    def __exit__(self,*args):
        try:self.request('/auth/logout','POST',{})
        finally:self.cookies.clear();self.csrf=''

    def create_inbox(self,address,operation_id,label=''):
        existing=self.request('/mailboxes')
        for mailbox in existing['data']:
            if mailbox['address']==address.strip().lower():
                return {'data':mailbox,'existing':True,'request_id':existing['request_id']}
        preview=self.request('/mailboxes/preview','POST',{'address':address})['data']
        return self.request('/mailboxes','POST',{'address':address,'plan_token':preview['plan_token'],'label':label},
                            {'Idempotency-Key':operation_id})


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    commands=parser.add_subparsers(dest='command',required=True)
    commands.add_parser('domains');commands.add_parser('discover-domains')
    status=commands.add_parser('domain-status');status.add_argument('domain')
    preview=commands.add_parser('preview-domain');preview.add_argument('domain');preview.add_argument('--create-zone',action='store_true');preview.add_argument('--no-enable-routing',action='store_true')
    connect=commands.add_parser('connect-domain');connect.add_argument('domain');connect.add_argument('--plan-token',required=True)
    verify=commands.add_parser('verify-domain');verify.add_argument('domain')
    inbox=commands.add_parser('create-inbox');inbox.add_argument('address');inbox.add_argument('--operation-id',required=True);inbox.add_argument('--label',default='')
    key=commands.add_parser('create-key');key.add_argument('--name',required=True);key.add_argument('--scopes',required=True);key.add_argument('--mailboxes',required=True,help='Comma-separated mailbox IDs, or * for all-mailboxes management');key.add_argument('--expires-at')
    args=parser.parse_args()
    with Administrator()as api:
        if args.command=='domains':result=api.request('/domains')
        elif args.command=='discover-domains':result=api.request('/domains/discover')
        elif args.command=='domain-status':result=api.request('/domains/status?'+urllib.parse.urlencode({'domain':args.domain}))
        elif args.command=='preview-domain':result=api.request('/domains/preview','POST',{'domain':args.domain,'create_zone':args.create_zone,'enable_routing':not args.no_enable_routing})
        elif args.command=='connect-domain':result=api.request('/domains','POST',{'domain':args.domain,'plan_token':args.plan_token})
        elif args.command=='verify-domain':result=api.request('/domains/verify','POST',{'domain':args.domain})
        elif args.command=='create-inbox':result=api.create_inbox(args.address,args.operation_id,args.label)
        elif args.command=='create-key':
            body={'name':args.name,'scopes':[x.strip()for x in args.scopes.split(',')if x.strip()],
                  'mailbox_ids':'*'if args.mailboxes=='*'else[x.strip()for x in args.mailboxes.split(',')if x.strip()]}
            if args.expires_at:body['expires_at']=args.expires_at
            result=api.request('/keys','POST',body)
        # Creating a key explicitly returns its one-time secret; handle stdout securely.
        print(json.dumps(result,indent=2))


if __name__=='__main__':
    try:main()
    except (APIError,ValueError,urllib.error.URLError,TimeoutError)as exc:
        print(str(exc),file=sys.stderr);raise SystemExit(1)
