from typing import Dict, List
import json
import os
from transformers import pipeline
import numpy as np

class BrandStyleChecker:
    def __init__(self):
        self.style_guidelines = self._load_style_guidelines()
        self.classifier = pipeline(
            "text-classification",
            model="distilbert-base-uncased-finetuned-sst-2-english",
            device=-1
        )
        self.tone_keywords = self._load_tone_keywords()
    
    def _load_style_guidelines(self) -> Dict:
        """Load brand style guidelines from file."""
        guidelines_path = 'data/style_guidelines/brand_guidelines.json'
        if os.path.exists(guidelines_path):
            with open(guidelines_path, 'r') as f:
                return json.load(f)
        return {
            "tone": "professional yet approachable",
            "voice": "confident and authoritative",
            "key_phrases": [],
            "avoided_phrases": [],
            "brand_values": []
        }
    
    def _load_tone_keywords(self) -> Dict[str, List[str]]:
        """Load tone keywords for analysis."""
        keywords_path = 'data/style_guidelines/tone_keywords.json'
        if os.path.exists(keywords_path):
            with open(keywords_path, 'r') as f:
                return json.load(f)
        return {
            "professional": ["expert", "professional", "industry", "experience"],
            "approachable": ["friendly", "helpful", "understand", "support"],
            "confident": ["guaranteed", "proven", "success", "expertise"],
            "authoritative": ["leading", "best", "premier", "trusted"]
        }
    
    def check_alignment(self, content: str) -> float:
        """
        Check how well the content aligns with the brand style.
        
        Args:
            content: The content to check
            
        Returns:
            Alignment score between 0 and 1
        """
        scores = []
        
        # Check sentiment alignment
        sentiment_score = self._check_sentiment(content)
        scores.append(sentiment_score)
        
        # Check keyword presence
        keyword_score = self._check_keywords(content)
        scores.append(keyword_score)
        
        # Check tone consistency
        tone_score = self._check_tone_consistency(content)
        scores.append(tone_score)
        
        # Calculate final score (weighted average)
        weights = [0.3, 0.4, 0.3]  # Adjust weights based on importance
        final_score = np.average(scores, weights=weights)
        
        return float(final_score)
    
    def _check_sentiment(self, content: str) -> float:
        """Check if the sentiment aligns with brand guidelines."""
        result = self.classifier(content)[0]
        # Assuming positive sentiment (score > 0.5) is desired
        return result['score'] if result['label'] == 'POSITIVE' else 1 - result['score']
    
    def _check_keywords(self, content: str) -> float:
        """Check presence of brand-aligned keywords."""
        content_lower = content.lower()
        total_keywords = sum(len(keywords) for keywords in self.tone_keywords.values())
        found_keywords = sum(
            sum(1 for keyword in keywords if keyword in content_lower)
            for keywords in self.tone_keywords.values()
        )
        return found_keywords / total_keywords if total_keywords > 0 else 0.0
    
    def _check_tone_consistency(self, content: str) -> float:
        """Check consistency with brand tone guidelines."""
        # This is a simplified version - in practice, you might want to use
        # more sophisticated NLP techniques or a fine-tuned model
        content_lower = content.lower()
        tone_matches = 0
        total_checks = 0
        
        # Check for professional tone
        if any(word in content_lower for word in ["we", "our", "us"]):
            tone_matches += 1
        total_checks += 1
        
        # Check for approachable tone
        if any(word in content_lower for word in ["you", "your", "help", "support"]):
            tone_matches += 1
        total_checks += 1
        
        # Check for confident tone
        if any(word in content_lower for word in ["guarantee", "proven", "expert"]):
            tone_matches += 1
        total_checks += 1
        
        return tone_matches / total_checks if total_checks > 0 else 0.0 