#!/usr/bin/env python3
"""memory_guardian.py — 记忆守卫 (no_agent)

每日运行，按SOUL记忆规则检查并清理：
1. MEMORY.md 是否存在、不超容量
2. 通过gateway自动清理共享memory中带[Agent:知微]的profile专属条目
3. 报告结果给Dad

有违规→输出报告 | 一切正常→SILENT
"""

import json, subprocess, urllib.request
from pathlib import Path
from datetime import datetime

HOME = Path.home()
PROFILE = HOME / ".hermes" / "profiles" / "position-analyst"
MEMORY_FILE = PROFILE / "MEMORY.md"
MEMORY_MAX = 3000
MEMORY_WARN = 2400
ISSUES = []


def check_memory_md():
    if not MEMORY_FILE.exists():
        ISSUES.append("MEMORY.md 不存在！profile专属内容可能全部塞在共享memory中")
        return
    size = MEMORY_FILE.stat().st_size
    if size > MEMORY_MAX:
        ISSUES.append(f"MEMORY.md 超限: {size}/{MEMORY_MAX}字符 ({size-MEMORY_MAX}超出)")
    elif size > MEMORY_WARN:
        ISSUES.append(f"MEMORY.md 接近上限: {size}/{MEMORY_MAX}字符")
    else:
        print(f"  ✅ MEMORY.md: {size}/{MEMORY_MAX}字符")


def cleanup_memory():
    """通过gateway自动清理共享memory中profile专属条目"""
    try:
        payload = json.dumps({
            "model": "default",
            "messages": [{"role": "user",
                "content": "清理共享memory中所有带[Agent:知微]标签或Session:2026的条目。"
                           "这些应该放在MEMORY.md而非共享memory。"
                           "用memory(action='remove', old_text='唯一子串')逐条删除。"
                           "完成后回复'清理完成'。"}],
            "max_tokens": 100,
        }).encode()
        req = urllib.request.Request(
            "http://localhost:8643/v1/chat/completions",
            data=payload,
            headers={"Content-Type": "application/json",
                     "Authorization": "Bearer hermes123",
                     "X-Hermes-Session-Id": "memory-guardian"}
        )
        resp = urllib.request.urlopen(req, timeout=120)
        result = json.loads(resp.read())
        reply = result["choices"][0]["message"]["content"]
        return "清理完成" in reply, reply[:200]
    except Exception as e:
        return False, str(e)[:200]


def main():
    print(f"记忆守卫 | {datetime.now().strftime('%Y-%m-%d %H:%M')}")
    print()
    check_memory_md()

    ok, detail = cleanup_memory()
    print(f"  {'✅' if ok else '⚠️'} 共享memory清理: {'已完成' if ok else detail}")

    if ISSUES:
        print()
        print(f"⚠️ 发现 {len(ISSUES)} 个问题:")
        for i in ISSUES:
            print(f"  • {i}")
    else:
        print()
        print("[SILENT] 记忆系统正常")


if __name__ == "__main__":
    main()
