import subprocess
import os

p12 = "data/certs/personal.p12"
pwd = "Mecedora12"

cmd = ["python", "convert_cert.py", p12, pwd]
result = subprocess.run(cmd, capture_output=True, text=True)
print(f"Convert: {result.returncode} {result.stdout}")

key = "data/certs/cert_key.pem"
cert = "data/certs/cert_cert.pem"

if os.path.exists(key) and os.path.exists(cert):
    print(f"Key size: {os.path.getsize(key)}")
    print(f"Cert size: {os.path.getsize(cert)}")

    cmd = ["go", "run", "main.go"]
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)

    import time
    time.sleep(3)

    import urllib.request
    import json

    try:
        req = urllib.request.Request("http://localhost:6789/api/v1/health")
        with urllib.request.urlopen(req) as resp:
            print(f"Health: {resp.read()}")
    except Exception as e:
        print(f"Health error: {e}")

    invoice = {
        "tipo": "alta",
        "factura": {
            "emisor_nif": "53950250R",
            "num_serie": "FV2026/FINAL",
            "fecha_expedicion": "17-04-2026",
            "tipo_factura": "F1",
            "descripcion": "Final test",
            "iva": [{"base": 100, "cuota": 21, "tipo": 21}],
            "importe_total": 121
        },
        "sistema": {
            "nombre": "Test",
            "nif_proveedor": "53950250R",
            "version": "1.0"
        }
    }

    req = urllib.request.Request(
        "http://localhost:6789/api/v1/facturas",
        data=json.dumps(invoice).encode(),
        method="POST"
    )
    req.add_header("Content-Type", "application/json")

    try:
        with urllib.request.urlopen(req) as resp:
            print(f"Invoice: {resp.read()}")
    except Exception as e:
        print(f"Invoice error: {e}")

    proc.terminate()
    proc.wait()
else:
    print("Files not found")