import easypost

from functions.Response import API_Error
from functions.Shipments.Convert import (convertCarrier, convertRate,
                                         deEmojify, getShipmentPlatformCreds,
                                         saveShipment)


def getCarriers(enterpriseId:str):
    creds = getShipmentPlatformCreds(enterpriseId, "EASYPOST")
    carriers:list[dict] = []
    if creds:
        if creds.get("enabled") == False: return carriers
        try:
            easypost.api_key = creds.get('apiKey')
            carriersAccounts = easypost.CarrierAccount.all()
            carriers = [convertCarrier(
                id=carrier.get('id'), 
                platformId="EASYPOST", 
                name=carrier.get('readable'), 
                description= carrier.get('description'),
                platformName="EasyPost",
                ) for carrier in carriersAccounts]
        except Exception as e:
            print(e)
            # raise API_Error(str(e), 500)
    return carriers

def getRates(enterpriseId:str, fromAddress:dict, order:dict, parcel:dict, carrierId:str):
    creds = getShipmentPlatformCreds(enterpriseId, "EASYPOST")
    rates = []
    if creds:
        try:
            toAddress = order.get('shippingAddress')
            easypost.api_key = creds.get('apiKey')
            fromAddress  = dict(
                name=fromAddress.get('name'),
                street1 = fromAddress.get('address1'),
                street2 = fromAddress.get('address2'),
                state = fromAddress.get('state'),
                city = fromAddress.get('city'),
                zip = fromAddress.get('zip'),
                country = fromAddress.get('country'),
                phone = fromAddress.get('phone'),
            )
            toAddress  = dict(
                name=toAddress.get('name'),
                street1 = toAddress.get('address1'),
                street2 = toAddress.get('address2'),
                city = toAddress.get('city'),
                state = toAddress.get('state'),
                zip = toAddress.get('zip'),
                country = toAddress.get('country'),
                phone = toAddress.get('phone') if toAddress.get('phone') else fromAddress.get('phone'),
                verify=False,
                verify_strict=False
            )
            parcel = dict(
                length  = parcel.get('length'),
                width  = parcel.get('width'),
                height  = parcel.get('height'),
                weight  = parcel.get('weight'),
            )
            shipment = easypost.Shipment.create(
                reference=order.get('id'),
                to_address = toAddress,
                from_address = fromAddress,
                parcel = parcel,
                options=dict(label_size="4x6"),
                carrier_accounts=[carrierId],
                address_validation_level="0",
                customs_info=easypost.CustomsInfo.create(
                     customs_items=[easypost.CustomsItem.create(
                    description = "Clothing",
                    quantity = "1",
                    weight= parcel.get('weight'),
                    value = order.get("grandTotal") if order.get("grandTotal") else 1,
                    origin_country = fromAddress.get('country'),
                    hs_tariff_number="610910"
                    )],
                eel_pfc='NOEEI 30.37(a)',
                contents_type='merchandise',
                restriction_type='none',
                restriction_comments='none',
                non_delivery_option="return",
                customs_certify='true',
                customs_signer="Adam Arizaga" if enterpriseId == "60D7GFDlMFFd6IsK1e58" else None,
                contents_explanation="",
                ),
            )
            rates = shipment.get('rates')
            if not rates:
                raise API_Error("No rates available", 500)
            return [convertRate(
                id=rate.get('id'), 
                name = rate.get('service'), 
                carrierId=rate.get('carrier_account_id'), 
                carrierName=rate.get('carrier'),
                cost=rate.get('rate'), 
                deliveryDays=rate.get('delivery_days'), 
                shipmentId=rate.get('shipment_id'),
                platformId="EASYPOST",
                platformName="EasyPost",
                serviceId =rate.get("service")
                ) for rate in rates]
        except Exception as e:
            print(e)
            raise API_Error(str(e))
    return []

def createShipment(uid:str, order:dict, rate:dict, insurance=False):
    enterpriseId = order.get('enterpriseId')
    creds = getShipmentPlatformCreds(enterpriseId, "EASYPOST")
    try:
        easypost.api_key = creds.get('apiKey')
        shipment = easypost.Shipment.retrieve(rate.get('shipmentId'))
        shipment = shipment.buy(rate=rate)
        shipment = shipment.to_dict()
        shipment = saveShipment(
            uid=uid,
            enterpriseId=enterpriseId,
            platformId="EASYPOST",
            platformName="EasyPost",
            orderId= order.get('id'),
            platformOrderId= order.get('platformOrderId'),
            image = shipment.get('postage_label', {}).get('label_url'),
            carrierName = shipment.get('selected_rate').get('carrier'),
            platformShipmentId= shipment.get('id'),
            pdf= shipment.get('postage_label', {}).get('label_pdf_url'),
            cost=shipment.get('selected_rate', {}).get('rate'), 
            trackingCode=shipment.get('tracking_code'),
            currency=shipment.get('selected_rate', {}).get('currency', 'USD'),
            carrierService= shipment.get('selected_rate', {}).get('service'),
            trackingUrl= shipment.get('tracker', {}).get('public_url'),
            userUid= order.get('uid'),
            routedOrderIds = order.get("routedOrderIds", [])
        )
        return shipment
    except Exception as e:
        raise API_Error(str(e), 500)
        

