"""The images app's tool as an MCP server over stdio: each call asks Ivy's images endpoint,
which makes the images on Ivy's provider accounts and saves them to the space. Standard
library only: the sandbox installs nothing."""

import http.client
import json
import os
import socket
import sys
import threading
import urllib.parse
from pathlib import Path

PROTOCOL_VERSION = "2025-06-18"
# Past the endpoint's 105 s deadline, within an agent's 120 s tool call.
TIMEOUT_SECONDS = 110
HERE = Path(__file__).resolve().parent
# Agents read the tool's description from the app's manifest, not from this list.
TOOLS = [
    {
        "name": "generate_image",
        "inputSchema": json.loads((HERE / "tools" / "generate_image.json").read_text("utf-8")),
    }
]
# Ivy shows the files a result names here under the agent's reply.
MADE_FILES = "ivy/files"

write_lock = threading.Lock()


class ToolError(Exception):
    pass


class UnixConnection(http.client.HTTPConnection):
    def __init__(self, address):
        super().__init__("ivy-api", timeout=TIMEOUT_SECONDS)
        self.address = address

    def connect(self):
        self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        self.sock.settimeout(self.timeout)
        self.sock.connect(self.address)


def connection():
    url = os.environ.get("IVY_API_URL", "")
    if url.startswith("@"):
        return UnixConnection("\0" + url[1:])
    if url.startswith("/"):
        return UnixConnection(url)
    parts = urllib.parse.urlsplit(url)
    if parts.scheme == "http" and parts.hostname:
        return http.client.HTTPConnection(parts.hostname, parts.port, timeout=TIMEOUT_SECONDS)
    raise ToolError("this app can't reach Ivy here (no IVY_API_URL)")


def images_path():
    ids = [
        urllib.parse.quote(os.environ.get(name, ""), safe="")
        for name in ("IVY_ORGANISATION_ID", "IVY_WORKSPACE_ID", "IVY_APP_ID", "IVY_INSTANCE_ID")
    ]
    return "/v1/organisations/{}/spaces/{}/apps/{}/instances/{}/images".format(*ids)


def generate_image(args):
    properties = TOOLS[0]["inputSchema"]["properties"]
    request = {key: args[key] for key in properties if args.get(key) is not None}
    body = json.dumps(request).encode()
    conn = connection()
    try:
        conn.request(
            "POST",
            images_path(),
            body=body,
            headers={"Content-Type": "application/json", "Content-Length": str(len(body))},
        )
        response = conn.getresponse()
        text = response.read().decode("utf-8", "replace")
    except (OSError, http.client.HTTPException) as error:
        raise ToolError(f"Ivy didn't answer: {error!r}") from None
    finally:
        conn.close()
    try:
        answer = json.loads(text)
    except ValueError:
        answer = {}
    if response.status != 200:
        error = answer.get("error", {}) if isinstance(answer, dict) else {}
        code = error.get("code", f"http_{response.status}")
        raise ToolError(f"{code}: {error.get('message', 'no images were made')}")
    images = answer["images"]
    return (
        {
            "model": answer["model"],
            "images": [
                {"name": image["name"], "path": image["path"], "link": f"ivy-file:{image['file_id']}"}
                for image in images
            ],
        },
        [{"file_id": image["file_id"]} for image in images],
    )


HANDLERS = {"generate_image": generate_image}


def send(message):
    line = json.dumps(message, ensure_ascii=False) + "\n"
    with write_lock:
        sys.stdout.write(line)
        sys.stdout.flush()


def call_tool(request_id, params):
    handler = HANDLERS.get(params.get("name"))
    made = []
    try:
        if handler is None:
            raise ToolError(f"no tool {params.get('name')!r}")
        result, made = handler(params.get("arguments") or {})
        content, is_error = json.dumps(result, ensure_ascii=False), False
    except ToolError as error:
        content, is_error = str(error), True
    except (KeyError, TypeError, ValueError) as error:
        content, is_error = f"unexpected input or answer: {error!r}", True
    result = {"content": [{"type": "text", "text": content}], "isError": is_error}
    if made:
        result["_meta"] = {MADE_FILES: made}
    send({"jsonrpc": "2.0", "id": request_id, "result": result})


def handle(message):
    method, request_id = message.get("method"), message.get("id")
    if request_id is None:
        return
    if method == "tools/call":
        threading.Thread(
            target=call_tool, args=(request_id, message.get("params") or {}), daemon=True
        ).start()
        return
    if method == "initialize":
        result = {
            "protocolVersion": PROTOCOL_VERSION,
            "capabilities": {"tools": {}},
            "serverInfo": {"name": "images", "version": "1.0.0"},
        }
    elif method == "tools/list":
        result = {"tools": TOOLS}
    elif method == "ping":
        result = {}
    else:
        send(
            {
                "jsonrpc": "2.0",
                "id": request_id,
                "error": {"code": -32601, "message": f"no method {method!r}"},
            }
        )
        return
    send({"jsonrpc": "2.0", "id": request_id, "result": result})


def main():
    for line in sys.stdin:
        line = line.strip()
        if not line:
            continue
        try:
            message = json.loads(line)
        except ValueError:
            continue
        if isinstance(message, dict):
            handle(message)


if __name__ == "__main__":
    main()
