import json
from enum import Enum
from typing import Tuple, Dict, Any, Optional
from sqlalchemy.orm import Session


class IssueType(Enum):
    BUG = "bug"
    FEATURE_REQUEST = "feature_request"
    OTHER = "other"
    UNKNOWN = "unknown"


class ClassifierService:
    """问题自动分类服务 - 使用LLM进行分类"""
    
    def __init__(self, db: Session):
        self.db = db
    
    async def classify(self, content: str) -> Tuple[IssueType, Dict[str, Any]]:
        """
        自动分类问题类型
        使用本地LLM或fallback到规则匹配
        """
        # 尝试使用LLM分类
        try:
            from backend.integrations.llm_service import get_llm_service
            llm = get_llm_service()
            
            prompt = f"""分析以下内容，判断是BUG报告还是功能需求：

内容：{content}

请返回JSON格式：
{{
    "type": "bug" 或 "feature_request" 或 "other",
    "confidence": 0.0-1.0,
    "reason": "判断理由",
    "severity": "P0/P1/P2/P3" (如果是BUG),
    "priority": "high/medium/low" (如果是需求)
}}"""
            
            result = llm.chat(prompt)
            data = json.loads(result)
            
            issue_type = IssueType(data.get('type', 'other'))
            return issue_type, data
            
        except Exception as e:
            # Fallback到规则匹配
            return self._rule_based_classify(content)
    
    def _rule_based_classify(self, content: str) -> Tuple[IssueType, Dict[str, Any]]:
        """基于规则的分类（fallback）"""
        content_lower = content.lower()
        
        # BUG关键词
        bug_keywords = ['错误', 'bug', '崩溃', '闪退', '报错', '异常', '失败', '问题', '修复']
        # 需求关键词
        feature_keywords = ['希望', '建议', '想要', '需要', '增加', '添加', '功能', '改进']
        
        bug_score = sum(1 for kw in bug_keywords if kw in content_lower)
        feature_score = sum(1 for kw in feature_keywords if kw in content_lower)
        
        if bug_score > feature_score:
            return IssueType.BUG, {
                'type': 'bug',
                'confidence': 0.6,
                'reason': '基于关键词规则匹配',
                'severity': 'P2'
            }
        elif feature_score > 0:
            return IssueType.FEATURE_REQUEST, {
                'type': 'feature_request',
                'confidence': 0.6,
                'reason': '基于关键词规则匹配',
                'priority': 'medium'
            }
        
        return IssueType.UNKNOWN, {
            'type': 'unknown',
            'confidence': 0.0,
            'reason': '无法识别'
        }
    
    async def extract_bug_info(self, content: str) -> Dict[str, Any]:
        """提取BUG关键信息"""
        try:
            from backend.integrations.llm_service import get_llm_service
            llm = get_llm_service()
            
            prompt = f"""从以下BUG报告中提取关键信息：

内容：{content}

请返回JSON格式：
{{
    "title": "BUG标题",
    "description": "问题描述",
    "steps_to_reproduce": ["步骤1", "步骤2"],
    "expected_behavior": "期望行为",
    "actual_behavior": "实际行为",
    "environment": "环境信息",
    "severity": "P0/P1/P2/P3"
}}"""
            
            result = llm.chat(prompt)
            return json.loads(result)
            
        except Exception:
            return {
                'title': content[:50],
                'description': content,
                'steps_to_reproduce': [],
                'severity': 'P2'
            }
    
    async def extract_requirement_info(self, content: str) -> Dict[str, Any]:
        """提取需求关键信息"""
        try:
            from backend.integrations.llm_service import get_llm_service
            llm = get_llm_service()
            
            prompt = f"""从以下需求描述中提取关键信息：

内容：{content}

请返回JSON格式：
{{
    "title": "需求标题",
    "background": "背景",
    "user_scenario": "用户场景",
    "expected_behavior": "期望行为",
    "priority": "high/medium/low"
}}"""
            
            result = llm.chat(prompt)
            return json.loads(result)
            
        except Exception:
            return {
                'title': content[:50],
                'background': content,
                'priority': 'medium'
            }
