import requests
from flask import current_app


def create_shipment(order_number: str, recipient: dict,
                    weight_kg: float = 0.5, cod_amount=None) -> str:
    """Create a DPD shipment.

    Args:
        order_number: e-računi order number
        recipient: dict with keys name, street, city, postal_code, country,
                   and optionally email, phone
        weight_kg: package weight in kilograms
        cod_amount: cash-on-delivery amount, or None

    Returns:
        pl_number barcode string
    """
    api_url = current_app.config['DPD_API_URL']
    api_key = current_app.config['DPD_API_KEY']

    parcel_type = 'D-COD-B2C' if cod_amount else 'D-B2C'
    payload = {
        "order_number": order_number,
        "parcel_type": parcel_type,
        "recipient": {
            "name": recipient['name'],
            "street": recipient['street'],
            "city": recipient['city'],
            "postal_code": recipient['postal_code'],
            "country": recipient['country'],
            "email": recipient.get('email', ''),
            "phone": recipient.get('phone', ''),
        },
        "weight": weight_kg,
        "cod_amount": cod_amount,
    }
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    }
    resp = requests.post(
        f"{api_url}/parcel/parcel_import",
        json=payload,
        headers=headers,
        timeout=30,
    )
    resp.raise_for_status()
    return resp.json()['pl_number']


def get_label(barcode: str) -> str:
    """Fetch ZPL label for a DPD barcode.

    Returns:
        ZPL string
    """
    api_url = current_app.config['DPD_API_URL']
    api_key = current_app.config['DPD_API_KEY']
    headers = {"Authorization": f"Bearer {api_key}"}
    resp = requests.get(
        f"{api_url}/parcel/parcel_print",
        params={"pl_number": barcode},
        headers=headers,
        timeout=30,
    )
    resp.raise_for_status()
    return resp.text
