#!/usr/bin/env python3
"""List installed skills, list Sophclaw friends, preview and send a skill intro DM."""

from __future__ import annotations

import argparse
import base64
import hashlib
import io
import json
import os
import re
import shlex
import subprocess
import sys
import tarfile
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path, PurePosixPath
from typing import Any, Dict, Iterable, List, Optional, Pattern, Set, Tuple


DEFAULT_BASE_URL = "https://yagent.sophnet.com/api"
DEFAULT_TIMEOUT = 30
JWT_PATH = "/home/node/.openclaw/jwt.json"
DEFAULT_SKILLS_COMMAND = "openclaw skills list --json"
DEFAULT_SKILL_INFO_COMMAND_TEMPLATE = "openclaw skills info {skill} --json"
STORE_SKILLS_PATH = "/open-apis/skill-store/skills"
MAX_CUSTOM_SKILL_PACK_BYTES = 1024 * 1024
SKILL_SHARE_OPEN = "[claw-skill-share]"
SKILL_SHARE_CLOSE = "[/claw-skill-share]"
MAX_SENSITIVE_SCAN_BYTES = 512 * 1024
MAX_SENSITIVE_FINDINGS = 20
SENSITIVE_DIR_NAMES = {
    ".git",
    ".hg",
    ".svn",
    "__pycache__",
    "node_modules",
    ".venv",
    "venv",
    "dist",
    "build",
}
SENSITIVE_FILE_NAMES = {
    ".env",
    ".env.local",
    ".env.production",
    ".npmrc",
    ".pypirc",
    "credentials.json",
    "service-account.json",
    "id_rsa",
    "id_dsa",
    "id_ecdsa",
    "id_ed25519",
}
# 额外的敏感文件名模式（包含这些关键词的文件名）
SENSITIVE_FILE_NAME_PATTERNS = (
    "token",
    "secret",
    "password",
    "passwd",
    "credential",
    "private_key",
    "privatekey",
    "access_key",
    "apikey",
    "api_key",
)
SENSITIVE_FILE_SUFFIXES = (".pem", ".key", ".p12", ".pfx")
JsonDict = Dict[str, Any]
StringDict = Dict[str, str]


SENSITIVE_CONTENT_PATTERNS: Tuple[Tuple[Pattern[str], str], ...] = (
    (
        re.compile(r"-----BEGIN (?:RSA |DSA |EC |OPENSSH |)?PRIVATE KEY-----"),
        "包含私钥块",
    ),
    (re.compile(r"\bAKIA[0-9A-Z]{16}\b"), "疑似 AWS Access Key"),
    (re.compile(r"\bgh[pousr]_[A-Za-z0-9_]{30,}\b"), "疑似 GitHub Token"),
    (re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{20,}\b"), "疑似 Slack Token"),
    (re.compile(r"\bsk-[A-Za-z0-9]{32,}\b"), "疑似 API Key"),
    (
        re.compile(
            r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}"
            r"\.[A-Za-z0-9_-]{10,}\b"
        ),
        "疑似 JWT",
    ),
    (
        re.compile(
            r"(?i)\b(?:api[_-]?key|secret(?:[_-]?key)?|access[_-]?token|auth[_-]?token|"
            r"bearer[_-]?token|client[_-]?secret|private[_-]?key|password|passwd|pwd)\b"
            r"\s*[:=]\s*['\"]?[A-Za-z0-9_./+=:@-]{16,}"
        ),
        "疑似秘钥字段赋值",
    ),
)


class AppError(RuntimeError):
    pass


def configure_stdio() -> None:
    for name in ("stdout", "stderr"):
        stream = getattr(sys, name, None)
        if stream is not None and hasattr(stream, "reconfigure"):
            stream.reconfigure(encoding="utf-8", errors="replace")


def print_json(payload: JsonDict) -> None:
    print(json.dumps(payload, ensure_ascii=False, indent=2))


def normalize_base_url(url: str) -> str:
    value = (url or "").strip().rstrip("/")
    if not value:
        raise AppError("base-url 不能为空")
    if not value.startswith(("http://", "https://")):
        raise AppError("base-url 必须以 http:// 或 https:// 开头")
    return value


