import json
from typing import List, Optional
import requests

from llm_redact.db.models import RedactionRule


def generate_rules_from_llm(
    user_input: str,
    llm_host_url: str,
    model: Optional[str] = None
) -> List[RedactionRule]:
    """
    Generate redaction rules using LLM host service
    
    Args:
        user_input: User's description of what to redact
        llm_host_url: URL of the LLM host service
        model: Optional specific model to use
        
    Returns:
        List of RedactionRule objects
    """
    # Prepare request data
    request_data = {
        "user_input": user_input
    }
    
    if model:
        request_data["model"] = model
    
    # Make request to LLM host
    url = f"{llm_host_url.rstrip('/')}/rule/generate"
    
    try:
        response = requests.post(url, json=request_data, timeout=30)
        response.raise_for_status()
        
        response_data = response.json()
        rules_data = response_data.get("rules", [])
        
        # Convert to RedactionRule objects
        rules = []
        for rule_data in rules_data:
            rules.append(RedactionRule(
                name=rule_data.get("name", ""),
                description=rule_data.get("description", ""),
                data_type=rule_data.get("data_type", "")
            ))
        
        return rules
        
    except requests.RequestException as e:
        raise Exception(f"Failed to generate rules: {str(e)}")
    except (KeyError, json.JSONDecodeError) as e:
        raise Exception(f"Invalid response from LLM host: {str(e)}") 