import requests
import time
from flask import current_app

PAKET24_SERVICE_CODE = 26


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

    Args:
        order_number: e-računi order number (e.g. 'S1001')
        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:
        barcode string
    """
    api_url = current_app.config['PAKET24_API_URL']
    api_key = current_app.config['PAKET24_API_KEY']

    shipment_id = f"{order_number}{int(time.time())}"
    additional_services = [30, 32]
    if cod_amount:
        additional_services.append(9)

    payload = {
        "shipments": [{
            "shipment_id": shipment_id,
            "service_code": PAKET24_SERVICE_CODE,
            "additional_services": additional_services,
            "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}/shipment/create_shipment_orders",
        json=payload,
        headers=headers,
        timeout=30,
    )
    resp.raise_for_status()
    data = resp.json()
    return data['shipments'][0]['barcode']


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

    Returns:
        ZPL string
    """
    api_url = current_app.config['PAKET24_API_URL']
    api_key = current_app.config['PAKET24_API_KEY']
    headers = {"Authorization": f"Bearer {api_key}"}
    resp = requests.get(
        f"{api_url}/shipment/get_shipping_labels",
        params={"barcode": barcode},
        headers=headers,
        timeout=30,
    )
    resp.raise_for_status()
    return resp.json()['PackageLabelString']
