"""Ghost Deploy server-side Python client v0.1.0. Python 3.10+, standard library only."""
import json
import re
from urllib.request import Request, build_opener, HTTPRedirectHandler
from urllib.error import HTTPError


class GhostDeployError(Exception):
    def __init__(self, status, code=None):
        super().__init__(f"Ghost Deploy request failed ({status}).")
        self.status, self.code = status, code


class _NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


class _Client:
    def _request(self, path, method="GET", data=None, headers=None):
        request = Request(self.base + path, data=data, method=method,
                          headers={**self.headers, **(headers or {})})
        try:
            with build_opener(_NoRedirect).open(request, timeout=60) as response:
                body = json.load(response)
                if body.get("status") is not True:
                    raise GhostDeployError(response.status, body.get("code"))
                return body
        except HTTPError as error:
            raise GhostDeployError(error.code) from None


class SpacesClient(_Client):
    """Use only in trusted server code; permanent Space secrets must stay private."""
    def __init__(self, access_key_id, secret_access_key):
        if not access_key_id or not secret_access_key:
            raise ValueError("A matching Space key pair is required.")
        self.base = "https://spaces.ghostdeploy.com/v1/objects"
        self.headers = {"X-GhostDeploy-Access-Key": access_key_id,
                        "X-GhostDeploy-Access-Secret": secret_access_key}

    def list(self):
        return self._request("")

    def upload(self, path, data, content_type="application/octet-stream"):
        if not isinstance(data, bytes) or not data:
            raise ValueError("Nonempty bytes are required; use an S3 SDK for large files.")
        return self._request("", "PUT", data, {"Content-Type": content_type,
            "X-GhostDeploy-Object-Path": path, "X-GhostDeploy-Upload-Size": str(len(data))})

    def remove(self, object_id):
        if not re.fullmatch(r"[a-fA-F0-9-]{36}", object_id):
            raise ValueError("Use the object UUID returned by the API.")
        return self._request("/" + object_id, "DELETE")


class GhostDeployClient(_Client):
    def __init__(self, token, workspace_id):
        if not token or not re.fullmatch(r"\d+", str(workspace_id)):
            raise ValueError("Workspace public ID and API token are required.")
        self.base = f"https://ghostdeploy.com/api/v1/workspaces/{workspace_id}"
        self.headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}

    def applications(self):
        return self._request("/applications")

    def create_application(self, configuration, idempotency_key):
        if not re.fullmatch(r"[a-zA-Z0-9._:-]{16,200}", idempotency_key):
            raise ValueError("A 16–200 character idempotency key is required.")
        return self._request("/applications", "POST", json.dumps(configuration).encode(),
                             {"Idempotency-Key": idempotency_key})

    def deploy(self, stage_id, rebuild=False):
        if not re.fullmatch(r"[a-fA-F0-9-]{36}", stage_id):
            raise ValueError("Use the application-stage UUID.")
        return self._request(f"/applications/{stage_id}/action", "POST",
                             json.dumps({"action": "rebuild" if rebuild else "redeploy"}).encode())
