import base64
import json
from urllib.request import urlopen, Request
from urllib.error import URLError
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.backends import default_backend

API_URL = "http://localhost:6789"

print("=" * 60)
print("Test: Enviar Factura con Validation")
print("=" * 60)

invoice = {
    "tipo": "alta",
    "factura": {
        "emisor_nif": "53950250R",
        "num_serie": "FV2026/001",
        "fecha_expedicion": "17-04-2026",
        "tipo_factura": "F1",
        "descripcion": "Factura de prueba",
        "destinatario": {
            "nombre": "Cliente Test SL",
            "nif": "B12345678"
        },
        "iva": [
            {"base": 100.00, "cuota": 21.00, "tipo": 21.0}
        ],
        "importe_total": 121.00
    },
    "sistema": {
        "nombre": "VeriFactu API",
        "nif_proveedor": "53950250R",
        "version": "1.0"
    }
}

print("\nEnviando factura...")

req = Request(
    f"{API_URL}/api/v1/facturas",
    data=json.dumps(invoice).encode(),
    method="POST"
)
req.add_header("Content-Type", "application/json")

try:
    with urlopen(req, timeout=30) as response:
        result = json.loads(response.read().decode())
        print(json.dumps(result, indent=2))
except URLError as e:
    print(f"Error HTTP: {e}")
except Exception as e:
    print(f"Error: {type(e).__name__}: {e}")