import base64
import requests
from pathlib import Path

DEFAULT_URL = "https://<RAILWAY_DOMAIN>"  # update this!

class YuroClient:
    """
    Python client library for deploying models and running inference
    via the Yuro backend.
    """

    def __init__(self, api_key: str, base_url: str = DEFAULT_URL):
        self.api_key = api_key
        self.base_url = base_url.rstrip("/")

    # ----------------------------
    # Deploy a model from S3
    # ----------------------------
    def deploy(self, s3_key: str, name: str):
        payload = {"s3_key": s3_key, "name": name}
        r = requests.post(
            f"{self.base_url}/yuro/deploy",
            json=payload,
            headers={"X-API-Key": self.api_key},
            timeout=60,
        )
        r.raise_for_status()
        return r.json()

    # ----------------------------
    # Inference (path)
    # ----------------------------
    def infer_path(self, image_path: str):
        with open(image_path, "rb") as f:
            files = {"image": ("upload.jpg", f.read())}
        r = requests.post(
            f"{self.base_url}/yuro/infer",
            files=files,
            headers={"X-API-Key": self.api_key},
            timeout=60,
        )
        r.raise_for_status()
        return r.json()

    # ----------------------------
    # Inference (bytes)
    # ----------------------------
    def infer_bytes(self, image_bytes: bytes):
        files = {"image": ("upload.jpg", image_bytes)}
        r = requests.post(
            f"{self.base_url}/yuro/infer",
            files=files,
            headers={"X-API-Key": self.api_key},
            timeout=60,
        )
        r.raise_for_status()
        return r.json()

    # ----------------------------
    # Inference (base64)
    # ----------------------------
    def infer_base64(self, b64: str):
        payload = {"image_base64": b64}
        r = requests.post(
            f"{self.base_url}/yuro/infer",
            json=payload,
            headers={"X-API-Key": self.api_key},
            timeout=60,
        )
        r.raise_for_status()
        return r.json()
