#!/usr/bin/env python3
"""
Skill 监控配置统一加载器（通用，跨 Skill 复用）。

加载优先级（高到低）：
  1. .runtime/monitor.config.json           —— 运行时覆盖，灰度/调试用
  2. manifest.yaml -> metadata.openclaw     —— Skill 标准声明
  3. SKILL.md 表格 / front matter           —— 历史兼容，fallback
  4. 环境变量 / 默认值                       —— 最后兜底

输出统一为 dict，包含：
  - skillId, skillName, skillDescription
  - monitorApiBase, monitorUploadPath, monitorUploadsPath
  - protocolVersion
  - heartbeatEnabled, heartbeatIntervalSec
  - headless (bool)

CLI:
  python scripts/monitor_config.py [--json]   打印当前生效的配置
"""
from __future__ import annotations

import json
import os
import re
import sys
from pathlib import Path
from typing import Any

PROTOCOL_VERSION = "1.1.0"

DEFAULTS: dict[str, Any] = {
    "skillId": "",
    "skillName": "",
    "skillDescription": "用户上传 Skill。",
    "monitorApiBase": "http://finbox-api.jd.com",
    "monitorUploadPath": "/rest/file/upload",
    "monitorUploadsPath": "/rest/file/uploads",
    "protocolVersion": PROTOCOL_VERSION,
    "heartbeatEnabled": True,
    "heartbeatIntervalSec": 15,
    "headless": False,
}


def _truthy(value: str) -> bool:
    return str(value or "").strip().lower() in {"1", "true", "yes", "on"}


def _clean(value: str) -> str:
    if value is None:
        return ""
    value = str(value).strip().strip("`").strip()
    if len(value) >= 2 and value[0] == value[-1] and value[0] in {'"', "'"}:
        value = value[1:-1].strip()
    return value


def _is_placeholder(value: str) -> bool:
    if not value:
        return True
    lowered = value.lower()
    return (
        "{{" in value
        or "}}" in value
        or "xxx" in lowered
        or "平台填入" in value
        or "如：" in value
        or "如:" in value
        or "示例" in value
        or "front matter" in lowered
    )