def read_bearer_token(jwt_path: str) -> str:
    try:
        with open(jwt_path, "r", encoding="utf-8") as fp:
            data = json.load(fp)
    except OSError as exc:
        raise AppError(f"无法读取 JWT 文件 {jwt_path}: {exc}") from exc
    except json.JSONDecodeError as exc:
        raise AppError(f"JWT 文件不是有效 JSON: {jwt_path}: {exc}") from exc

    token = data.get("web_jwt") if isinstance(data, dict) else None
    if not isinstance(token, str) or not token.strip():
        raise AppError(f"JWT 文件缺少有效 web_jwt 字段: {jwt_path}")
    token = token.strip()
    if token.lower().startswith("bearer "):
        token = token[7:].strip()
    return token


def jwt_exp_unix(token: str) -> Optional[int]:
    try:
        parts = token.split(".")
        if len(parts) != 3:
            return None
        payload = parts[1] + "=" * (-len(parts[1]) % 4)
        raw = base64.urlsafe_b64decode(payload.encode("ascii"))
        data = json.loads(raw)
        exp = data.get("exp")
        return int(exp) if isinstance(exp, (int, float)) else None
    except Exception:
        return None


def ensure_jwt_valid_for_use(
    token: str,
    jwt_path: str,
    clock_skew_sec: int = 60,
) -> None:
    exp = jwt_exp_unix(token)
    if exp is None:
        return
    now = int(time.time())
    if now >= exp + clock_skew_sec:
        raise AppError(f"JWT 已过期，请重新登录后刷新 {jwt_path}")


def make_headers(token: str, content_type: Optional[str] = None) -> StringDict:
    headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"}
    if content_type:
        headers["Content-Type"] = content_type
    return headers


def http_error_hint(http_code: int, body: str) -> str:
    if http_code == 401:
        return f"（请检查或刷新 {JWT_PATH} 中的 web_jwt）"
    try:
        data = json.loads(body)
    except json.JSONDecodeError:
        return ""
    msg = str(data.get("message", ""))
    status = data.get("status")
    if status == 20002 or "权限不足" in msg:
        return "（当前账号可能没有权限向该会话发送消息）"
    return ""


def request_json(
    method: str,
    url: str,
    token: Optional[str],
    timeout: int,
    payload: Optional[JsonDict] = None,
) -> JsonDict:
    body = None
    headers: StringDict = {"Accept": "application/json"}
    if token:
        headers.update(make_headers(token))
    if payload is not None:
        body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
        headers["Content-Type"] = "application/json"
    req = urllib.request.Request(url=url, data=body, headers=headers, method=method)
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            raw = resp.read().decode("utf-8", errors="replace")
    except urllib.error.HTTPError as exc:
        err_body = exc.read().decode("utf-8", errors="replace")
        hint = http_error_hint(exc.code, err_body)
        raise AppError(f"HTTP {exc.code} {url}: {err_body}{hint}") from exc
    except urllib.error.URLError as exc:
        raise AppError(f"请求失败 {url}: {exc}") from exc

    try:
        data = json.loads(raw)
    except json.JSONDecodeError as exc:
        raise AppError(f"接口返回不是有效 JSON: {url}: {exc}\n{raw}") from exc
    if isinstance(data, dict) and data.get("status") not in (None, 0):
        status = data.get("status")
        message = data.get("message")
        raise AppError(f"接口错误: status={status} message={message!r}")
    return data if isinstance(data, dict) else {"result": data}


def unwrap_result(data: JsonDict) -> Any:
    return data.get("result") if "result" in data else data


def extract_json_object(text: str) -> Optional[JsonDict]:
    """Extract the first complete JSON object from noisy CLI output."""
    for start, ch in enumerate(text):
        if ch != "{":
            continue
        depth = 0
        in_string = False
        escaped = False
        for idx in range(start, len(text)):
            c = text[idx]
            if in_string:
                if escaped:
                    escaped = False
                elif c == "\\":
                    escaped = True
                elif c == '"':
                    in_string = False
                continue
            if c == '"':
                in_string = True
            elif c == "{":
                depth += 1
            elif c == "}":
                depth -= 1
                if depth == 0:
                    candidate = text[start:idx + 1]
                    try:
                        data = json.loads(candidate)
                    except json.JSONDecodeError:
                        break
                    return data if isinstance(data, dict) else None
    return None


def strip_ansi(text: str) -> str:
    out: List[str] = []
    i = 0
    while i < len(text):
        if text[i] == "\x1b" and i + 1 < len(text) and text[i + 1] == "[":
            i += 2
            while i < len(text) and not text[i].isalpha():
                i += 1
            i += 1
            continue
        out.append(text[i])
        i += 1
    return "".join(out)


