import base64
import requests
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization

# Caminhos dos arquivos
private_key_path = "/home/joaomonezi/Consultme/private_key.pem"
public_key_path = "public_key.pem"

# 1. Carregar chave privada do negócio
with open(private_key_path, "rb") as key_file:
    private_key = serialization.load_pem_private_key(
        key_file.read(),
        password=None,  # coloque a senha aqui se sua chave for protegida
    )

# 2. Ler conteúdo da chave pública do endpoint (que será assinada)
with open(public_key_path, "rb") as f:
    public_key_data = f.read()

# 3. Assinar a chave pública com a chave privada
signature = private_key.sign(
    public_key_data,
    padding.PKCS1v15(),
    hashes.SHA256()
)

# 4. Codificar assinatura em base64 para enviar na API
signature_b64 = base64.b64encode(signature).decode()

# 5. Chave pública em string para enviar (PEM format)
public_key_str = public_key_data.decode()

# 6. Montar JSON para upload
payload = {
    "public_key": public_key_str,
    "signature": signature_b64
}

# 7. Fazer upload via API (exemplo genérico, ajuste URL e headers)
api_url = "https://consultme.grupoginseng.com.br/v1/business/public_key"
headers = {
    "Authorization": "EAAe3eozOvZCMBO5vngFSqhg823ohKbusZCz2kbkjsrOZAGcDOOnsXQcK17KGu8Gy6oANKHdpT0ZAIJ7422VtZClrdcGNugMXratBvct2xbyo1MuBHZAowFuJq2wsWYAXoR6jypNTuXsHcYwfTeojY5AXsBTOILQEmeqZClzZAvFL7ZBhf51Pku6P2TMAjFdPzeovDZCWtdTbfB4MNTOkDlxkwjSuDxl8ktxoCXH8C52p88azU2casUEqQZD",
    "Content-Type": "application/json"
}

response = requests.post(api_url, json=payload, headers=headers)

if response.status_code == 200:
    print("Chave pública assinada enviada com sucesso!")
else:
    print(f"Erro no upload: {response.status_code} - {response.text}")
