from __future__ import annotations

import json
import tempfile
import unittest
from pathlib import Path

from mentor_agent import MentorSkillRegistry


ROOT = Path(__file__).resolve().parents[1]


def write_skill(root: Path, directory: str, skill_id: str, name: str) -> None:
    path = root / directory
    path.mkdir(parents=True, exist_ok=True)
    (path / "SKILL.md").write_text(
        "\n".join(
            (
                "---",
                f"name: {skill_id}",
                "description: |",
                f"  {name}的思维框架。",
                f"  用途：使用{name}的视角分析市场。",
                "---",
                "",
                f"# {name} · 思维操作系统",
                "",
                '> "先看事实，再做判断。"',
                "",
                "### 模型1: 证据优先",
            )
        ),
        encoding="utf-8",
    )


class MentorSkillRegistryTests(unittest.TestCase):
    def test_private_skills_require_explicit_inclusion(self):
        with tempfile.TemporaryDirectory() as temporary:
            base = Path(temporary)
            public_root = base / "public"
            private_root = base / "private"
            write_skill(public_root, "public-person", "public-person", "公开老师")
            write_skill(private_root, "private-person", "private-person", "私有老师")
            (public_root / "mentor_catalog.json").write_text(
                json.dumps(
                    {
                        "mentors": {
                            "public-person": {
                                "evidence": {"grade": "A", "label": "原始语料", "note": "原帖"},
                                "quality": {"score": 6, "total": 6, "status": "pass"},
                            }
                        }
                    },
                    ensure_ascii=False,
                ),
                encoding="utf-8",
            )
            registry = MentorSkillRegistry(public_root, private_root)

            self.assertEqual([item.skill_id for item in registry.list_skills()], ["public-person"])
            with self.assertRaises(ValueError):
                registry.get_skill("private-person")

            admin_skills = registry.list_skills(include_private=True)
            self.assertEqual({item.skill_id for item in admin_skills}, {"public-person", "private-person"})
            private_skill = registry.get_skill("private-person", include_private=True)
            self.assertTrue(private_skill.is_private)
            self.assertTrue(private_skill.public()["private"])
            public_skill = registry.get_skill("public-person")
            self.assertEqual(public_skill.evidence_grade, "A")
            self.assertEqual(public_skill.quality_score, 6)

    def test_all_public_project_skills_have_catalog_metadata(self):
        registry = MentorSkillRegistry(ROOT / "游资skills")
        skills = registry.list_skills()
        self.assertGreaterEqual(len(skills), 21)
        self.assertNotIn("xiaobai-perspective", {item.skill_id for item in skills})
        self.assertTrue(all(item.evidence_grade in {"A", "B", "C"} for item in skills))
        self.assertTrue(all(item.quality_total == 6 for item in skills))

    def test_server_applies_private_guard_to_every_mentor_entry_point(self):
        mentor_section = (
            ROOT / "backend" / "features" / "mentor" / "service.py"
        ).read_text(encoding="utf-8")
        self.assertGreaterEqual(
            mentor_section.count('include_private=self.membership()["is_admin"]'),
            4,
        )


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