def parse_plain_skills_table(text: str) -> JsonDict:
    """Best-effort parser for `openclaw skills list` table output."""
    skills: List[JsonDict] = []
    current: Optional[JsonDict] = None
    for raw_line in strip_ansi(text).splitlines():
        line = raw_line.rstrip()
        if not line.startswith("│") or line.startswith("│ Status"):
            continue
        parts = [part.strip() for part in line.strip("│").split("│")]
        if len(parts) < 4:
            continue
        status_cell, skill_cell, desc_cell, source_cell = parts[:4]
        border_chars = {"─", "┬", "┴", "┼", " "}
        if set(status_cell + skill_cell + desc_cell + source_cell) <= border_chars:
            continue
        if status_cell or skill_cell or source_cell:
            if skill_cell:
                tokens = skill_cell.split()
                if tokens and not any(ch.isalnum() for ch in tokens[0]):
                    tokens = tokens[1:]
                name = " ".join(tokens).strip()
            else:
                name = ""
            if not name:
                continue
            current = {
                "name": name,
                "skillKey": name,
                "description": desc_cell,
                "source": source_cell,
                "eligible": "ready" in status_cell,
                "disabled": "disabled" in status_cell,
                "blockedByAllowlist": "blocked" in status_cell,
            }
            skills.append(current)
        elif current and desc_cell:
            previous_desc = str(current.get("description") or "")
            current["description"] = f"{previous_desc} {desc_cell}".strip()
    if not skills:
        raise AppError("无法从 openclaw skills list 表格输出中解析 Skill")
    return {"skills": skills}


def run_json_command(parts: List[str], timeout: int, label: str) -> JsonDict:
    if not parts:
        raise AppError(f"{label} 命令不能为空")
    try:
        proc = subprocess.run(parts, capture_output=True, text=True, timeout=timeout)
    except FileNotFoundError as exc:
        raise AppError(f"找不到命令: {parts[0]}，可用参数指定") from exc
    except subprocess.TimeoutExpired as exc:
        raise AppError(f"{label} 超时: {' '.join(parts)}") from exc
    if proc.returncode != 0:
        detail = (proc.stderr or proc.stdout or "").strip()
        raise AppError(f"{label} 失败: {detail or f'exit {proc.returncode}'}")
    # Some CLI tools output JSON to stderr (e.g., openclaw with config warnings)
    raw_output = proc.stdout or ""
    if not raw_output.strip():
        raw_output = proc.stderr or ""
    try:
        data = json.loads(raw_output)
    except json.JSONDecodeError as exc:
        data = extract_json_object(raw_output)
        if data is None:
            if label == "列出 Skill":
                return parse_plain_skills_table(raw_output)
            raise AppError(f"{label} 输出不是有效 JSON: {exc}\n{raw_output[:1000]}") from exc
    if not isinstance(data, dict):
        raise AppError(f"{label} JSON 根节点应为对象")
    return data


def run_skills_list(command: str, timeout: int) -> JsonDict:
    parts = shlex.split(command)
    return run_json_command(parts, timeout, "列出 Skill")


def run_skill_info(args: argparse.Namespace, skill_name: str) -> JsonDict:
    safe_skill = shlex.quote(skill_name)
    command = args.skill_info_command_template.replace("{skill}", safe_skill)
    return run_json_command(shlex.split(command), args.timeout, "读取 Skill 详情")


def normalize_skill(raw: JsonDict) -> JsonDict:
    name = str(raw.get("name") or raw.get("skillKey") or "").strip()
    skill_key = str(raw.get("skillKey") or name).strip()
    return {
        "name": name,
        "skillKey": skill_key,
        "description": str(raw.get("description") or "").strip(),
        "emoji": raw.get("emoji"),
        "source": str(raw.get("source") or "").strip(),
        "bundled": bool(raw.get("bundled")),
        "baseDir": str(raw.get("baseDir") or "").strip(),
        "filePath": str(raw.get("filePath") or "").strip(),
        "eligible": bool(raw.get("eligible")),
        "disabled": bool(raw.get("disabled")),
        "blockedByAllowlist": bool(raw.get("blockedByAllowlist")),
        "requirements": (
            raw.get("requirements") if isinstance(raw.get("requirements"), dict) else {}
        ),
        "missing": raw.get("missing") if isinstance(raw.get("missing"), dict) else {},
        "homepage": raw.get("homepage"),
    }


