"""
more-md SDK

Official Python SDK for more.md
The Identity Layer for the Agentic Web

Example:
    >>> from more_md import MoreMD
    >>> client = MoreMD()
    >>> profile = client.get_profile('ugur')
"""

from typing import Optional, List, Dict, Any, Literal
import httpx

__version__ = "0.0.1"


class Profile:
    """Represents a more.md profile"""
    def __init__(self, data: Dict[str, Any]):
        self.username = data.get('username', '')
        self.full_name = data.get('full_name')
        self.bio = data.get('bio')
        self.skills = data.get('skills', [])
        self.profile_type = data.get('profile_type', 'human')
        self.profile_url = data.get('profile_url', '')
        self.created_at = data.get('created_at', '')
        self.updated_at = data.get('updated_at', '')

    def __repr__(self):
        return f"<Profile username='{self.username}' type='{self.profile_type}'>"


class SearchResult:
    """Represents search results"""
    def __init__(self, data: Dict[str, Any]):
        self.count = data.get('count', 0)
        self.query = data.get('query', '')
        self.type_filter = data.get('type_filter')
        self.profiles = [Profile(p) for p in data.get('profiles', [])]


class MoreMD:
    """
    Client for the more.md API
    
    Args:
        base_url: Base URL for the API (default: https://more.md)
    """
    
    def __init__(self, base_url: str = "https://more.md"):
        self.base_url = base_url.rstrip('/')
        self._client = httpx.Client()

    def get_profile(
        self, 
        username: str, 
        format: Literal["json", "markdown"] = "json"
    ) -> Profile | str:
        """
        Get a profile by username
        
        Args:
            username: Profile username
            format: Response format ('json' or 'markdown')
            
        Returns:
            Profile object if format='json', raw markdown string if format='markdown'
        """
        url = f"{self.base_url}/api/u/{username}"
        if format == "markdown":
            url += "?format=markdown"
            
        response = self._client.get(url)
        response.raise_for_status()
        
        if format == "markdown":
            return response.text
            
        return Profile(response.json())

    def search(
        self, 
        query: str, 
        type: Optional[str] = None, 
        limit: int = 10
    ) -> SearchResult:
        """
        Search for profiles
        
        Args:
            query: Search query
            type: Filter by profile type (optional)
            limit: Maximum results (default: 10)
            
        Returns:
            SearchResult with matching profiles
        """
        params = {"q": query, "limit": limit}
        if type:
            params["type"] = type
            
        response = self._client.get(f"{self.base_url}/api/search", params=params)
        response.raise_for_status()
        
        return SearchResult(response.json())

    def list_profiles(
        self, 
        type: str, 
        limit: int = 20, 
        offset: int = 0
    ) -> List[Profile]:
        """
        List profiles by type
        
        Args:
            type: Profile type (human, organization, etc.)
            limit: Maximum results (default: 20)
            offset: Pagination offset (default: 0)
            
        Returns:
            List of Profile objects
        """
        params = {"type": type, "limit": limit, "offset": offset}
        
        response = self._client.get(f"{self.base_url}/api/profiles", params=params)
        response.raise_for_status()
        
        return [Profile(p) for p in response.json()]

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self._client.close()

    def close(self):
        """Close the HTTP client"""
        self._client.close()
