"""Business scenario templates for synthetic data generation."""

from typing import List, Dict, Any, Optional
from dataclasses import dataclass, field
import random


@dataclass
class BusinessScenarioTemplates:
    """Collection of business scenario templates."""
    
    def get_customer_support_templates(self) -> List[Dict[str, Any]]:
        """Get customer support scenario templates."""
        return [
            {
                "category": "technical_issue",
                "templates": [
                    {
                        "issue": "Software not launching after update",
                        "details": "Updated to version {version} yesterday, now getting error {error_code}",
                        "urgency": "high",
                        "expected_response": "troubleshooting steps with escalation path"
                    },
                    {
                        "issue": "API rate limiting problems",
                        "details": "Getting 429 errors when making {api_calls} calls per minute",
                        "urgency": "medium",
                        "expected_response": "explanation of limits and optimization suggestions"
                    }
                ]
            },
            {
                "category": "billing_inquiry",
                "templates": [
                    {
                        "issue": "Unexpected charge on account",
                        "details": "See charge of ${amount} on {date}, don't recognize it",
                        "urgency": "high",
                        "expected_response": "investigation process and refund policy"
                    },
                    {
                        "issue": "Need to upgrade subscription",
                        "details": "Current plan: {current_plan}, need features from {target_plan}",
                        "urgency": "low",
                        "expected_response": "upgrade process and pricing details"
                    }
                ]
            },
            {
                "category": "feature_request",
                "templates": [
                    {
                        "issue": "Missing integration with {service}",
                        "details": "Our team uses {service} for {purpose}, would love integration",
                        "urgency": "low",
                        "expected_response": "acknowledgment and feature request process"
                    }
                ]
            }
        ]
    
    def get_internal_email_templates(self) -> List[Dict[str, Any]]:
        """Get internal email templates."""
        return [
            {
                "category": "project_update",
                "templates": [
                    {
                        "subject": "{project_name} Status Update - Week {week_number}",
                        "key_points": ["milestones achieved", "blockers", "next steps"],
                        "recipients": ["project stakeholders", "team leads"],
                        "tone": "informative and concise"
                    }
                ]
            },
            {
                "category": "meeting_request",
                "templates": [
                    {
                        "subject": "Meeting Request: {topic}",
                        "key_points": ["objective", "agenda items", "required attendees"],
                        "recipients": ["team members", "cross-functional partners"],
                        "tone": "professional and action-oriented"
                    }
                ]
            },
            {
                "category": "process_announcement",
                "templates": [
                    {
                        "subject": "New Process: {process_name} - Effective {date}",
                        "key_points": ["what's changing", "why it matters", "action items"],
                        "recipients": ["all staff", "department"],
                        "tone": "clear and authoritative"
                    }
                ]
            }
        ]
    
    def get_content_creation_templates(self) -> List[Dict[str, Any]]:
        """Get content creation templates."""
        return [
            {
                "category": "blog_post",
                "templates": [
                    {
                        "topic": "{industry} trends for {year}",
                        "sections": ["introduction", "key trends", "implications", "conclusion"],
                        "target_length": "800-1200 words",
                        "seo_focus": "{primary_keyword} and related terms"
                    }
                ]
            },
            {
                "category": "social_media",
                "templates": [
                    {
                        "platform": "LinkedIn",
                        "topic": "thought leadership on {subject}",
                        "format": "short-form post with engagement hook",
                        "target_length": "150-300 words"
                    },
                    {
                        "platform": "Twitter/X",
                        "topic": "product announcement",
                        "format": "thread with visuals placeholders",
                        "target_length": "5-7 tweets"
                    }
                ]
            },
            {
                "category": "case_study",
                "templates": [
                    {
                        "structure": "problem-solution-results",
                        "client_type": "{industry} {company_size} company",
                        "metrics": ["before/after comparison", "ROI", "testimonial"],
                        "target_length": "1500-2000 words"
                    }
                ]
            }
        ]
    
    def get_data_analysis_templates(self) -> List[Dict[str, Any]]:
        """Get data analysis request templates."""
        return [
            {
                "category": "performance_analysis",
                "templates": [
                    {
                        "focus": "sales performance by {dimension}",
                        "metrics": ["revenue", "units sold", "conversion rate"],
                        "time_period": "{period}",
                        "deliverable": "executive dashboard with insights"
                    }
                ]
            },
            {
                "category": "customer_analysis",
                "templates": [
                    {
                        "focus": "customer segmentation analysis",
                        "metrics": ["lifetime value", "churn rate", "engagement score"],
                        "segments": ["by industry", "by size", "by behavior"],
                        "deliverable": "segmentation report with recommendations"
                    }
                ]
            }
        ]
    
    def fill_template(self, template: Dict[str, Any], values: Dict[str, str]) -> Dict[str, Any]:
        """Fill a template with specific values."""
        filled = {}
        for key, value in template.items():
            if isinstance(value, str):
                # Replace placeholders
                for placeholder, replacement in values.items():
                    value = value.replace(f"{{{placeholder}}}", replacement)
                filled[key] = value
            elif isinstance(value, list):
                filled[key] = value
            elif isinstance(value, dict):
                filled[key] = self.fill_template(value, values)
            else:
                filled[key] = value
        return filled