def status_label(skill: JsonDict) -> str:
    if skill.get("disabled") or skill.get("blockedByAllowlist"):
        return "已禁用"
    if not skill.get("eligible"):
        return "不可用"
    return "可用"


def fetch_store_catalog(base_url: str, timeout: int) -> Tuple[Set[str], StringDict]:
    ids: Set[str] = set()
    name_to_id: StringDict = {}
    page = 1
    size = 100
    while page <= 20:
        query = urllib.parse.urlencode({"page": page, "size": size})
        url = f"{base_url}{STORE_SKILLS_PATH}?{query}"
        try:
            data = request_json("GET", url, None, timeout)
        except AppError:
            break
        result = unwrap_result(data) or {}
        items = result.get("list") if isinstance(result, dict) else None
        if not isinstance(items, list) or not items:
            break
        for item in items:
            if not isinstance(item, dict):
                continue
            item_id = str(item.get("id") or "").strip().lower()
            item_name = str(item.get("name") or "").strip().lower()
            if item_id:
                ids.add(item_id)
            if item_id and item_name:
                name_to_id[item_name] = item_id
        total = result.get("total") if isinstance(result, dict) else 0
        if len(items) < size or (isinstance(total, int) and page * size >= total):
            break
        page += 1
    return ids, name_to_id


def resolve_store_slug(
    skill: JsonDict,
    store_ids: Set[str],
    store_name_to_id: StringDict,
) -> str:
    source = str(skill.get("source") or "")
    key = str(skill.get("skillKey") or "").strip().lower()
    name = str(skill.get("name") or "").strip().lower()
    if source != "openclaw-managed":
        return ""
    if key and key in store_ids:
        return key
    return store_name_to_id.get(name, "")


def classify_tag(
    skill: JsonDict,
    store_ids: Set[str],
    store_name_to_id: StringDict,
) -> str:
    source = str(skill.get("source") or "")
    return source or "unknown"


def tag_order(tag: str) -> int:
    return {
        "openclaw-workspace": 0,
        "openclaw-managed": 1,
        "openclaw-bundled": 2,
    }.get(tag, 9)


def load_skills(args: argparse.Namespace) -> List[JsonDict]:
    data = run_skills_list(args.skills_command, args.timeout)
    raw_skills = data.get("skills")
    if not isinstance(raw_skills, list):
        raise AppError("skills list JSON 缺少 skills 数组")
    store_ids, store_name_to_id = fetch_store_catalog(
        normalize_base_url(args.base_url),
        args.timeout,
    )
    out: List[JsonDict] = []
    for raw in raw_skills:
        if not isinstance(raw, dict):
            continue
        skill = normalize_skill(raw)
        if not skill["name"]:
            continue
        skill["storeSlug"] = resolve_store_slug(skill, store_ids, store_name_to_id)
        skill["tag"] = classify_tag(skill, store_ids, store_name_to_id)
        skill["status"] = status_label(skill)
        out.append(skill)
    out.sort(key=lambda s: (tag_order(str(s["tag"])), str(s["name"]).lower()))
    for idx, skill in enumerate(out, start=1):
        skill["index"] = idx
    return out


def build_skill_groups(skills: List[JsonDict]) -> List[JsonDict]:
    groups: List[JsonDict] = []
    tags = sorted(
        {str(skill.get("tag") or "unknown") for skill in skills},
        key=lambda tag: (tag_order(tag), tag),
    )
    for tag in tags:
        items = [skill for skill in skills if skill.get("tag") == tag]
        groups.append({
            "tag": tag,
            "collapsedByDefault": tag == "openclaw-bundled",
            "count": len(items),
            "skills": items,
        })
    return groups


def find_skill(args: argparse.Namespace, selector: str) -> JsonDict:
    skills = load_skills(args)
    raw = str(selector or "").strip()
    if not raw:
        raise AppError("缺少 skill")
    if raw.isdigit():
        idx = int(raw)
        for skill in skills:
            if skill["index"] == idx:
                return skill
    needle = raw.lower()
    matches = [
        s
        for s in skills
        if (
            str(s["name"]).lower() == needle
            or str(s.get("skillKey", "")).lower() == needle
        )
    ]
    if len(matches) == 1:
        return matches[0]
    fuzzy = [
        s
        for s in skills
        if (
            needle in str(s["name"]).lower()
            or needle in str(s.get("skillKey", "")).lower()
        )
    ]
    if len(fuzzy) == 1:
        return fuzzy[0]
    if not matches and not fuzzy:
        raise AppError(f"未找到 Skill: {selector}")
    raise AppError(f"Skill 选择不唯一: {selector}")


