"""Permission-aware Bot API proxy.

Checks agent permissions before sending messages through the Bot API.
Credentials are stored in admin_dir (invisible to sub-agents).

Usage:
    python scripts/bot_client_proxy.py --agent-id <id> send --message "..."
"""

import argparse
import json
import os
import subprocess
import sys

def _find_manager_scripts() -> str:
    """Locate sophnet-customer-agent-manager/scripts at runtime."""
    skill_name = "sophnet-customer-agent-manager"
    subdir = "scripts"
    candidates = [
        os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", skill_name, subdir),
        os.path.join(os.path.expanduser("~"), ".openclaw", "skills", skill_name, subdir),
        os.path.join("/app", "skills", skill_name, subdir),
    ]
    for path in candidates:
        resolved = os.path.realpath(path)
        if os.path.isdir(resolved):
            return resolved
    return os.path.realpath(candidates[0])


sys.path.insert(0, _find_manager_scripts())
from permission_store import _DEFAULT_ADMIN_DIR, get_permission

_BOT_CREDENTIALS_FILENAME = "bot_credentials.json"


def _output(data: dict) -> None:
    print(json.dumps(data, ensure_ascii=False, indent=2))
    sys.exit(0 if data.get("status") == "ok" else 1)


def _load_credentials(admin_dir: str, agent_id: str) -> dict | None:
    path = os.path.join(admin_dir, agent_id, _BOT_CREDENTIALS_FILENAME)
    if not os.path.isfile(path):
        return None
    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)


def send_message(
    agent_id: str,
    message: str,
    admin_dir: str = _DEFAULT_ADMIN_DIR,
) -> dict:
    """Send a message through Bot API with permission checking."""
    permission = get_permission(admin_dir, agent_id)
    if permission is None:
        return {
            "status": "error",
            "action": "bot_client_send",
            "message": f"未找到 agent '{agent_id}' 的权限记录",
            "fix": "请先使用 agent_manager_cli.py create 创建该 agent",
        }

    credentials = _load_credentials(admin_dir, agent_id)
    if credentials is None:
        return {
            "status": "error",
            "action": "bot_client_send",
            "message": f"未找到 agent '{agent_id}' 的 Bot API 凭据",
            "fix": "请先执行 bot_client_setup.py setup --mode proxy",
        }

    url = credentials["url"]
    secret = credentials["secret"]
    remote_agent_id = credentials["remote_agent_id"]

    # Use agent_id as a stable chatId so the server always resolves to the
    # same sessionKey.  Previously we saved the server's sessionKey and sent
    # it back as chatId, but sessionKey is a composite key that already
    # contains chatId — feeding it back caused infinite key growth and a new
    # session on every request.
    payload = {
        "agentId": remote_agent_id,
        "senderId": agent_id,
        "text": message,
        "chatId": agent_id,
        "senderPermissions": {
            "operations": permission.get("operations", {}),
            "scope": permission.get("scope", {}),
        },
    }

    try:
        result = subprocess.run(
            [
                "curl", "-s", "-X", "POST", url,
                "-H", "Content-Type: application/json",
                "-H", f"Authorization: Bearer {secret}",
                "-d", json.dumps(payload, ensure_ascii=False),
            ],
            capture_output=True,
            text=True,
            timeout=120,
        )
    except subprocess.TimeoutExpired:
        return {
            "status": "error",
            "action": "bot_client_send",
            "message": "Bot API 请求超时 (120s)",
        }

    if result.returncode != 0:
        return {
            "status": "error",
            "action": "bot_client_send",
            "message": f"curl 请求失败 (exit {result.returncode})",
            "stderr": result.stderr,
        }

    try:
        response = json.loads(result.stdout)
    except json.JSONDecodeError:
        return {
            "status": "error",
            "action": "bot_client_send",
            "message": "Bot API 返回了无法解析的响应",
            "raw": result.stdout[:500],
        }

    return {
        "status": "ok",
        "action": "bot_client_send",
        "reply": response.get("reply", ""),
        "sessionKey": response.get("sessionKey", ""),
    }


def main():
    parser = argparse.ArgumentParser(description="Permission-aware Bot API proxy")
    parser.add_argument("--agent-id", required=True, help="Agent identifier")
    parser.add_argument(
        "--admin-dir", default=_DEFAULT_ADMIN_DIR,
        help="Admin directory (permissions + credentials)",
    )

    subparsers = parser.add_subparsers(dest="command", required=True)

    send_parser = subparsers.add_parser("send", help="Send message via Bot API")
    send_parser.add_argument("--message", required=True, help="Message to send")

    args = parser.parse_args()

    if args.command == "send":
        result = send_message(
            agent_id=args.agent_id,
            message=args.message,
            admin_dir=args.admin_dir,
        )
        _output(result)


if __name__ == "__main__":
    main()
