from __future__ import annotations

import subprocess
import sys
import unittest
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]
SCRIPT = REPO_ROOT / "scripts" / "generate_agent_memory_skill_assets.py"
GLOBAL_CARD = REPO_ROOT / "skills" / "agent-memory-skill.global.md"
READONLY_CARD = REPO_ROOT / "skills" / "agent-memory-skill.readonly.md"


class TestAgentMemorySkillAssets(unittest.TestCase):
    def test_generated_agent_memory_skill_assets_are_fresh(self):
        proc = subprocess.run(
            [sys.executable, str(SCRIPT), "--check"],
            cwd=REPO_ROOT,
            capture_output=True,
            text=True,
            check=False,
        )
        self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
        self.assertIn("OK agent-memory skill assets are up to date", proc.stdout)

    def test_canonical_skill_cards_keep_required_sections(self):
        for path in (GLOBAL_CARD, READONLY_CARD):
            text = path.read_text(encoding="utf-8")
            self.assertTrue(text.startswith("# Agent memory skill"), path.name)
            self.assertIn("## Tool mapping", text, path.name)
            self.assertTrue(
                "## Trust" in text or "## Trust & safety hygiene" in text,
                path.name,
            )

    def test_generated_assets_are_marked_autogenerated(self):
        for rel in [
            "docs/agent-memory-skill-cards.md",
            "docs/snippets/openclaw-agentturn-message.global-default.md",
            "docs/snippets/openclaw-agentturn-message.watchdog-readonly.md",
        ]:
            text = (REPO_ROOT / rel).read_text(encoding="utf-8")
            self.assertTrue(
                text.splitlines()[0].startswith("<!-- AUTO-GENERATED by scripts/generate_agent_memory_skill_assets.py"),
                rel,
            )


if __name__ == "__main__":
    unittest.main()
