"""Hosted SSLCOMMERZ integration. Secrets come from the hosting environment."""
import json
import os
from urllib.parse import urlencode, urlsplit
from urllib.request import Request, build_opener, HTTPRedirectHandler
from core import Invalid, amount

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

def configuration():
    env=os.environ
    testing=env.get('ASTHA_SSL_SANDBOX','1')!='0'
    fields=(env.get('ASTHA_SSL_STORE',''),env.get('ASTHA_SSL_PASSWORD',''),env.get('ASTHA_PUBLIC_BASE','').rstrip('/'))
    try:
        base=urlsplit(fields[2])
        valid=base.scheme=='https' and base.hostname and not (base.username or base.password or base.query or base.fragment)
    except ValueError:
        valid=False
    return ('sandbox.sslcommerz.com' if testing else 'securepay.sslcommerz.com',*fields) if all(fields) and valid else None

def read_json(request):
    try:
        with build_opener(NoRedirect()).open(request,timeout=8) as response:
            data=json.loads(response.read(200000))
        if isinstance(data,dict):
            return data
    except (OSError,ValueError):
        pass
    raise Invalid('The payment provider is unavailable. Try again from order tracking.')

def initiate(order):
    host,store,password,base=configuration()
    callback=base+'/payment/return'
    data={
       'store_id':store,'store_passwd':password,'total_amount':f"{(order['subtotal']+order['delivery'])/100:.2f}",
       'currency':'BDT','tran_id':order['code'],'success_url':callback,'fail_url':callback,'cancel_url':callback,'ipn_url':base+'/payment/ipn',
       'emi_option':0,'cus_name':order['customer'],'cus_email':order['email'],'cus_add1':order['address'],'cus_city':order['zone'],
       'cus_country':'Bangladesh','cus_phone':order['phone'],'shipping_method':'YES','num_of_item':1,'product_name':'Pharmacy order',
       'product_category':'Healthcare','product_profile':'general',
       'ship_name':order['customer'],'ship_add1':order['address'],'ship_city':order['zone'],'ship_country':'Bangladesh'
    }
    response=read_json(Request('https://'+host+'/gwprocess/v4/api.php',data=urlencode(data).encode()))
    location=str(response.get('GatewayPageURL',''))
    target=urlsplit(location)
    if response.get('status')!='SUCCESS' or target.scheme!='https' or target.hostname!=host or target.username or target.password:
        raise Invalid('The payment provider could not open this transaction. Please verify merchant configuration.')
    return location,str(response.get('sessionkey',''))

def validate(value):
    host,store,password,_=configuration()
    query=urlencode({'val_id':value,'store_id':store,'store_passwd':password,'v':1,'format':'json'})
    result=read_json(Request('https://'+host+'/validator/api/validationserverAPI.php?'+query))
    if (result.get('status') not in ('VALID','VALIDATED') or result.get('currency')!='BDT' or str(result.get('risk_level','0'))!='0'):
        raise Invalid('The gateway has not confirmed this payment.')
    return str(result.get('tran_id','')),amount(result.get('amount','')),str(result.get('bank_tran_id',''))
