#!/usr/bin/env python3
"""Inspect and control the open Mac Playground without an Isaac Lab environment."""

import argparse
import base64
import binascii
import json
import os
from pathlib import Path
import plistlib
import runpy
import sys
import uuid


MAC_BUNDLE_ID = "com.therobotsimguy.simoji.mac"
IMAGE_SUFFIXES = {
    "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp",
    "image/gif": ".gif", "image/avif": ".avif", "image/heic": ".heic",
    "image/svg+xml": ".svg",
}


class ControlError(RuntimeError):
    pass


def reject_constant(value):
    raise ValueError("Non-finite JSON numbers are not supported.")


def json_object(value):
    try:
        result = json.loads(value, parse_constant=reject_constant)
        json.dumps(result, allow_nan=False)
    except (ValueError, RecursionError):
        raise argparse.ArgumentTypeError("Arguments must be valid JSON with finite numbers.") from None
    if not isinstance(result, dict):
        raise argparse.ArgumentTypeError('Arguments must be a JSON object, for example \'{"action":"list"}\'.')
    return result


def timeout_seconds(value):
    try:
        timeout = float(value)
    except ValueError:
        timeout = 0
    if not 1 <= timeout <= 600:
        raise argparse.ArgumentTypeError("Timeout must be between 1 and 600 seconds.")
    return timeout


def tool_name(value):
    if not value or value != value.strip():
        raise argparse.ArgumentTypeError("Provide the exact tool name shown by tools.")
    return value


def parser():
    result = argparse.ArgumentParser(description=__doc__)
    result.add_argument("--app", type=Path, help="Installed Mac app (default: ~/Applications/Simoji.app, then /Applications/Simoji.app)")
    result.add_argument("--timeout", type=timeout_seconds, default=90, help="Tool reply timeout in seconds (default: 90)")
    commands = result.add_subparsers(dest="command", required=True)
    commands.add_parser("scene", help="Inspect the current scene before changing it")
    tools = commands.add_parser("tools", help="List available tools, or show one tool's full schema")
    tools.add_argument("name", nargs="?", type=tool_name)
    call = commands.add_parser("call", help="Call a tool with a JSON arguments object")
    call.add_argument("name", type=tool_name)
    call.add_argument("arguments", type=json_object)
    return result


def load_connector(app=None):
    candidates = [app.expanduser()] if app is not None else [
        Path.home() / "Applications/Simoji.app", Path("/Applications/Simoji.app"),
    ]
    for candidate in candidates:
        if not candidate.exists():
            continue
        installed = candidate.resolve(strict=True)
        contents = installed / "Contents"
        try:
            info = plistlib.loads((contents / "Info.plist").read_bytes())
        except (OSError, plistlib.InvalidFileException):
            raise ControlError("The selected app has no valid Info.plist.") from None
        if not isinstance(info, dict) or info.get("CFBundleIdentifier") != MAC_BUNDLE_ID:
            raise ControlError("The selected app is not the Simoji Mac app.")
        connector = contents / "Resources/simoji_mcp.py"
        if not connector.is_file() or connector.resolve() != connector:
            raise ControlError("The selected Mac app has no bundled local connector.")
        transport = runpy.run_path(str(connector))
        if any(not callable(transport.get(name)) for name in ("read_manifest", "manifest_for_app", "call_app")):
            raise ControlError("The bundled local connector is incompatible.")
        return installed, transport
    raise ControlError("Install the Mac app, open Playground, and retry. Use --app if it is installed elsewhere.")


def connection_for_app(app, transport):
    if explicit := os.environ.get("SIMOJI_MCP_CONNECTION"):
        manifest = Path(explicit).expanduser()
        transport["read_manifest"](manifest, expected_app=app)
        return manifest
    known = [
        Path.home() / "Library/Caches/SimojiMCP/connection.json",
        Path.home() / "Library/Containers" / MAC_BUNDLE_ID / "Data/Library/Caches/SimojiMCP/connection.json",
    ]
    for manifest in known:
        try:
            transport["read_manifest"](manifest, expected_app=app)
            return manifest
        except (OSError, ValueError, RecursionError):
            continue
    # Older installations can use a UUID-named sandbox. Only inspect those
    # containers if neither normal location provides the selected app's listener.
    manifest = transport["manifest_for_app"](app)
    transport["read_manifest"](manifest, expected_app=app)
    return manifest


def save_image(data, mime_type):
    if not isinstance(data, str):
        raise ControlError("The app returned invalid image data.")
    try:
        decoded = base64.b64decode(data, validate=True)
    except (ValueError, binascii.Error):
        raise ControlError("The app returned invalid image data.") from None
    directory = Path.home() / "simoji-work/simoji-control"
    directory.mkdir(mode=0o700, parents=True, exist_ok=True)
    if directory.is_symlink():
        raise ControlError("The image output directory must not be a symbolic link.")
    target = directory / ("image-" + uuid.uuid4().hex + IMAGE_SUFFIXES.get(mime_type, ".image"))
    fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
    with os.fdopen(fd, "wb") as output:
        output.write(decoded)
    return str(target)


def image_paths(value):
    """Keep image payloads out of terminal output, including embedded resources."""
    if isinstance(value, list):
        return [image_paths(item) for item in value]
    if not isinstance(value, dict):
        return value
    mime_type = value.get("mimeType", "")
    key = "data" if value.get("type") == "image" else (
        "blob" if isinstance(mime_type, str) and mime_type.startswith("image/") and "blob" in value else None
    )
    if key is not None:
        target = save_image(value.get(key), mime_type)
        return {**{name: image_paths(item) for name, item in value.items() if name != key}, "path": target}
    return {name: image_paths(item) for name, item in value.items()}


def call(transport, app, manifest, method, params, timeout):
    try:
        return transport["call_app"](method, params, manifest, timeout, expected_app=app)
    except Exception as error:
        rpc_error = transport.get("RPCError")
        if isinstance(rpc_error, type) and isinstance(error, rpc_error):
            raise ControlError(str(error)) from None
        raise


def run(args):
    app, transport = load_connector(args.app)
    try:
        manifest = connection_for_app(app, transport)
    except Exception as error:
        rpc_error = transport.get("RPCError")
        if isinstance(rpc_error, type) and isinstance(error, rpc_error):
            raise ControlError(str(error)) from None
        raise
    if args.command == "tools":
        result = call(transport, app, manifest, "tools/list", {}, args.timeout)
        tools = result["tools"]
        if args.name:
            for tool in tools:
                if tool.get("name") == args.name:
                    return image_paths(tool), False
            raise ControlError("Unknown tool. Run tools to see the available names.")
        return [{"name": tool["name"], "description": tool.get("description", "")} for tool in tools], False
    name = "get_scene_state" if args.command == "scene" else args.name
    arguments = {} if args.command == "scene" else args.arguments
    result = call(transport, app, manifest, "tools/call", {"name": name, "arguments": arguments}, args.timeout)
    output = image_paths(result)
    content = output.get("content", [])
    if len(content) == 1 and content[0].get("type") == "text":
        text = content[0].get("text", "")
        try:
            output = json.loads(text, parse_constant=reject_constant)
        except (ValueError, RecursionError):
            output = text
    return output, bool(result.get("isError"))


def main(argv=None):
    args = parser().parse_args(argv)
    try:
        output, failed = run(args)
        print(json.dumps(output, ensure_ascii=False, allow_nan=False, indent=2))
        return 1 if failed else 0
    except (ControlError, OSError, ValueError, KeyError, TypeError, RecursionError) as error:
        print("Simoji control: " + str(error), file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())
