"""Official client for the Morgane API: images and text (Python 3.8+, standard library only).

    from morgane import Morgane
    api = Morgane("ma_...")            # or set MORGANE_API_KEY
    png = api.generate("a red fox in the snow, watercolor", width=1024, height=768)
    open("fox.png", "wb").write(png)
    print(api.ask("Explain DNS in two sentences"))
    for piece in api.stream("Write a haiku about the sea"):   # live answer
        print(piece, end="", flush=True)
    first = api.chat("My name is Sam.", remember=True)        # conversation memory
    print(api.ask("What is my name?", conversation_id=first["conversation_id"]))

Command line:  python morgane.py "a red fox in the snow" -o fox.png
Docs: https://aiworkerinfo.com/api
"""
import argparse
import json
import os
import sys
import time
import urllib.error
import urllib.request

__version__ = "1.2.0"
BASE_URL = "https://aiworkerinfo.com/api/v1/public"
RETRYABLE = {429, 502, 503, 504}


class MorganeError(Exception):
    """API error: status (HTTP code, 0 for a failed generation), code (e.g. not_enough_points) and message."""

    def __init__(self, status, code, message, retry_after=None):
        super().__init__(f"{code} ({status}): {message}")
        self.status, self.code, self.message, self.retry_after = status, code, message, retry_after


