import os
import json
import re
import logging
import random
from datetime import datetime
from typing import List, Dict, Set, Tuple
from dataclasses import dataclass

@dataclass
class GifEmotionPattern:
    emotion: str
    keywords: List[str]
    responses: List[str]
    enabled: bool = True

@dataclass
class GifSituationPattern:
    situation: str
    keywords: List[str]
    responses: List[str]
    enabled: bool = True

class GifResponseManager:
    def __init__(self, config_file: str = None):
        self.emotion_patterns: List[GifEmotionPattern] = []
        self.situation_patterns: List[GifSituationPattern] = []
        self.config_file = config_file or './config/gif_patterns.json'
        self._load_default_patterns()
    
    def _load_default_patterns(self):
        emotion_patterns = [
            GifEmotionPattern('happy', ['happy', 'joy', 'smile', 'laugh', 'cheer', 'excited', 'celebration', 'party'], [
                '정말 즐거워 보이시네요! ',
                '기분이 좋으신 것 같아요!',
                '웃음이 전염되네요! ',
                '행복한 에너지가 느껴져요!'
            ], True),
            GifEmotionPattern('sad', ['sad', 'cry', 'tear', 'depressed', 'down', 'upset', 'disappointed'], [
                '괜찮으세요? 기분이 안 좋으신가 봐요 😢',
                '힘든 일이 있으셨나요?',
                '조금만 더 힘내세요!',
                '제가 도움이 될 수 있다면 언제든 말씀해주세요'
            ], True),
            GifEmotionPattern('angry', ['angry', 'mad', 'furious', 'rage', 'annoyed', 'irritated'], [
                '화가 나신 것 같아요. 차분히 생각해보세요',
                '무슨 일이 있으셨나요?',
                '진정하시고 천천히 말씀해주세요',
                '제가 도와드릴 수 있는 일이 있나요?'
            ], True),
            GifEmotionPattern('surprised', ['surprised', 'shock', 'wow', 'amazing', 'incredible', 'unbelievable'], [
                '와! 정말 놀라운 일이 있으셨나 봐요! ',
                '놀라셨을 것 같아요!',
                '어떤 일이 일어났나요?',
                '정말 신기한 일이네요!'
            ], True),
            GifEmotionPattern('love', ['love', 'heart', 'romantic', 'kiss', 'hug', 'affection', 'cute'], [
                '사랑스러운 마음이 전해져요! 💕',
                '정말 따뜻한 마음이네요',
                '사랑이 가득한 것 같아요',
                '아름다운 마음이 느껴져요'
            ], True),
            GifEmotionPattern('funny', ['funny', 'lol', 'haha', 'joke', 'comedy', 'hilarious', 'humor'], [
                '정말 재미있네요! ',
                '웃음이 터져나와요!',
                '유머 감각이 좋으시네요!',
                '기분이 좋아지는 GIF네요!'
            ], True),
            GifEmotionPattern('confused', ['confused', 'what', 'huh', 'question', 'thinking', 'puzzle'], [
                '궁금한 것이 있으시군요?',
                '혼란스러우신 것 같아요',
                '무엇이 궁금하신지 말씀해주세요',
                '제가 설명해드릴 수 있는 것이 있나요?'
            ], True),
            GifEmotionPattern('tired', ['tired', 'sleepy', 'exhausted', 'bored', 'yawn', 'rest'], [
                '피곤하신가 봐요. 푹 쉬세요!',
                '힘든 하루였나요?',
                '충분한 휴식을 취하세요',
                '무리하지 마시고 조금 쉬어가세요'
            ], True),
            GifEmotionPattern('celebrating', ['celebration', 'congratulations', 'success', 'victory', 'win', 'achievement'], [
                '축하드려요! 🎉',
                '정말 기쁜 일이 있으셨나 봐요!',
                '성공을 축하합니다!',
                '훌륭한 성과네요!'
            ], True),
            GifEmotionPattern('working', ['work', 'office', 'computer', 'meeting', 'business', 'professional'], [
                '열심히 일하고 계시는군요!',
                '업무에 집중하고 계시네요',
                '일이 잘 되고 있나요?',
                '업무 관련해서 도움이 필요하시면 말씀해주세요'
            ], True)
        ]
        
        situation_patterns = [
            GifSituationPattern('greeting', ['hello', 'hi', 'hey', 'good morning', 'good evening'], [
                '안녕하세요! 반갑습니다!',
                '인사해주셔서 감사해요!',
                '좋은 하루 보내세요!'
            ], True),
            GifSituationPattern('farewell', ['bye', 'goodbye', 'see you', 'farewell'], [
                '안녕히 가세요!',
                '좋은 하루 되세요!',
                '다음에 또 만나요!'
            ], True),
            GifSituationPattern('agreement', ['yes', 'agree', 'okay', 'sure', 'definitely', 'absolutely'], [
                '맞습니다!',
                '동감해요!',
                '정확한 말씀이에요!'
            ], True),
            GifSituationPattern('disagreement', ['no', 'disagree', 'nope', 'never', 'not'], [
                '그렇군요, 다른 의견이 있으시군요',
                '이해합니다',
                '다른 관점이 있으시네요'
            ], True),
            GifSituationPattern('question', ['what', 'how', 'why', 'when', 'where', 'who'], [
                '궁금한 것이 있으시군요!',
                '질문해주셔서 감사해요',
                '무엇이든 물어보세요!'
            ], True),
            GifSituationPattern('thanks', ['thank', 'thanks', 'appreciate', 'grateful'], [
                '천만에요!',
                '도움이 되었다니 기뻐요!',
                '별말씀을요!'
            ], True),
            GifSituationPattern('apology', ['sorry', 'apologize', 'excuse', 'forgive'], [
                '괜찮아요!',
                '전혀 문제없어요',
                '걱정하지 마세요'
            ], True),
            GifSituationPattern(
                'media',
                ['kbs', 'kbs2', 'sbs', 'mbc', 'jtbc', 'tv', 'news', 'anchor', 'studio', 'logo', 'broadcast', 'channel'],
                [
                    '방송 스튜디오 분위기네요! 🎬',
                    '뉴스/방송 관련 GIF 같아요.',
                    '공식적인 느낌이 나네요—어떤 소식인가요?'
                ],
                True
            ),
            GifSituationPattern('encouragement', ['good luck', 'cheer up', 'you can do it', 'fighting'], [
                '화이팅!',
                '힘내세요!',
                '응원합니다!'
            ], True)
        ]
        
        self.emotion_patterns.extend(emotion_patterns)
        self.situation_patterns.extend(situation_patterns)
        logging.info(f'기본 GIF 패턴 로드 완료: 감정 {len(emotion_patterns)}개, 상황 {len(situation_patterns)}개')
    
    def analyze_gif_content(self, gif_title: str) -> Dict:
        title_lower = gif_title.lower()
        
        detected_emotions = []
        for pattern in self.emotion_patterns:
            if not pattern.enabled:
                continue
            if any(keyword in title_lower for keyword in pattern.keywords):
                detected_emotions.append(pattern.emotion)
        
        detected_situations = []
        for pattern in self.situation_patterns:
            if not pattern.enabled:
                continue
            if any(keyword in title_lower for keyword in pattern.keywords):
                detected_situations.append(pattern.situation)
        
        return {
            'emotions': detected_emotions,
            'situations': detected_situations,
            'primary_emotion': detected_emotions[0] if detected_emotions else 'neutral',
            'primary_situation': detected_situations[0] if detected_situations else 'general'
        }
    
    def generate_contextual_response(self, analysis: Dict, gif_title: str, conversation_context: str = "") -> str:
        primary_emotion = analysis.get('primary_emotion', 'neutral')
        primary_situation = analysis.get('primary_situation', 'general')

        responses: List[str] = []

        # 1) 감정 기반
        for pattern in self.emotion_patterns:
            if pattern.enabled and pattern.emotion == primary_emotion:
                responses.extend(pattern.responses)
                break

        # 2) 상황 기반
        for pattern in self.situation_patterns:
            if pattern.enabled and pattern.situation == primary_situation:
                responses.extend(pattern.responses)
                break

        # 3) 대화 맥락 룰(문자열 기준 if-else)
        if conversation_context:
            ctx = conversation_context.lower()
            if any(word in ctx for word in ["힘들", "피곤", "지쳤", "고단"]):
                responses += ["힘든 하루에도 웃음을 찾으셨네요 😊", "피곤할 때는 이런 GIF가 딱이네요!"]
            if any(word in ctx for word in ["축하", "성공", "합격", "승진"]):
                responses += ["좋은 소식에 딱 맞는 GIF네요! 🎉", "축하의 마음이 전해집니다!"]
            if any(word in ctx for word in ["슬퍼", "우울", "외로", "눈물"]):
                responses += ["마음을 위로하는 GIF 같아요 💙", "조금은 기분이 나아지셨길 바라요"]
            if any(word in ctx for word in ["재밌", "웃겨", "폭소", "ㅋㅋ", "ㅎㅎ"]):
                responses += ["같이 웃으니 기분이 더 좋아져요 😆", "정말 빵 터지는 GIF네요!"]

        # 4) 기본 응답
        if not responses:
            responses = [
                "흥미로운 GIF네요!",
                "재미있는 선택이에요!",
                "어떤 의미로 보내주신 건가요?",
                "이 GIF에 대해 더 이야기해볼까요?"
            ]

        selected = random.choice(responses)

        # 부가 정보(검출 리스트 요약)
        context_info = ''
        if analysis.get('emotions'):
            context_info += f" ({', '.join(analysis['emotions'])}한 감정이 느껴져요)"
        if analysis.get('situations'):
            context_info += f" ({', '.join(analysis['situations'])} 상황인 것 같아요)"

        return selected + context_info

# 편의 함수들
_gif_manager_instance = None 

def analyze_gif_content(gif_title: str) -> Dict:
    global _gif_manager_instance
    if _gif_manager_instance is None:
        _gif_manager_instance = GifResponseManager()
    try:
        return _gif_manager_instance.analyze_gif_content(gif_title or "")
    except Exception:
        logging.exception("[GIF] analyze_gif_content failed")
        return {'emotions': [], 'situations': [], 'primary_emotion': 'neutral', 'primary_situation': 'general'}

def generate_contextual_response(analysis: Dict, gif_title: str, conversation_context: str = "") -> str:
    global _gif_manager_instance
    if _gif_manager_instance is None:
        _gif_manager_instance = GifResponseManager()
    return _gif_manager_instance.generate_contextual_response(
        analysis=analysis,
        gif_title=gif_title,
        conversation_context=conversation_context or ""
    )