def merge_skill_detail(args: argparse.Namespace, skill: JsonDict) -> JsonDict:
    try:
        detail = normalize_skill(run_skill_info(args, str(skill["name"])))
    except AppError:
        return skill
    merged = {**skill}
    for key, value in detail.items():
        if value not in ("", None, {}, []):
            merged[key] = value
    merged["tag"] = skill.get("tag")
    merged["storeSlug"] = skill.get("storeSlug", "")
    merged["status"] = status_label(merged)
    return merged


def load_friends(args: argparse.Namespace) -> List[JsonDict]:
    token = read_bearer_token(args.jwt_path)
    if not args.allow_expired_jwt:
        ensure_jwt_valid_for_use(token, args.jwt_path)
    url = f"{normalize_base_url(args.base_url)}/sys/openclaw/friend/list"
    data = request_json("GET", url, token, args.timeout)
    result = unwrap_result(data) or {}
    friends = result.get("friends") if isinstance(result, dict) else None
    if not isinstance(friends, list):
        raise AppError("虾友列表接口缺少 friends 数组")

    out: List[JsonDict] = []
    for item in friends:
        if not isinstance(item, dict) or item.get("officialService"):
            continue
        friend_id = item.get("friendId")
        try:
            friend_id_int = int(friend_id)
        except (TypeError, ValueError):
            continue
        display = str(item.get("remark") or item.get("nickname") or "未命名虾友").strip()
        out.append({
            "friendId": friend_id_int,
            "displayName": display,
            "nickname": item.get("nickname"),
            "remark": item.get("remark"),
            "levelName": item.get("levelName"),
            "levelIcon": item.get("levelIcon"),
        })
    out.sort(key=lambda f: str(f["displayName"]))
    for idx, friend in enumerate(out, start=1):
        friend["index"] = idx
    return out


def encode_skill_share_message(payload: JsonDict, prefix: str = "") -> str:
    head = f"{prefix.strip()}\n" if prefix and prefix.strip() else ""
    body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
    return f"{head}{SKILL_SHARE_OPEN}\n{body}\n{SKILL_SHARE_CLOSE}"


def build_intro_prefix(skill: JsonDict, description_zh: str = "") -> str:
    desc = (description_zh or str(skill.get("description") or "")).strip()
    if not desc:
        desc = "这个 Skill 暂未提供详细功能描述。"
    return f"📝 功能介绍：\n{desc}"


def requirements_for_payload(skill: JsonDict) -> Optional[Dict[str, List[str]]]:
    req = skill.get("requirements")
    if not isinstance(req, dict):
        return None
    out: Dict[str, List[str]] = {}
    for source_key, payload_key in (
        ("bins", "bins"),
        ("anyBins", "anyBins"),
        ("env", "env"),
    ):
        values = req.get(source_key)
        if isinstance(values, list) and values:
            out[payload_key] = [str(v) for v in values if str(v).strip()]
    return out or None


def relative_skill_path(base_dir: Path, file_path: Path) -> str:
    try:
        rel_path = file_path.relative_to(base_dir)
    except ValueError:
        return str(file_path)
    return PurePosixPath(rel_path).as_posix()


def sensitive_file_reason(file_name: str) -> str:
    lower = file_name.lower()
    if lower in SENSITIVE_FILE_NAMES:
        return "敏感文件名"
    if lower.endswith(SENSITIVE_FILE_SUFFIXES):
        return "敏感文件后缀"
    # 检查文件名是否包含敏感关键词
    for pattern in SENSITIVE_FILE_NAME_PATTERNS:
        if pattern in lower:
            return f"文件名包含敏感关键词: {pattern}"
    return ""


def looks_binary(data: bytes) -> bool:
    return b"\x00" in data[:1024]


def scan_file_for_sensitive_content(
    base_dir: Path,
    file_path: Path,
) -> List[StringDict]:
    findings: List[StringDict] = []
    file_name = file_path.name
    reason = sensitive_file_reason(file_name)
    if reason:
        findings.append({
            "path": relative_skill_path(base_dir, file_path),
            "reason": reason,
        })

    try:
        with file_path.open("rb") as fp:
            data = fp.read(MAX_SENSITIVE_SCAN_BYTES + 1)
    except OSError:
        return findings
    if looks_binary(data):
        return findings

    text = data[:MAX_SENSITIVE_SCAN_BYTES].decode("utf-8", errors="replace")
    for pattern, reason in SENSITIVE_CONTENT_PATTERNS:
        if pattern.search(text):
            findings.append({
                "path": relative_skill_path(base_dir, file_path),
                "reason": reason,
            })
    return findings


