# -*- coding: utf-8 -*-
"""Tests for 'guanlan skill' command and _install_skill / _uninstall_skill."""

import importlib.resources
import os
import tempfile
import unittest
from unittest.mock import patch

from guanlan.cli import _install_skill, _uninstall_skill


class TestSkillCommand(unittest.TestCase):
    """Test skill install and uninstall via CLI helpers."""

    def test_skill_resources_include_both_locales(self):
        """Package resources should expose both default and English skill markdown files."""
        skill_dir = importlib.resources.files("guanlan").joinpath("skill")

        default_skill = skill_dir.joinpath("SKILL.md").read_text(encoding="utf-8")
        english_skill = skill_dir.joinpath("SKILL_en.md").read_text(encoding="utf-8")

        self.assertTrue(default_skill.strip())
        self.assertTrue(english_skill.strip())

    def test_install_skill_creates_skill_md(self):
        """_install_skill should create SKILL.md in the first available skill dir."""
        with tempfile.TemporaryDirectory() as tmpdir:
            skill_dir = os.path.join(tmpdir, "skills")
            os.makedirs(skill_dir)

            with patch(
                "guanlan.cli.os.path.expanduser",
                side_effect=lambda p: p.replace("~", tmpdir),
            ), patch.dict(os.environ, {}, clear=False):
                # Remove OPENCLAW_HOME to avoid interference
                env = os.environ.copy()
                env.pop("OPENCLAW_HOME", None)
                with patch.dict(os.environ, env, clear=True):
                    _install_skill()

            # Check at least one known skill dir pattern
            for dirpath, _, filenames in os.walk(tmpdir):
                if "SKILL.md" in filenames:
                    # Verify content is non-empty
                    with open(os.path.join(dirpath, "SKILL.md")) as f:
                        content = f.read()
                    self.assertIn("观澜 / Guanlan", content)
            # _install_skill may or may not find dirs depending on mock; just ensure no crash
            # The important test is that the function runs without error

    def test_uninstall_skill_removes_dir(self):
        """_uninstall_skill should remove skill directories."""
        with tempfile.TemporaryDirectory() as tmpdir:
            # Create a fake skill installation
            skill_path = os.path.join(tmpdir, ".openclaw", "skills", "guanlan")
            os.makedirs(skill_path)
            with open(os.path.join(skill_path, "SKILL.md"), "w") as f:
                f.write("test")

            self.assertTrue(os.path.exists(skill_path))

            with patch(
                "guanlan.cli.os.path.expanduser",
                side_effect=lambda p: p.replace("~", tmpdir),
            ), patch.dict(os.environ, {}, clear=False):
                env = os.environ.copy()
                env.pop("OPENCLAW_HOME", None)
                with patch.dict(os.environ, env, clear=True):
                    _uninstall_skill()

            self.assertFalse(os.path.exists(skill_path))

    def test_install_creates_dir_if_parent_exists(self):
        """_install_skill should create guanlan dir inside existing skill dir."""
        with tempfile.TemporaryDirectory() as tmpdir:
            # Create the .openclaw/skills parent but not guanlan subdir
            skill_parent = os.path.join(tmpdir, ".openclaw", "skills")
            os.makedirs(skill_parent)

            with patch(
                "guanlan.cli.os.path.expanduser",
                side_effect=lambda p: p.replace("~", tmpdir),
            ), patch.dict(os.environ, {}, clear=False):
                env = os.environ.copy()
                env.pop("OPENCLAW_HOME", None)
                with patch.dict(os.environ, env, clear=True):
                    _install_skill()

            target = os.path.join(skill_parent, "guanlan", "SKILL.md")
            self.assertTrue(os.path.exists(target))
            with open(target) as f:
                content = f.read()
            self.assertIn("观澜 / Guanlan", content)

    def test_install_uses_english_skill_for_english_locale(self):
        """_install_skill should install the English skill file for English locales."""
        with tempfile.TemporaryDirectory() as tmpdir:
            skill_parent = os.path.join(tmpdir, ".openclaw", "skills")
            os.makedirs(skill_parent)

            with patch(
                "guanlan.cli.os.path.expanduser",
                side_effect=lambda p: p.replace("~", tmpdir),
            ):
                env = os.environ.copy()
                env.pop("OPENCLAW_HOME", None)
                env["LANG"] = "en_US.UTF-8"
                with patch.dict(os.environ, env, clear=True):
                    _install_skill()

            target = os.path.join(skill_parent, "guanlan", "SKILL.md")
            self.assertTrue(os.path.exists(target))
            with open(target) as f:
                content = f.read()
            self.assertTrue(content.strip())
            self.assertIn("Give your AI agent eyes to see the entire internet.", content)
            self.assertNotIn("搜推特", content)
            self.assertTrue(
                os.path.exists(os.path.join(skill_parent, "guanlan", "references"))
            )


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