#!/usr/bin/env python3

import requests, base64
# BASE_URL = "http://localhost:5000"  # à adapter
BASE_URL = "http://hagrid:5000"  # à adapter

HEADERS = {
    # "Authorization": f"Bearer {API_TOKEN}",
    "Content-Type": "application/json"
}

SESSION = requests.Session()

def get_ciphertext(name: str) -> bytes:
    """Retourne ciphertext complet (iv + ct) en bytes pour compatibilité."""
    resp = SESSION.post(
        f"{BASE_URL}/get_ciphertext",
        json={"name": name},
        headers=HEADERS,
        timeout=10,
    )
    resp.raise_for_status()
    j = resp.json()
    iv = base64.b64decode(j["iv"])
    ct = base64.b64decode(j["ciphertext"])
    return iv + ct

def is_padding_ok(ciphertext: bytes, name: str) -> bool:
    """Renvoie True/False en appelant l'oracle."""
    iv = ciphertext[:16]
    ct = ciphertext[16:]
    payload = {
        "iv": base64.b64encode(iv).decode(),
        "ciphertext": base64.b64encode(ct).decode(),
        "name": name
    }
    resp = SESSION.post(
        f"{BASE_URL}/is_padding_ok",
        json=payload,
        headers=HEADERS,
        timeout=10,
    )
    resp.raise_for_status()
    j = resp.json()
    return bool(j.get("valid", False))
