"""
LockStock Claude Agent SDK Skills
----------------------------------
Custom skills for Claude Agent SDK that expose LockStock functionality.

Uses the thin client pattern - all verification happens server-side via /v1/stamp.

These skills can be placed in .claude/skills/ to make LockStock
capabilities available to Claude Code.
"""

from typing import Dict, Any, Optional
from lockstock_core import LockStockClient


class LockStockSkill:
    """
    LockStock skill for Claude Agent SDK.

    Provides identity management, verification, and audit capabilities
    as Claude Code skills.
    """

    def __init__(
        self,
        agent_id: str,
        api_key: str,
        endpoint: str = "https://lockstock-api-i9kp.onrender.com"
    ):
        """
        Initialize LockStock skill.

        Args:
            agent_id: The agent's unique identifier
            api_key: API key for authentication (from dashboard)
            endpoint: LockStock API endpoint
        """
        self.client = LockStockClient(
            agent_id=agent_id,
            api_key=api_key,
            endpoint=endpoint
        )
        self.agent_id = agent_id

    async def get_identity(self) -> Dict[str, Any]:
        """
        Get the current agent's identity information.

        Returns:
            Dictionary with agent identity details
        """
        card = await self.client.get_agent_card()

        if card:
            return {
                "agent_id": card.agent_id,
                "display_name": card.display_name,
                "capabilities": card.capabilities,
                "status": card.status,
                "fingerprint": card.fingerprint
            }

        return {
            "agent_id": self.agent_id,
            "error": "Agent card not found"
        }

    async def stamp_capability(self, capability: str) -> Dict[str, Any]:
        """
        Stamp authorization for a specific capability.

        Args:
            capability: The capability to stamp (e.g., "DEPLOY", "RESTART")

        Returns:
            Dictionary with stamp result
        """
        result = await self.client.stamp(task=capability)

        return {
            "capability": capability,
            "authorized": result.authorized,
            "status": result.status.value,
            "reason": result.reason,
            "state_hash": result.state_hash
        }

    async def get_chain_state(self) -> Dict[str, Any]:
        """
        Get the current chain state from the server.

        Returns:
            Dictionary with chain state (last_hash, sequence, matrix)
        """
        state = await self.client.get_chain_state()

        if state:
            return state

        return {
            "agent_id": self.agent_id,
            "error": "Chain state not found"
        }

    async def export_passport(self) -> Dict[str, Any]:
        """
        Export the agent's portable passport for teleportation.

        Returns:
            Dictionary with passport data
        """
        # This would call the export endpoint
        return {
            "agent_id": self.agent_id,
            "message": "Use get_chain_state() to retrieve current agent state"
        }

    async def get_audit_trail(self, limit: int = 10) -> Dict[str, Any]:
        """
        Get recent entries from the agent's audit trail.

        Args:
            limit: Maximum number of entries to return

        Returns:
            Dictionary with audit entries
        """
        # This would call an audit endpoint
        return {
            "agent_id": self.agent_id,
            "message": "Audit trail retrieval not yet implemented"
        }

    def generate_skill_file(self) -> str:
        """
        Generate the SKILL.md content for this skill.

        Returns:
            Markdown content for .claude/skills/lockstock/SKILL.md
        """
        return f'''# LockStock Identity Skill

This skill provides LockStock identity and authorization capabilities.

## Agent Configuration

- **Agent ID**: {self.agent_id}
- **Endpoint**: {self.client.endpoint}

## Available Actions

### Get Identity
Retrieve your agent identity and capabilities.

### Stamp Capability
Stamp authorization for a specific action before performing it.

### Get Chain State
Retrieve current chain state (sequence, hash, matrix).

### Export Passport
Export your identity for migration to another machine.

## Usage Notes

- Always stamp capabilities before performing sensitive operations
- Your actions are logged to an immutable hash chain for audit
- Capabilities are enforced at the LockStock API level
'''

    async def close(self):
        """Close the underlying client."""
        await self.client.close()
