"""
Loopuman Python SDK
The Human Layer for AI - Get human intelligence on demand
"""

import requests
from typing import List, Dict, Optional

class Loopuman:
    """Client for Loopuman Enterprise API"""
    
    def __init__(self, api_key: str, base_url: str = "https://api.loopuman.com/api/v1"):
        self.api_key = api_key
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers.update({"X-API-Key": api_key})
    
    def create_tasks(
        self,
        tasks: List[Dict],
        webhook_url: Optional[str] = None,
        priority: str = "normal"
    ) -> Dict:
        """
        Create multiple tasks in a single batch.
        
        Args:
            tasks: List of task objects
            webhook_url: URL for completion notifications
            priority: 'normal', 'high', or 'urgent'
        
        Returns:
            Batch creation response with batch_id
        """
        response = self.session.post(
            f"{self.base_url}/tasks/bulk",
            json={
                "tasks": tasks,
                "webhook_url": webhook_url,
                "priority": priority
            }
        )
        response.raise_for_status()
        return response.json()
    
    def get_batch_status(self, batch_id: str) -> Dict:
        """Get the status of a task batch."""
        response = self.session.get(f"{self.base_url}/batches/{batch_id}")
        response.raise_for_status()
        return response.json()
    
    def get_batch_results(
        self,
        batch_id: str,
        status: str = "approved",
        limit: int = 100,
        offset: int = 0
    ) -> Dict:
        """
        Get results from a completed batch.
        
        Args:
            batch_id: The batch ID
            status: Filter by 'approved' or 'all'
            limit: Results per page (max 1000)
            offset: Pagination offset
        """
        response = self.session.get(
            f"{self.base_url}/batches/{batch_id}/results",
            params={"status": status, "limit": limit, "offset": offset}
        )
        response.raise_for_status()
        return response.json()
    
    def get_task(self, task_id: str) -> Dict:
        """Get details of a single task."""
        response = self.session.get(f"{self.base_url}/tasks/{task_id}")
        response.raise_for_status()
        return response.json()
    
    def health_check(self) -> Dict:
        """Check API availability."""
        response = requests.get(f"{self.base_url.replace('/api/v1', '')}/health")
        return response.json()


# Convenience functions for common use cases
def create_rlhf_comparisons(
    client: Loopuman,
    comparisons: List[tuple],
    budget_per_task: int = 50,
    workers_per_task: int = 3,
    webhook_url: Optional[str] = None
) -> Dict:
    """
    Create RLHF comparison tasks for AI training.
    
    Args:
        client: Loopuman client
        comparisons: List of (response_a, response_b) tuples
        budget_per_task: Payment in VAE cents
        workers_per_task: Number of human evaluators per comparison
        webhook_url: Notification URL
    
    Returns:
        Batch creation response
    """
    tasks = [
        {
            "title": "Compare AI Responses",
            "description": "Read both AI responses and select which is more helpful, accurate, and harmless. Explain your reasoning.",
            "private_description": f"Response A:\n{a}\n\nResponse B:\n{b}",
            "category": "ai_training",
            "budget": budget_per_task,
            "max_workers": workers_per_task,
            "external_id": f"rlhf_{i}"
        }
        for i, (a, b) in enumerate(comparisons)
    ]
    return client.create_tasks(tasks, webhook_url)


def create_image_labeling(
    client: Loopuman,
    image_urls: List[str],
    instructions: str,
    budget_per_image: int = 25,
    webhook_url: Optional[str] = None
) -> Dict:
    """
    Create image labeling tasks.
    
    Args:
        client: Loopuman client
        image_urls: List of image URLs to label
        instructions: Labeling instructions for workers
        budget_per_image: Payment per image
        webhook_url: Notification URL
    """
    tasks = [
        {
            "title": "Label Image",
            "description": f"{instructions}\n\nImage: {url}",
            "category": "labeling",
            "budget": budget_per_image,
            "external_id": f"img_{i}"
        }
        for i, url in enumerate(image_urls)
    ]
    return client.create_tasks(tasks, webhook_url)


# Example usage
if __name__ == "__main__":
    # Initialize client
    client = Loopuman(api_key="your_api_key_here")
    
    # Check health
    print(client.health_check())
    
    # Create RLHF tasks
    comparisons = [
        ("Response A text...", "Response B text..."),
        ("Another A...", "Another B..."),
    ]
    
    batch = create_rlhf_comparisons(
        client,
        comparisons,
        webhook_url="https://your-server.com/webhook"
    )
    
    print(f"Created batch: {batch['batch_id']}")
    print(f"Total cost: ${batch['total_cost'] / 100:.2f}")
