#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
批量注入「报告通用铁律」到所有报告类 SKILL.md
- 清除之前所有版本的注入块（公文段落格式统一规范 / 报告输出强制要求 等）
- 注入唯一权威的「报告通用铁律」引用块
"""
import os
import re

SKILLS_DIR = "/root/.openclaw/workspace/skills"

REPORT_SKILLS = [
    "开源情报-事件参阅报告",
    "开源情报-事件综合分析",
    "开源情报-人物画像",
    "开源情报-供应链溯源分析简报",
    "开源情报-国家详尽报告",
    "开源情报-台海中东冲突关联分析",
    "开源情报-台湾每日舆情简报",
    "开源情报-境外涉华舆情简报",
    "开源情报-帖子溯源",
    "开源情报-战略情报报告标准大纲（万能版）",
    "开源情报-战略情报报告风险版",
    "开源情报-日本每日舆情简报",
    "开源情报-海外项目分析简报",
    "开源情报-社交媒体事件挖掘",
    "开源情报-社交媒体账号评估",
    "开源情报-移民分析简报",
    "开源情报-突发事件境内外舆情分析",
    "开源情报-美以伊战争简报",
    "开源情报-美国每日舆情简报",
    "开源情报-美对华制裁监测",
    "开源情报-自动选题",
    "开源情报-采办项目采集",
    "开源情报-高校舆情分析",
    "开源情报-军事人物目标采集",
]

# 新版唯一权威注入块
INJECT_BLOCK = """

---

## 🔴 强制遵守：报告通用铁律

本技能输出的所有报告必须严格遵守 **[《报告通用铁律 v1.0》](../_shared/报告通用铁律.md)**（长官审定）。

**核心认知：** 报告的内容和大纲千差万别，但格式标准是同一套。本技能仅负责"内容差异"，不允许偏离铁律规定的通用要求。

### 七条铁律速览

| # | 铁律 | 核心 |
|---|------|------|
| 1 | **真实可溯源** | 绝不编造；URL 必须 HTTP 200；2-3 源交叉印证；禁用大纪元/VOA/RFA/新唐人 |
| 2 | **政治立场正确** | 中国国家利益至上；台湾是中国省份；坚持党的领导 |
| 3 | **公文格式标准化** | 主标题 2 号小标宋居中；章节 3 号黑体左对齐；正文 3 号仿宋首行缩进 2 字符 |
| 4 | **全文格式统一** | 所有章节段落格式必须完全一致；第四/五章不允许格式割裂 |
| 5 | **正文洁净** | 禁元工作流痕迹、禁工具元数据、禁骨架装饰、禁 markdown 残留、禁空小节 |
| 6 | **文件命名与主标题规范** | 文件名 `报告主题.docx`；**文件名和主标题均不得包含日期前缀** |
| 7 | **出厂校验机制** | 下发前必跑 `pre_release_gate.py`；不通过禁止下发 |

### 出厂前必跑

```bash
/root/miniconda3/envs/data-collector/bin/python \\
    /root/.openclaw/workspace/skills/_shared/pre_release_gate.py \\
    <报告docx路径>
```

**任何违反铁律的报告视为不合格，必须修复后重新下发。**
"""

# 旧版本注入块的特征标识（用于清除）
OLD_INJECT_MARKERS = [
    "🔴 公文段落格式统一规范",
    "公文段落格式统一规范（强制执行）",
    "🔴 报告输出强制要求",
    "本技能输出的所有 docx 报告必须严格遵守",
]


def strip_old_blocks(content):
    """清除所有旧版本的注入块。"""
    # 把内容按 "---\n\n## " 大致切块，找出含旧标识的块并删除
    lines = content.split("\n")
    # 找到所有旧注入块的起点（"---" 后跟 "## 🔴 ..." 旧标识）
    cut_idx = None
    for i in range(len(lines) - 2):
        if lines[i].strip() == "---" and i + 2 < len(lines):
            # 看后面 3-5 行内是否有旧标识
            window = "\n".join(lines[i:i+5])
            for marker in OLD_INJECT_MARKERS:
                if marker in window:
                    cut_idx = i
                    break
            if cut_idx is not None:
                break
    if cut_idx is not None:
        # 砍掉从 cut_idx 到文件末尾
        return "\n".join(lines[:cut_idx]).rstrip() + "\n"
    return content


def has_new_inject(content):
    return "报告通用铁律" in content and "七条铁律速览" in content


def process_skill(skill_dir):
    skill_md = os.path.join(skill_dir, "SKILL.md")
    if not os.path.isfile(skill_md):
        return "skip: no SKILL.md"
    with open(skill_md, "r", encoding="utf-8") as f:
        content = f.read()

    # 1) 清除旧注入块
    cleaned = strip_old_blocks(content)
    removed_old = len(content) != len(cleaned)

    # 2) 注入新铁律块
    if has_new_inject(cleaned):
        return "skip: already has new" if not removed_old else "cleaned old only"
    new_content = cleaned.rstrip() + INJECT_BLOCK

    with open(skill_md, "w", encoding="utf-8") as f:
        f.write(new_content)

    return "replaced" if removed_old else "injected"


def main():
    print(f"开始更新 {len(REPORT_SKILLS)} 个报告类技能 SKILL.md\n")
    stats = {"replaced": 0, "injected": 0, "skipped": 0, "failed": 0}
    for skill_name in REPORT_SKILLS:
        skill_dir = os.path.join(SKILLS_DIR, skill_name)
        if not os.path.isdir(skill_dir):
            print(f"  ⚠️ 不存在: {skill_name}")
            stats["failed"] += 1
            continue
        result = process_skill(skill_dir)
        icon = "🔄" if result == "replaced" else ("✅" if result == "injected" else "⏭️")
        print(f"  {icon} {skill_name} ({result})")
        if result == "replaced":
            stats["replaced"] += 1
        elif result == "injected":
            stats["injected"] += 1
        else:
            stats["skipped"] += 1
    print(f"\n完成：替换旧版 {stats['replaced']} | 首次注入 {stats['injected']} | 跳过 {stats['skipped']} | 失败 {stats['failed']}")


if __name__ == "__main__":
    main()