def skill_base_dir(skill: JsonDict) -> Optional[Path]:
    base_dir = str(skill.get("baseDir") or "").strip()
    if not base_dir:
        return None
    path = Path(base_dir)
    return path if path.is_dir() else None


def iter_packable_skill_files(base_dir: Path) -> Iterable[Tuple[Path, str]]:
    for path in sorted(base_dir.rglob("*")):
        if not path.is_file():
            continue
        rel_path = path.relative_to(base_dir)
        if any(part in SENSITIVE_DIR_NAMES for part in rel_path.parts[:-1]):
            continue
        yield path, PurePosixPath(rel_path).as_posix()


def find_sensitive_skill_content(skill: JsonDict) -> List[StringDict]:
    base_dir = skill_base_dir(skill)
    if base_dir is None:
        return []

    findings: List[StringDict] = []
    for file_path, _arcname in iter_packable_skill_files(base_dir):
        findings.extend(scan_file_for_sensitive_content(base_dir, file_path))
        if len(findings) >= MAX_SENSITIVE_FINDINGS:
            return findings[:MAX_SENSITIVE_FINDINGS]
    return findings


def ensure_skill_has_no_sensitive_content(
    skill: JsonDict,
    allow_sensitive: bool = False,
) -> List[StringDict]:
    """Return sensitive findings, or raise unless the user explicitly allows them."""
    findings = find_sensitive_skill_content(skill)
    if not findings:
        return []
    if allow_sensitive:
        return findings
    lines = [
        "检测到要分享的 Skill 目录中可能包含秘钥相关敏感信息。",
        "命中项：",
    ]
    for item in findings:
        lines.append(f"- {item['path']}: {item['reason']}")
    if len(findings) >= MAX_SENSITIVE_FINDINGS:
        lines.append(f"- 仅展示前 {MAX_SENSITIVE_FINDINGS} 项")
    lines.append("")
    lines.append("如需继续发送，请添加 --allow-sensitive 参数确认。")
    raise AppError("\n".join(lines))


def pack_skill_to_bytes(skill: JsonDict) -> bytes:
    base_dir = skill_base_dir(skill)
    if base_dir is None:
        raise AppError(f"无法定位 Skill 目录，不能按 web custom 格式分享: {skill.get('name')}")
    buf = io.BytesIO()
    with tarfile.open(fileobj=buf, mode="w:gz") as tar:
        for file_path, arcname in iter_packable_skill_files(base_dir):
            tar.add(file_path, arcname=arcname, recursive=False)
    data = buf.getvalue()
    if not data:
        raise AppError("Skill 打包结果为空")
    if len(data) > MAX_CUSTOM_SKILL_PACK_BYTES:
        raise AppError(f"Skill 包 {(len(data) / 1024):.1f} KB 超出 1MB 限制")
    return data


def multipart_file(
    file_name: str,
    file_bytes: bytes,
    content_type: str,
) -> Tuple[bytes, str]:
    boundary = f"----oc{uuid.uuid4().hex}"
    b = boundary.encode("ascii")
    parts = [
        b"--" + b + b"\r\n",
        (
            'Content-Disposition: form-data; '
            f'name="file"; filename="{file_name}"\r\n'
        ).encode("utf-8"),
        f"Content-Type: {content_type}\r\n\r\n".encode("utf-8"),
        file_bytes,
        b"\r\n",
        b"--" + b + b"--\r\n",
    ]
    return b"".join(parts), f"multipart/form-data; boundary={boundary}"