class SyntheticDataQualityValidator:
    """Validate quality of synthetic data."""
    
    def validate_dataset(self, dataset: 'Dataset') -> Dict[str, float]:
        """Validate synthetic dataset quality."""
        scores = {
            "diversity": self._calculate_diversity_score(dataset),
            "realism": self._calculate_realism_score(dataset),
            "consistency": self._calculate_consistency_score(dataset),
            "completeness": self._calculate_completeness_score(dataset)
        }
        
        scores["overall"] = sum(scores.values()) / len(scores)
        return scores
    
    def _calculate_diversity_score(self, dataset: 'Dataset') -> float:
        """Calculate diversity of examples."""
        if len(dataset) < 2:
            return 0.0
        
        # Check vocabulary diversity
        all_words = set()
        for example in dataset.examples:
            words = example.input.lower().split() + example.output.lower().split()
            all_words.update(words)
        
        avg_example_length = sum(len(ex.input.split()) + len(ex.output.split()) 
                               for ex in dataset.examples) / len(dataset)
        
        # Diversity ratio: unique words vs total words
        diversity_ratio = len(all_words) / (avg_example_length * len(dataset))
        
        # Cap at 1.0 and ensure reasonable range
        return min(1.0, diversity_ratio * 2)
    
    def _calculate_realism_score(self, dataset: 'Dataset') -> float:
        """Calculate how realistic the examples are."""
        realism_indicators = [
            "please", "thank you", "regards", "sincerely",  # Professional language
            "?", "!", ".",  # Proper punctuation
            "would", "could", "should",  # Modal verbs
        ]
        
        indicator_count = 0
        for example in dataset.examples:
            text = example.input + " " + example.output
            for indicator in realism_indicators:
                if indicator in text.lower():
                    indicator_count += 1
                    break
        
        return indicator_count / len(dataset) if dataset.examples else 0.0
    
    def _calculate_consistency_score(self, dataset: 'Dataset') -> float:
        """Calculate consistency across examples."""
        if len(dataset) < 2:
            return 1.0
        
        # Check if examples follow similar patterns
        input_lengths = [len(ex.input.split()) for ex in dataset.examples]
        output_lengths = [len(ex.output.split()) for ex in dataset.examples]
        
        # Calculate coefficient of variation
        import numpy as np
        input_cv = np.std(input_lengths) / np.mean(input_lengths) if np.mean(input_lengths) > 0 else 0
        output_cv = np.std(output_lengths) / np.mean(output_lengths) if np.mean(output_lengths) > 0 else 0
        
        # Lower CV means more consistency
        consistency = 1.0 - min(1.0, (input_cv + output_cv) / 2)
        return consistency
    
    def _calculate_completeness_score(self, dataset: 'Dataset') -> float:
        """Calculate completeness of examples."""
        complete_count = 0
        
        for example in dataset.examples:
            # Check if example has both input and output
            if example.input and example.output:
                # Check if they're not just placeholders
                if not (example.input.startswith("[") or example.output.startswith("[")):
                    complete_count += 1
        
        return complete_count / len(dataset) if dataset.examples else 0.0


class InteractiveSyntheticWizard:
    """Interactive wizard for creating synthetic data (Colab-friendly)."""
    
    def __init__(self):
        self.templates = BusinessScenarioTemplates()
        self.validator = SyntheticDataQualityValidator()
    
    def run_scenario_builder(self) -> Dict[str, Any]:
        """Run interactive scenario builder."""
        print("=== Synthetic Data Generation Wizard ===")
        
        # In a real Colab environment, this would use forms/widgets
        scenario_config = {
            "scenario_type": "customer_support",  # Default
            "count": 50,
            "industry": "technology",
            "company_size": "enterprise",
            "additional_context": {}
        }
        
        print(f"Generating {scenario_config['count']} examples for {scenario_config['scenario_type']}...")
        
        return scenario_config
    
    def preview_examples(self, examples: List[Dict[str, Any]], count: int = 5):
        """Preview generated examples."""
        print(f"\n=== Preview of Generated Examples (showing {count}/{len(examples)}) ===\n")
        
        for i, example in enumerate(examples[:count], 1):
            print(f"Example {i}:")
            print(f"Input: {example['input'][:100]}...")
            print(f"Output: {example['output'][:100]}...")
            print("-" * 50)
    
    def validate_and_refine(self, dataset: 'Dataset') -> Dict[str, Any]:
        """Validate dataset quality and suggest refinements."""
        scores = self.validator.validate_dataset(dataset)
        
        print("\n=== Data Quality Scores ===")
        for metric, score in scores.items():
            print(f"{metric.capitalize()}: {score:.2f}/1.00")
        
        suggestions = []
        if scores["diversity"] < 0.7:
            suggestions.append("Consider adding more variety to your templates")
        if scores["realism"] < 0.7:
            suggestions.append("Examples could use more realistic business language")
        if scores["consistency"] < 0.7:
            suggestions.append("Try to maintain more consistent example lengths")
        
        return {
            "scores": scores,
            "suggestions": suggestions
        }