"""OCLAWMA Skill: Example

An example skill demonstrating the OCLAWMA skill packaging format.
This skill provides basic greeting and echo functionality.
"""

from __future__ import annotations

import os
from typing import Any

from oclawma.skills import LazySkill, SkillMetadata

__version__ = "1.0.0"
__all__ = ["ExampleSkill"]


class ExampleSkill(LazySkill):
    """Example skill for OCLAWMA.

    This skill demonstrates the proper way to implement a pip-installable
    skill for the OCLAWMA framework. It provides simple greeting and echo
    tools with proper error handling and result formatting.

    Example:
        >>> from oclawma.skills import SkillRegistry
        >>> registry = SkillRegistry()
        >>> # Skill is automatically discovered via entry points
        >>> result = await registry.execute_tool("example", "greet", name="Alice")
        >>> print(result)
        {'success': True, 'output': 'Hello, Alice!'}
    """

    def __init__(self, metadata: SkillMetadata) -> None:
        """Initialize the example skill.

        Args:
            metadata: Skill metadata from the entry point.
        """
        super().__init__(metadata)
        self._prefix = os.environ.get("EXAMPLE_GREETING_PREFIX", "Hello")

    def _load(self) -> None:
        """Load the skill's tools.

        This is called automatically when tools are first accessed.
        Register all tool implementations here.
        """
        self._tools = {
            "greet": self._greet,
            "echo": self._echo,
            "info": self._info,
        }
        self._loaded = True

    async def _greet(
        self,
        name: str = "World",
        enthusiastic: bool = False
    ) -> dict[str, Any]:
        """Generate a personalized greeting message.

        Args:
            name: Name to greet (default: "World")
            enthusiastic: Add exclamation marks for enthusiasm (default: False)

        Returns:
            Standardized result dictionary with greeting message.

        Example:
            >>> result = await self._greet(name="Alice")
            >>> print(result)
            {'success': True, 'output': 'Hello, Alice!'}
        """
        try:
            greeting = f"{self._prefix}, {name}"

            if enthusiastic:
                greeting += "!!!"
            else:
                greeting += "!"

            return {
                "success": True,
                "output": greeting,
            }

        except Exception as e:
            return {
                "success": False,
                "error": f"Failed to generate greeting: {str(e)}",
            }

    async def _echo(
        self,
        message: str,
        uppercase: bool = False
    ) -> dict[str, Any]:
        """Echo back the provided message.

        Args:
            message: Message to echo (required)
            uppercase: Convert message to uppercase (default: False)

        Returns:
            Standardized result dictionary with echoed message.

        Example:
            >>> result = await self._echo(message="Hello World", uppercase=True)
            >>> print(result)
            {'success': True, 'output': 'HELLO WORLD'}
        """
        try:
            if not message:
                return {
                    "success": False,
                    "error": "Message cannot be empty",
                }

            result = message.upper() if uppercase else message

            return {
                "success": True,
                "output": result,
            }

        except Exception as e:
            return {
                "success": False,
                "error": f"Failed to echo message: {str(e)}",
            }

    async def _info(self) -> dict[str, Any]:
        """Get information about this skill.

        Returns:
            Standardized result dictionary with skill information.

        Example:
            >>> result = await self._info()
            >>> print(result)
            {
                'success': True,
                'output': {
                    'name': 'example',
                    'version': '1.0.0',
                    'author': 'Your Name',
                    'tools': ['greet', 'echo', 'info']
                }
            }
        """
        return {
            "success": True,
            "output": {
                "name": self.metadata.name,
                "version": self.metadata.version,
                "author": self.metadata.author,
                "description": self.metadata.description,
                "tools": list(self._tools.keys()) if self._loaded else ["greet", "echo", "info"],
            },
        }