class Morgane:
    def __init__(self, api_key=None, base_url=None, timeout=60, retries=3):
        self.api_key = api_key or os.environ.get("MORGANE_API_KEY", "")
        if not self.api_key.startswith("ma_"):
            raise ValueError("API key missing or invalid: create one on https://aiworkerinfo.com/workers")
        self.base_url = (base_url or os.environ.get("MORGANE_API_URL") or BASE_URL).rstrip("/")
        self.timeout, self.retries = timeout, retries

    def _request(self, method, path, body=None, raw=False, timeout=None):
        timeout = timeout or self.timeout
        data = None if body is None else json.dumps(body).encode("utf-8")
        for attempt in range(self.retries + 1):
            request = urllib.request.Request(self.base_url + path, data=data, method=method, headers={
                "Authorization": "Bearer " + self.api_key, "Content-Type": "application/json",
                "Accept": "application/json", "User-Agent": "morgane-python/" + __version__})
            try:
                with urllib.request.urlopen(request, timeout=timeout) as response:
                    payload = response.read()
                    return payload if raw else json.loads(payload.decode("utf-8"))
            except urllib.error.HTTPError as error:
                try:
                    info = json.loads(error.read().decode("utf-8"))
                except (ValueError, UnicodeDecodeError):
                    info = {}
                header = error.headers.get("Retry-After") if error.headers else None
                retry_after = float(header) if header and header.replace(".", "", 1).isdigit() else None
                failure = MorganeError(error.code, info.get("error", f"http_{error.code}"), info.get("message", str(error.reason)), retry_after)
                if error.code not in RETRYABLE or attempt >= self.retries:
                    raise failure from None
                time.sleep(min(60, retry_after or 2 ** (attempt + 1)))
            except (urllib.error.URLError, TimeoutError, ConnectionError) as error:
                if attempt >= self.retries:
                    raise MorganeError(0, "network", str(getattr(error, "reason", error))) from None
                time.sleep(2 ** (attempt + 1))

    def me(self):
        """Balance, price per image and whether your worker is connected (free images)."""
        return self._request("GET", "/me")

    def models(self):
        return self._request("GET", "/models")

    def submit(self, prompt, negative=None, width=None, height=None, seed=None, model=None):
        """Start a generation; returns {id, status, cost, free, points, statusUrl}."""
        body = {"prompt": prompt}
        for key, value in (("negative", negative), ("width", width), ("height", height), ("seed", seed), ("model", model)):
            if value is not None:
                body[key] = value
        return self._request("POST", "/images", body)

    def status(self, image_id):
        return self._request("GET", f"/images/{image_id}")

    def file(self, image_id):
        """PNG bytes of a completed image."""
        return self._request("GET", f"/images/{image_id}/file", raw=True)

    def wait(self, image_id, timeout=900, interval=3):
        """Wait for the image and return its PNG bytes."""
        deadline = time.monotonic() + timeout
        while True:
            state = self.status(image_id)
            if state["status"] == "completed":
                return self.file(image_id)
            if state["status"] == "failed":
                raise MorganeError(0, "generation_failed", "The generation failed; the points were refunded.")
            if time.monotonic() > deadline:
                raise MorganeError(0, "timeout", f"Image {image_id} still not ready after {timeout} s.")
            time.sleep(interval)

    def generate(self, prompt, timeout=900, **options):
        """Submit and wait: returns PNG bytes."""
        return self.wait(self.submit(prompt, **options)["id"], timeout=timeout)

    @staticmethod
    def _chat_body(messages, system=None, max_tokens=None, temperature=None, conversation_id=None, remember=None):
        body = {"prompt": messages} if isinstance(messages, str) else {"messages": messages}
        if system is not None and isinstance(messages, str):
            body["system"] = system
        for key, value in (("max_tokens", max_tokens), ("temperature", temperature), ("conversation_id", conversation_id), ("remember", remember)):
            if value is not None:
                body[key] = value
        return body

    def chat(self, messages, system=None, max_tokens=None, temperature=None, timeout=None, conversation_id=None, remember=None):
        """Text model, paid per token. messages: a string or [{"role": "user", "content": "..."}].
        remember=True keeps the conversation on Morgane's side; pass the returned conversation_id next time
        and send only the new message. Returns {message, usage, cost, points, finish, conversation_id?}."""
        body = self._chat_body(messages, system, max_tokens, temperature, conversation_id, remember)
        return self._request("POST", "/chat", body, timeout=timeout or max(self.timeout, 240))

    def ask(self, prompt, **options):
        """Just the answer text."""
        return self.chat(prompt, **options)["message"]["content"]

    def stream(self, messages, timeout=None, **options):
        """Live answer: yields the pieces of text as they are written. The final result
        (usage, cost, points, conversation_id) is then in self.last_result."""
        body = self._chat_body(messages, **options)
        body["stream"] = True
        self.last_result = None
        request = urllib.request.Request(self.base_url + "/chat", data=json.dumps(body).encode("utf-8"), method="POST", headers={
            "Authorization": "Bearer " + self.api_key, "Content-Type": "application/json",
            "Accept": "text/event-stream", "User-Agent": "morgane-python/" + __version__})
        try:
            response = urllib.request.urlopen(request, timeout=timeout or max(self.timeout, 240))
        except urllib.error.HTTPError as error:
            try:
                info = json.loads(error.read().decode("utf-8"))
            except (ValueError, UnicodeDecodeError):
                info = {}
            raise MorganeError(error.code, info.get("error", f"http_{error.code}"), info.get("message", str(error.reason))) from None
        except (urllib.error.URLError, TimeoutError, ConnectionError) as error:
            raise MorganeError(0, "network", str(getattr(error, "reason", error))) from None
        with response:
            for raw in response:
                line = raw.decode("utf-8").strip()
                if not line.startswith("data:") or line == "data: [DONE]":
                    continue
                event = json.loads(line[5:])
                if event.get("type") == "delta":
                    yield event["content"]
                elif event.get("type") == "done":
                    self.last_result = event
                elif event.get("type") == "error":
                    raise MorganeError(0, event.get("error", "unavailable"), event.get("message", ""))

    def conversations(self):
        """Conversations Morgane keeps for your account."""
        return self._request("GET", "/conversations")["conversations"]

    def conversation(self, conversation_id):
        """One kept conversation with its messages."""
        return self._request("GET", f"/conversations/{conversation_id}")

    def delete_conversation(self, conversation_id):
        return self._request("DELETE", f"/conversations/{conversation_id}")


def main(argv=None):
    parser = argparse.ArgumentParser(description="Generate an image with the Morgane API.")
    parser.add_argument("prompt")
    parser.add_argument("-o", "--output", default="morgane.png")
    parser.add_argument("--negative")
    parser.add_argument("--width", type=int)
    parser.add_argument("--height", type=int)
    parser.add_argument("--seed", type=int)
    parser.add_argument("--model")
    parser.add_argument("--key", help="API key (default: MORGANE_API_KEY)")
    args = parser.parse_args(argv)
    try:
        api = Morgane(args.key)
        png = api.generate(args.prompt, negative=args.negative, width=args.width, height=args.height, seed=args.seed, model=args.model)
    except (MorganeError, ValueError) as error:
        print(error, file=sys.stderr)
        return 1
    with open(args.output, "wb") as handle:
        handle.write(png)
    print(args.output)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