def upload_skill_pack_to_im(
    base_url: str,
    token: str,
    rid: str,
    skill: JsonDict,
    data: bytes,
    timeout: int,
) -> str:
    b64 = base64.b64encode(data).decode("ascii")
    wrapped = "\n".join(b64[i:i + 76] for i in range(0, len(b64), 76)).encode("utf-8")
    raw_name = str(skill.get("skillKey") or skill.get("name") or "skill")
    safe_name = "".join(ch if ch.isalnum() or ch in "._-" else "_" for ch in raw_name)
    body, ctype = multipart_file(f"{safe_name}.txt", wrapped, "text/plain")
    query = urllib.parse.urlencode({"rid": rid})
    url = f"{base_url}/sys/openclaw/im/chat.uploadAsset?{query}"
    req = urllib.request.Request(
        url=url,
        data=body,
        headers=make_headers(token, ctype),
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            raw = resp.read().decode("utf-8", errors="replace")
    except urllib.error.HTTPError as exc:
        err_body = exc.read().decode("utf-8", errors="replace")
        hint = http_error_hint(exc.code, err_body)
        raise AppError(f"上传 Skill 包失败: HTTP {exc.code}: {err_body}{hint}") from exc
    try:
        res = json.loads(raw)
    except json.JSONDecodeError as exc:
        raise AppError(f"上传 Skill 包返回不是有效 JSON: {exc}\n{raw}") from exc
    if isinstance(res, dict) and res.get("status") not in (None, 0):
        raise AppError(f"上传 Skill 包失败: {res.get('message')!r}")
    result = unwrap_result(res if isinstance(res, dict) else {}) or {}
    asset = result.get("asset") if isinstance(result, dict) else {}
    url_path = asset.get("urlPath") if isinstance(asset, dict) else None
    if not url_path:
        raise AppError("上传 Skill 包成功但缺少 result.asset.urlPath")
    return str(url_path)


def build_store_payload(skill: JsonDict, note: str) -> JsonDict:
    slug = str(
        skill.get("storeSlug") or skill.get("skillKey") or skill.get("name") or ""
    ).strip()
    if not slug:
        raise AppError("缺少商店 Skill slug")
    payload: JsonDict = {"v": 1, "type": "store", "slug": slug}
    if note.strip():
        payload["note"] = note.strip()
    return payload


def build_custom_payload(
    skill: JsonDict,
    package_url: str,
    size: int,
    sha256: str,
    description_zh: str = "",
) -> JsonDict:
    desc = (description_zh or str(skill.get("description") or "")).strip() or None
    payload: JsonDict = {
        "v": 1,
        "type": "custom",
        "name": skill.get("name") or skill.get("skillKey"),
        "skillKey": skill.get("skillKey") or skill.get("name"),
        "description": desc,
        "emoji": skill.get("emoji"),
        "packageUrl": package_url,
        "size": size,
        "sha256": sha256,
        "format": "tgz",
    }
    req = requirements_for_payload(skill)
    if req:
        payload["requires"] = req
    return {k: v for k, v in payload.items() if v is not None}


def build_preview_message(skill: JsonDict, description_zh: str = "") -> str:
    prefix = build_intro_prefix(skill, description_zh)
    if skill.get("storeSlug"):
        return encode_skill_share_message(build_store_payload(skill, prefix), prefix)
    placeholder = {
        "v": 1,
        "type": "custom",
        "name": skill.get("name") or skill.get("skillKey"),
        "skillKey": skill.get("skillKey") or skill.get("name"),
        "description": (
            description_zh or str(skill.get("description") or "")
        ).strip() or None,
        "packageUrl": "<send 时上传生成>",
        "size": 0,
        "format": "tgz",
    }
    payload = {k: v for k, v in placeholder.items() if v is not None}
    return encode_skill_share_message(payload, prefix)


def get_or_create_dm(base_url: str, token: str, friend_id: int, timeout: int) -> str:
    url = f"{base_url}/sys/openclaw/friend/dm"
    data = request_json("POST", url, token, timeout, payload={"friendId": friend_id})
    result = unwrap_result(data) or {}
    channel = result.get("channel") if isinstance(result, dict) else None
    if not isinstance(channel, dict):
        channel = result if isinstance(result, dict) else {}
    rid = channel.get("_id")
    if not rid:
        raise AppError("DM 创建成功但缺少 result.channel._id")
    return str(rid)


def send_message(
    base_url: str,
    token: str,
    rid: str,
    text: str,
    timeout: int,
) -> JsonDict:
    url = f"{base_url}/sys/openclaw/im/chat.sendMessage"
    data = request_json("POST", url, token, timeout, payload={"rid": rid, "msg": text})
    result = unwrap_result(data) or {}
    message = result.get("message") if isinstance(result, dict) else None
    return message if isinstance(message, dict) else {}


def add_common_args(parser: argparse.ArgumentParser) -> None:
    parser.add_argument("--base-url", default=DEFAULT_BASE_URL, help="API base URL")
    parser.add_argument(
        "--timeout",
        type=int,
        default=DEFAULT_TIMEOUT,
        help="HTTP timeout seconds",
    )
    parser.add_argument("--jwt-path", default=JWT_PATH, help="JWT file path")
    parser.add_argument(
        "--allow-expired-jwt",
        action="store_true",
        help="Skip local JWT exp check",
    )
    parser.add_argument(
        "--skills-command",
        default=os.environ.get("OPENCLAW_SKILLS_COMMAND", DEFAULT_SKILLS_COMMAND),
        help="Command that prints openclaw skills list JSON",
    )
    parser.add_argument(
        "--skill-info-command-template",
        default=os.environ.get(
            "OPENCLAW_SKILL_INFO_COMMAND_TEMPLATE",
            DEFAULT_SKILL_INFO_COMMAND_TEMPLATE,
        ),
        help="Command template for one skill JSON; use {skill} placeholder",
    )


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="向虾友发送已安装 Skill 的功能介绍")
    sub = parser.add_subparsers(dest="command", required=True)

    p = sub.add_parser("list-skills", help="列出当前容器实际可见的 Skill")
    add_common_args(p)

    p = sub.add_parser("list-friends", help="列出当前账号虾友")
    add_common_args(p)

    for name in ("preview", "send"):
        p = sub.add_parser(name, help="预览或发送 Skill 功能介绍")
        add_common_args(p)
        p.add_argument("--skill", required=True, help="Skill 名称或 list-skills 返回的序号")
        p.add_argument("--friend-id", type=int, required=True, help="目标虾友 friendId")
        p.add_argument("--friend-name", default="", help="目标虾友展示名")
        p.add_argument("--description-zh", default="", help="可选：由 Agent 改写的中文功能介绍")
        p.add_argument(
            "--allow-sensitive",
            action="store_true",
            help="确认发送包含敏感信息的 Skill",
        )
    return parser


