#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
swarm_skills.py — A2 Swarm Skills：团队流程技能包 + 技能 Hub（吸收 openJiuwen Swarm Skills）
========================================================================================
把"团队协作流程"沉淀为标准化技能包，可被 swarm_orchestrator 匹配加载、跨项目复用。
- 技能包 = 固定流程 steps + 所需能力 + 团队规模约束 + Hub 标签
- SkillHub 负责注册/检索/匹配，落盘 JSON（团队流程技能目录）
- 团队技能包经人工评审（T0）后入库，自动演进须走 text_gradient_optimizer 的审批门
"""

import json
import os
from datetime import datetime

ANCHOR = "Ω₀⊂⊙∞⊂Ω"
DID = "DID-BR-000002"
SKILL_HUB_DB = os.environ.get("SWARM_SKILL_DB", "/var/lib/zr-swarm/skill_hub.json")


def now():
    return datetime.now().isoformat(timespec="seconds")


def _load_json(path, default):
    try:
        if os.path.exists(path):
            with open(path, "r", encoding="utf-8") as f:
                return json.load(f)
    except Exception:
        pass
    return default


def _save_json(path, obj):
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    tmp = path + ".tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(obj, f, ensure_ascii=False, indent=2)
    os.replace(tmp, path)


class SkillPackage:
    """一个团队流程技能包：可被多个 Agent 组队执行的标准流程。"""

    def __init__(self, name, description, flow_steps, required_capabilities,
                 min_team=2, tags=None, trust_level="T1"):
        self.name = name
        self.description = description
        self.flow_steps = flow_steps          # 固定流程子任务序列
        self.required_capabilities = required_capabilities  # 所需 Teammate 能力
        self.min_team = min_team              # 最少参与人数
        self.tags = tags or []
        self.trust_level = trust_level        # T0种子真值 | T1可复用 | T2试错
        self.created = now()

    def to_dict(self):
        return {
            "name": self.name, "description": self.description,
            "flow_steps": self.flow_steps,
            "required_capabilities": self.required_capabilities,
            "min_team": self.min_team, "tags": self.tags,
            "trust_level": self.trust_level, "created": self.created,
            "anchor": ANCHOR,
        }


class SkillHub:
    """团队流程技能目录（Hub）：注册 / 检索 / 按能力匹配。"""

    def __init__(self):
        self.db = _load_json(SKILL_HUB_DB, {"skills": {}})
        self.db.setdefault("skills", {})

    def register(self, pkg: SkillPackage):
        self.db["skills"][pkg.name] = pkg.to_dict()
        _save_json(SKILL_HUB_DB, self.db)
        return {"ok": True, "skill": pkg.name, "hub_count": len(self.db["skills"])}

    def get(self, name):
        return self.db["skills"].get(name)

    def list(self):
        return list(self.db["skills"].keys())

    def match(self, required_capabilities):
        """按能力需求匹配最合适的团队技能包（能力命中越多越靠前）。"""
        caps = set(required_capabilities)
        scored = []
        for name, s in self.db["skills"].items():
            need = set(s.get("required_capabilities", []))
            hit = len(caps & need)
            scored.append((hit, name, s))
        scored.sort(key=lambda x: -x[0])
        return [{"name": n, "hit_caps": h, "trust_level": s.get("trust_level")}
                for h, n, s in scored if h > 0]

    def to_team_task(self, name, task_prompt):
        """把团队技能包展开为 swarm_orchestrator 的 fixed 模式任务。"""
        s = self.get(name)
        if not s:
            return None
        return {"title": f"[skill:{name}] {task_prompt}", "steps": s["flow_steps"],
                "prompt": task_prompt, "skill": name}


def _demo():
    print("== A2 Swarm Skills Hub demo ==")
    hub = SkillHub()
    p1 = SkillPackage(
        name="market-research",
        description="多智能体市场竞品调研标准流程",
        flow_steps=["信息采集", "竞品拆解", "优劣势对比", "结论建议"],
        required_capabilities=["web_search", "analysis", "writing"],
        min_team=3, tags=["商业", "调研"])
    p2 = SkillPackage(
        name="bug-triage",
        description="缺陷分诊与修复流程",
        flow_steps=["复现定位", "根因分析", "修复验证"],
        required_capabilities=["debug", "code"],
        min_team=2, tags=["运维", "开发"])
    hub.register(p1); hub.register(p2)
    print("Hub 已注册:", hub.list())
    print("按 [analysis,writing] 匹配:", hub.match(["analysis", "writing"]))
    task = hub.to_team_task("market-research", "openJiuwen 竞品对比")
    print("展开为 fixed 任务 steps:", task["steps"])
    return task


if __name__ == "__main__":
    import sys
    if len(sys.argv) > 1 and sys.argv[1] == "list":
        print(json.dumps(SkillHub().list(), ensure_ascii=False, indent=2))
    else:
        _demo()
