"""Synthetic data generation for enterprise scenarios."""

from typing import List, Dict, Any, Optional
from dataclasses import dataclass
import random
import json
from datetime import datetime, timedelta

from ..core.base import Example, Dataset
from ..core.interfaces import DataGenerator, BusinessContext
from ..utils.llm_clients import BaseLLMClient


@dataclass
class ScenarioTemplate:
    """Template for generating business scenarios."""
    name: str
    input_template: str
    output_template: str
    variables: List[str]
    constraints: List[str]
    examples: List[Dict[str, str]]


class EnterpriseDataGenerator(DataGenerator):
    """Generate synthetic data for enterprise use cases."""
    
    def __init__(self, llm_client: Optional[BaseLLMClient] = None):
        self.llm_client = llm_client
        self.scenario_templates = self._load_scenario_templates()
    
    def _load_scenario_templates(self) -> Dict[str, ScenarioTemplate]:
        """Load pre-defined scenario templates."""
        return {
            "customer_support": ScenarioTemplate(
                name="Customer Support",
                input_template="Customer inquiry: {issue_description}\nProduct: {product}\nCustomer sentiment: {sentiment}",
                output_template="Support response addressing {issue_type} with {tone} tone",
                variables=["issue_description", "product", "sentiment", "issue_type", "tone"],
                constraints=["professional", "empathetic", "solution-focused"],
                examples=[
                    {
                        "issue_description": "My order hasn't arrived yet and it's been 10 days",
                        "product": "Electronics",
                        "sentiment": "frustrated",
                        "issue_type": "shipping delay",
                        "tone": "apologetic and helpful"
                    }
                ]
            ),
            "internal_email": ScenarioTemplate(
                name="Internal Email",
                input_template="Write email: Subject: {subject}\nContext: {context}\nRecipient: {recipient_role}",
                output_template="Professional email with {email_type} purpose",
                variables=["subject", "context", "recipient_role", "email_type"],
                constraints=["concise", "clear action items", "appropriate tone"],
                examples=[
                    {
                        "subject": "Q4 Planning Meeting",
                        "context": "Need to schedule quarterly planning session",
                        "recipient_role": "team lead",
                        "email_type": "meeting request"
                    }
                ]
            ),
            "content_creation": ScenarioTemplate(
                name="Content Creation",
                input_template="Create {content_type} about {topic}\nTarget audience: {audience}\nTone: {tone}",
                output_template="{content_type} with {word_count} words",
                variables=["content_type", "topic", "audience", "tone", "word_count"],
                constraints=["engaging", "informative", "brand-aligned"],
                examples=[
                    {
                        "content_type": "blog post introduction",
                        "topic": "AI in healthcare",
                        "audience": "healthcare professionals",
                        "tone": "professional yet accessible",
                        "word_count": "150-200"
                    }
                ]
            ),
            "data_analysis": ScenarioTemplate(
                name="Data Analysis Request",
                input_template="Analyze {data_type} for {time_period}\nFocus on: {metrics}\nPurpose: {purpose}",
                output_template="Analysis summary with {deliverable_type}",
                variables=["data_type", "time_period", "metrics", "purpose", "deliverable_type"],
                constraints=["data-driven", "actionable insights", "clear visualizations"],
                examples=[
                    {
                        "data_type": "sales performance",
                        "time_period": "Q3 2024",
                        "metrics": "revenue growth and customer acquisition",
                        "purpose": "board presentation",
                        "deliverable_type": "executive summary"
                    }
                ]
            )
        }
    
    def generate(self, count: int, context: Dict[str, Any]) -> List[Dict[str, Any]]:
        """Generate synthetic examples based on context."""
        scenario_type = context.get("scenario_type", "customer_support")
        template = self.scenario_templates.get(scenario_type)
        
        if not template:
            raise ValueError(f"Unknown scenario type: {scenario_type}")
        
        examples = []
        for _ in range(count):
            example = self._generate_single_example(template, context)
            examples.append(example)
        
        return examples
    
    def _generate_single_example(self, template: ScenarioTemplate, 
                               context: Dict[str, Any]) -> Dict[str, Any]:
        """Generate a single synthetic example."""
        # Generate variable values
        variables = {}
        for var in template.variables:
            variables[var] = self._generate_variable_value(var, context)
        
        # Format input and output
        input_text = template.input_template.format(**variables)
        output_hint = template.output_template.format(**variables)
        
        # If LLM client is available, generate realistic output
        if self.llm_client:
            output_text = self._generate_output_with_llm(
                input_text, output_hint, template.constraints
            )
        else:
            output_text = f"[Generated response for: {output_hint}]"
        
        return {
            "input": input_text,
            "output": output_text,
            "metadata": {
                "scenario": template.name,
                "variables": variables,
                "constraints": template.constraints,
                "synthetic": True
            }
        }
    
    def _generate_variable_value(self, variable: str, context: Dict[str, Any]) -> str:
        """Generate appropriate value for a variable."""
        # Industry-specific variations
        industry = context.get("industry", "general")
        
        generators = {
            "issue_description": lambda: random.choice([
                "I can't log into my account",
                "The product isn't working as expected",
                "I need to update my billing information",
                "The service has been down for hours",
                "I received the wrong item in my order"
            ]),
            "product": lambda: random.choice(
                context.get("products", ["Software", "Hardware", "Service", "Subscription"])
            ),
            "sentiment": lambda: random.choice(["frustrated", "neutral", "confused", "angry", "satisfied"]),
            "issue_type": lambda: random.choice(["technical", "billing", "shipping", "account", "general"]),
            "tone": lambda: random.choice(["professional", "friendly", "formal", "empathetic"]),
            "subject": lambda: self._generate_email_subject(context),
            "context": lambda: self._generate_business_context(context),
            "recipient_role": lambda: random.choice(["manager", "team lead", "colleague", "director", "VP"]),
            "email_type": lambda: random.choice(["update", "request", "announcement", "follow-up"]),
            "content_type": lambda: random.choice(["blog post", "social media post", "newsletter", "case study"]),
            "topic": lambda: self._generate_topic(industry),
            "audience": lambda: random.choice(["professionals", "executives", "customers", "partners"]),
            "data_type": lambda: random.choice(["sales", "customer", "operational", "financial"]),
            "time_period": lambda: self._generate_time_period(),
            "metrics": lambda: self._generate_metrics(context),
            "purpose": lambda: random.choice(["reporting", "analysis", "decision-making", "presentation"]),
            "deliverable_type": lambda: random.choice(["report", "dashboard", "summary", "presentation"]),
            "word_count": lambda: random.choice(["100-150", "200-300", "500-750"])
        }
        
        generator = generators.get(variable, lambda: f"[{variable}]")
        return generator()
    
    def _generate_email_subject(self, context: Dict[str, Any]) -> str:
        """Generate realistic email subjects."""
        templates = [
            "Update on {project}",
            "Action Required: {deadline}",
            "Meeting Request: {topic}",
            "Follow-up: {previous_discussion}",
            "{department} Weekly Update"
        ]
        
        template = random.choice(templates)
        # Simple placeholder replacement
        return template.replace("{project}", "Q4 Initiative")\
                      .replace("{deadline}", "End of Week")\
                      .replace("{topic}", "Budget Review")\
                      .replace("{previous_discussion}", "Strategy Session")\
                      .replace("{department}", context.get("department", "Sales"))
    
    def _generate_business_context(self, context: Dict[str, Any]) -> str:
        """Generate business context descriptions."""
        contexts = [
            "Preparing for quarterly business review",
            "Following up on customer feedback",
            "Implementing new process improvements",
            "Addressing team performance metrics",
            "Planning next sprint priorities"
        ]
        return random.choice(contexts)
    
    def _generate_topic(self, industry: str) -> str:
        """Generate industry-relevant topics."""
        topics = {
            "technology": ["AI adoption", "cloud migration", "cybersecurity", "digital transformation"],
            "healthcare": ["patient care", "telemedicine", "health data", "medical innovation"],
            "finance": ["market trends", "risk management", "fintech", "compliance"],
            "retail": ["customer experience", "e-commerce", "supply chain", "omnichannel"],
            "general": ["productivity", "innovation", "leadership", "growth strategies"]
        }
        
        industry_topics = topics.get(industry, topics["general"])
        return random.choice(industry_topics)
    
    def _generate_time_period(self) -> str:
        """Generate time period descriptions."""
        periods = ["Last Month", "Q1 2024", "YTD", "Last Quarter", "Past 30 Days"]
        return random.choice(periods)
    
    def _generate_metrics(self, context: Dict[str, Any]) -> str:
        """Generate relevant metrics based on context."""
        metric_sets = [
            "conversion rate and customer acquisition cost",
            "revenue growth and profit margins",
            "customer satisfaction and retention rate",
            "operational efficiency and cost reduction",
            "employee productivity and engagement"
        ]
        return random.choice(metric_sets)
    
    def _generate_output_with_llm(self, input_text: str, output_hint: str,
                                 constraints: List[str]) -> str:
        """Use LLM to generate realistic output."""
        prompt = f"""Generate a realistic business response for the following:

Input: {input_text}

The response should be: {output_hint}

Constraints: {', '.join(constraints)}

Provide only the response text, no additional commentary."""
        
        response = self.llm_client.generate(prompt, temperature=0.7, max_tokens=300)
        return response.text
    
    def create_customer_support_data(self, company_context: Dict[str, Any],
                                   count: int = 200) -> Dataset:
        """Generate customer support scenarios."""
        context = {
            **company_context,
            "scenario_type": "customer_support"
        }
        
        examples_data = self.generate(count, context)
        examples = [
            Example(
                input=ex["input"],
                output=ex["output"],
                metadata=ex.get("metadata", {})
            )
            for ex in examples_data
        ]
        
        return Dataset(
            examples=examples,
            name="customer_support_synthetic",
            metadata={
                "synthetic": True,
                "scenario": "customer_support",
                "company_context": company_context,
                "generated_at": datetime.now().isoformat()
            }
        )
    
    def create_internal_communication_data(self, team_context: Dict[str, Any],
                                         count: int = 150) -> Dataset:
        """Generate internal communication scenarios."""
        context = {
            **team_context,
            "scenario_type": "internal_email"
        }
        
        examples_data = self.generate(count, context)
        examples = [
            Example(
                input=ex["input"],
                output=ex["output"],
                metadata=ex.get("metadata", {})
            )
            for ex in examples_data
        ]
        
        return Dataset(
            examples=examples,
            name="internal_communication_synthetic",
            metadata={
                "synthetic": True,
                "scenario": "internal_email",
                "team_context": team_context,
                "generated_at": datetime.now().isoformat()
            }
        )
    
    def create_content_creation_data(self, brand_context: Dict[str, Any],
                                   count: int = 100) -> Dataset:
        """Generate content creation scenarios."""
        context = {
            **brand_context,
            "scenario_type": "content_creation"
        }
        
        examples_data = self.generate(count, context)
        examples = [
            Example(
                input=ex["input"],
                output=ex["output"],
                metadata=ex.get("metadata", {})
            )
            for ex in examples_data
        ]
        
        return Dataset(
            examples=examples,
            name="content_creation_synthetic",
            metadata={
                "synthetic": True,
                "scenario": "content_creation",
                "brand_context": brand_context,
                "generated_at": datetime.now().isoformat()
            }
        )