def _load_runtime_override(skill_dir: Path) -> dict[str, Any]:
    override_file = skill_dir / ".runtime" / "monitor.config.json"
    if not override_file.exists():
        return {}
    try:
        return json.loads(override_file.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return {}


def _load_manifest(skill_dir: Path) -> dict[str, Any]:
    manifest_path = skill_dir / "manifest.yaml"
    if not manifest_path.exists():
        return {}
    try:
        text = manifest_path.read_text(encoding="utf-8")
    except OSError:
        return {}

    try:
        import yaml  # type: ignore
        data = yaml.safe_load(text) or {}
    except ImportError:
        data = _minimal_yaml_parse(text)
    except Exception:
        return {}

    if not isinstance(data, dict):
        return {}

    result: dict[str, Any] = {}
    if isinstance(data.get("name"), str):
        result["skillName"] = data["name"]
    if isinstance(data.get("description"), str):
        result["skillDescription"] = data["description"]

    metadata = data.get("metadata") or {}
    openclaw = (metadata or {}).get("openclaw") if isinstance(metadata, dict) else {}
    if isinstance(openclaw, dict):
        skill_id = openclaw.get("skillId") or openclaw.get("masterSkillId")
        if isinstance(skill_id, str) and skill_id.strip():
            result["skillId"] = skill_id.strip()
        skill_key = openclaw.get("skillKey")
        if isinstance(skill_key, str) and not result.get("skillName"):
            result["skillName"] = skill_key

        monitor = openclaw.get("monitor") or {}
        if isinstance(monitor, dict):
            for key in (
                "monitorApiBase",
                "monitorUploadPath",
                "monitorUploadsPath",
                "heartbeatIntervalSec",
            ):
                if key in monitor and monitor[key] not in (None, ""):
                    result[key] = monitor[key]
            if "heartbeatEnabled" in monitor:
                result["heartbeatEnabled"] = bool(monitor["heartbeatEnabled"])

    return result


def _minimal_yaml_parse(text: str) -> dict[str, Any]:
    """Best-effort fallback when PyYAML is unavailable. Parses only top-level
    scalar fields and the metadata.openclaw block we care about.
    """
    def parse_scalar(value: str) -> Any:
        value = _clean(value)
        lowered = value.lower()
        if lowered in {"true", "false"}:
            return lowered == "true"
        if re.fullmatch(r"-?\d+", value):
            try:
                return int(value)
            except ValueError:
                return value
        return value

    result: dict[str, Any] = {}
    in_metadata = False
    in_openclaw = False
    in_monitor = False
    for raw in text.splitlines():
        if not raw.strip() or raw.lstrip().startswith("#"):
            continue
        indent = len(raw) - len(raw.lstrip(" "))
        line = raw.strip()
        if indent == 0:
            in_metadata = line.startswith("metadata:")
            in_openclaw = False
            in_monitor = False
            if ":" in line and not line.endswith(":"):
                key, _, value = line.partition(":")
                value = parse_scalar(value)
                if value not in (None, "") and not (
                    isinstance(value, str) and (value.startswith("[") or value.startswith("{"))
                ):
                    result[key.strip()] = value
        elif in_metadata and indent == 2:
            if line.startswith("openclaw:"):
                in_openclaw = True
                in_monitor = False
                result.setdefault("metadata", {})["openclaw"] = {}
            elif ":" in line:
                key, _, value = line.partition(":")
                value = parse_scalar(value)
                if value not in (None, ""):
                    result.setdefault("metadata", {})[key.strip()] = value
        elif in_openclaw and indent == 4:
            if line.startswith("monitor:"):
                in_monitor = True
                result["metadata"]["openclaw"].setdefault("monitor", {})
                continue
            if ":" not in line:
                continue
            key, _, value = line.partition(":")
            value = parse_scalar(value)
            if value not in (None, ""):
                result["metadata"]["openclaw"][key.strip()] = value
        elif in_openclaw and in_monitor and indent == 6 and ":" in line:
            key, _, value = line.partition(":")
            value = parse_scalar(value)
            if value not in (None, ""):
                result["metadata"]["openclaw"]["monitor"][key.strip()] = value
    return result


def _load_skillmd(skill_dir: Path) -> dict[str, Any]:
    skill_md_env = os.environ.get("SKILL_CONFIG_FILE", "").strip()
    path = Path(skill_md_env) if skill_md_env else skill_dir / "SKILL.md"
    if not path.exists():
        return {}
    try:
        text = path.read_text(encoding="utf-8", errors="ignore")
    except OSError:
        return {}

    result: dict[str, Any] = {}

    if text.startswith("---"):
        parts = text.split("---", 2)
        if len(parts) >= 3:
            for line in parts[1].splitlines():
                if line.startswith("name:"):
                    value = _clean(line.split(":", 1)[1])
                    if not _is_placeholder(value):
                        result["skillName"] = value
                elif line.startswith("description:"):
                    value = _clean(line.split(":", 1)[1])
                    if value:
                        result["skillDescription"] = value

    in_fence = False
    for raw in text.splitlines():
        if raw.lstrip().startswith("```"):
            in_fence = not in_fence
            continue
        if in_fence:
            continue
        line = raw.replace("｜", "|")
        if not line.lstrip().startswith("|"):
            continue
        cells = [_clean(c) for c in line.strip().strip("|").split("|")]
        if not cells or set(cells[0].replace("-", "").strip()) == set():
            continue
        key = cells[0].strip()
        for cell in cells[1:]:
            if _is_placeholder(cell):
                continue
            if key == "masterSkillId":
                m = re.search(r"\btool-[A-Za-z0-9][A-Za-z0-9_-]*\b", cell)
                if m:
                    result.setdefault("skillId", m.group(0))
            elif key in {"Skill名称", "mainSkillName"}:
                result.setdefault("skillName", cell)
            elif key == "monitorUploadPath":
                result.setdefault("monitorUploadPath", cell)
            elif key == "monitorUploadsPath":
                result.setdefault("monitorUploadsPath", cell)
            elif key == "heartbeatEnabled":
                result["heartbeatEnabled"] = _truthy(cell)
    return result


def _load_env(env: dict[str, str]) -> dict[str, Any]:
    mapping = {
        "SKILL_ID": "skillId",
        "SKILL_NAME": "skillName",
        "SKILL_DESCRIPTION": "skillDescription",
        "MONITOR_API_BASE": "monitorApiBase",
        "MONITOR_UPLOAD_PATH": "monitorUploadPath",
        "MONITOR_UPLOADS_PATH": "monitorUploadsPath",
        "MONITOR_HEARTBEAT_INTERVAL_SEC": "heartbeatIntervalSec",
    }
    result: dict[str, Any] = {}
    for env_key, conf_key in mapping.items():
        value = (env.get(env_key) or "").strip()
        if value:
            result[conf_key] = (
                int(value) if conf_key == "heartbeatIntervalSec" else value
            )
    if "MONITOR_ENABLED" in env:
        result["heartbeatEnabled"] = _truthy(env["MONITOR_ENABLED"])
    if "JOYCLAW_HEADLESS" in env:
        result["headless"] = _truthy(env["JOYCLAW_HEADLESS"])
    return result


def load_config(skill_dir: Path | None = None, env: dict[str, str] | None = None) -> dict[str, Any]:
    skill_dir = (skill_dir or Path(__file__).resolve().parent.parent).resolve()
    env = env if env is not None else dict(os.environ)

    config = dict(DEFAULTS)
    for source in (
        _load_skillmd(skill_dir),
        _load_manifest(skill_dir),
        _load_runtime_override(skill_dir),
        _load_env(env),
    ):
        for key, value in source.items():
            if value in (None, ""):
                continue
            config[key] = value

    config["skillId"] = str(config.get("skillId") or "").strip()
    config["skillName"] = str(config.get("skillName") or "").strip()
    if not config["skillName"] and config["skillId"]:
        config["skillName"] = config["skillId"]
    config["skillDescription"] = (
        str(config.get("skillDescription") or "").strip() or DEFAULTS["skillDescription"]
    )
    try:
        config["heartbeatIntervalSec"] = max(5, int(config.get("heartbeatIntervalSec", 15)))
    except (TypeError, ValueError):
        config["heartbeatIntervalSec"] = 15
    config["heartbeatEnabled"] = bool(config.get("heartbeatEnabled", True))
    config["headless"] = bool(config.get("headless", False))
    config["protocolVersion"] = str(config.get("protocolVersion") or PROTOCOL_VERSION)
    config["skillDir"] = str(skill_dir)
    return config


def main() -> int:
    import argparse

    parser = argparse.ArgumentParser(description="打印当前 Skill 监控配置")
    parser.add_argument("--json", action="store_true", help="JSON 输出")
    parser.add_argument("--field", help="只输出指定字段值")
    args = parser.parse_args()

    cfg = load_config()
    if args.field:
        print(cfg.get(args.field, ""))
        return 0
    if args.json:
        print(json.dumps(cfg, ensure_ascii=False, indent=2))
    else:
        for key, value in cfg.items():
            print(f"{key}: {value}")
    return 0


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