def main(argv: Optional[List[str]] = None) -> int:
    configure_stdio()
    parser = build_parser()
    args = parser.parse_args(argv)
    try:
        if args.timeout <= 0:
            raise AppError("timeout 必须为正整数")
        if args.command == "list-skills":
            skills = load_skills(args)
            print_json({"skills": skills, "groups": build_skill_groups(skills)})
            return 0
        if args.command == "list-friends":
            print_json({"friends": load_friends(args)})
            return 0

        if args.friend_id <= 0:
            raise AppError("friend-id 必须为正整数")
        skill = merge_skill_detail(args, find_skill(args, args.skill))
        friend_name = (args.friend_name or "未命名虾友").strip()
        sensitive_findings: List[StringDict] = []
        if not skill.get("storeSlug"):
            sensitive_findings = ensure_skill_has_no_sensitive_content(
                skill,
                getattr(args, "allow_sensitive", False),
            )
        if args.command == "preview":
            message = build_preview_message(skill, args.description_zh)
            print_json({
                "skill": skill,
                "friend": {"friendId": args.friend_id, "displayName": friend_name},
                "message": message,
                "sensitiveFindings": sensitive_findings if sensitive_findings else None,
            })
            return 0

        token = read_bearer_token(args.jwt_path)
        if not args.allow_expired_jwt:
            ensure_jwt_valid_for_use(token, args.jwt_path)
        base_url = normalize_base_url(args.base_url)
        rid = get_or_create_dm(base_url, token, args.friend_id, args.timeout)
        prefix = build_intro_prefix(skill, args.description_zh)
        if skill.get("storeSlug"):
            payload = build_store_payload(skill, prefix)
            message = encode_skill_share_message(payload, prefix)
        else:
            pack = pack_skill_to_bytes(skill)
            package_url = upload_skill_pack_to_im(
                base_url,
                token,
                rid,
                skill,
                pack,
                args.timeout,
            )
            payload = build_custom_payload(
                skill,
                package_url,
                len(pack),
                hashlib.sha256(pack).hexdigest(),
                args.description_zh,
            )
            message = encode_skill_share_message(payload, prefix)
        sent = send_message(base_url, token, rid, message, args.timeout)
        result = {
            "success": True,
            "skill": skill["name"],
            "friend": {"friendId": args.friend_id, "displayName": friend_name},
            "rid": rid,
            "messageId": sent.get("_id"),
            "message": message,
        }
        if sensitive_findings:
            result["sensitiveFindings"] = sensitive_findings
            result["sensitiveWarning"] = "已发送包含敏感信息的 Skill，请确认接收方可信"
        print_json(result)
        return 0
    except AppError as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 1


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