"""
Context Handlers - команды для восстановления контекста
"""

import logging
from typing import Dict, List, Any
from .base_handler import BaseHandler
from .response_formatter import ResponseFormatter

class ContextHandlers(BaseHandler):
    """Обработчик команд контекста"""
    
    def register_tools(self):
        """Регистрация всех Context инструментов"""
        
        # Context Instant - мгновенное понимание контекста
        self.register_tool(
            "mcp_nmp_context_instant",
            "Get instant context understanding for current project",
            self.context_instant,
            {
                "type": "object",
                "properties": {
                    "project": {"type": "string", "description": "Project name (default: current)"},
                    "focus": {"type": "string", "description": "Focus area: my_actions|project_state|code_context"},
                    "time_window": {"type": "string", "description": "Time window: last_session|last_day|last_week"}
                },
                "required": []
            }
        )
        
        # Context Work Summary - краткая сводка работы
        self.register_tool(
            "mcp_nmp_context_work_summary",
            "Get work session summary with key achievements",
            self.context_work_summary,
            {
                "type": "object",
                "properties": {
                    "session_id": {"type": "string", "description": "Session ID (default: current)"},
                    "include_code": {"type": "boolean", "description": "Include code changes"},
                    "include_decisions": {"type": "boolean", "description": "Include decisions made"}
                },
                "required": []
            }
        )
        
        # Context Code Intelligence - умный анализ кода
        self.register_tool(
            "mcp_nmp_context_code_intelligence",
            "Get intelligent code context and suggestions",
            self.context_code_intelligence,
            {
                "type": "object",
                "properties": {
                    "file_path": {"type": "string", "description": "File to analyze"},
                    "analysis_type": {"type": "string", "description": "Type: dependencies|patterns|improvements"},
                    "depth": {"type": "string", "description": "Analysis depth: shallow|deep"}
                },
                "required": []
            }
        )
        
        # Context Save - сохранение контекста
        self.register_tool(
            "mcp_nmp_context_save",
            "Save context (dialogue + code + files)",
            self.context_save,
            {
                "type": "object",
                "properties": {
                    "conversation": {"type": "string", "description": "Conversation content"},
                    "project": {"type": "string", "description": "Project name"},
                    "tags": {"type": "array", "items": {"type": "string"}, "description": "Tags"},
                    "code_snippets": {"type": "array", "items": {"type": "string"}, "description": "Code snippets"},
                    "files_referenced": {"type": "array", "items": {"type": "string"}, "description": "Referenced files"}
                },
                "required": ["conversation"]
            }
        )
        
        # Context Search - умный поиск контекста
        self.register_tool(
            "mcp_nmp_context_search",
            "Smart context search with ready chains",
            self.context_search,
            {
                "type": "object",
                "properties": {
                    "query": {"type": "string", "description": "Search query"},
                    "project": {"type": "string", "description": "Project filter"},
                    "include_related": {"type": "boolean", "description": "Include related data"},
                    "qwen_analysis": {"type": "boolean", "description": "Include Qwen analysis"},
                    "limit": {"type": "number", "description": "Max results"}
                },
                "required": ["query"]
            }
        )
        
        # Context Restore - восстановление контекста
        self.register_tool(
            "mcp_nmp_context_restore",
            "Restore full project context",
            self.context_restore,
            {
                "type": "object",
                "properties": {
                    "project": {"type": "string", "description": "Project name"},
                    "restore_depth": {"type": "string", "description": "Restore depth: full|summary|recent"},
                    "include_code": {"type": "boolean", "description": "Include code patterns"},
                    "include_files": {"type": "boolean", "description": "Include file relations"},
                    "time_range": {"type": "string", "description": "Time range: all|recent|today"}
                },
                "required": []
            }
        )
        
        logging.info("✅ Зарегистрированы Context handlers (6 команд)")
    
    async def context_instant(self, project: str = "current", focus: str = "my_actions", time_window: str = "last_session") -> str:
        """Мгновенное понимание контекста"""
        try:
            data = {
                "project": project,
                "focus": focus,
                "time_window": time_window
            }
            response = self.make_request("api/context/instant", data)
            return ResponseFormatter.format_context(response)
        except Exception as e:
            error_response = await self.handle_error(e, "context_instant")
            return ResponseFormatter.format_error(error_response)
    
    async def context_work_summary(self, session_id: str = "current", include_code: bool = True, include_decisions: bool = True) -> str:
        """Краткая сводка работы"""
        try:
            data = {
                "session_id": session_id,
                "include_code": include_code,
                "include_decisions": include_decisions
            }
            
            response = self.make_request("api/context/work_summary", data)
            
            # Детальная диагностика
            debug_info = "=== DEBUG INFO ===\n"
            debug_info += f"1. Response type: {type(response)}\n"
            debug_info += f"2. Response keys: {list(response.keys()) if isinstance(response, dict) else 'NOT_DICT'}\n"
            debug_info += f"3. Success: {response.get('success') if isinstance(response, dict) else 'NO_SUCCESS_KEY'}\n"
            
            if isinstance(response, dict) and response.get('success'):
                response_data = response.get('data', {})
                debug_info += f"4. Data type: {type(response_data)}\n"
                debug_info += f"5. Data keys: {list(response_data.keys())}\n"
                debug_info += f"6. Has session_summary: {'session_summary' in response_data}\n"
                
                if 'session_summary' in response_data:
                    session_summary = response_data['session_summary']
                    debug_info += f"7. Session summary type: {type(session_summary)}\n"
                    debug_info += f"8. Session summary keys: {list(session_summary.keys()) if isinstance(session_summary, dict) else 'NOT_DICT'}\n"
                    debug_info += f"9. Session summary content: {str(session_summary)[:200]}...\n"
                
                debug_info += f"10. Full response_data: {str(response_data)[:500]}...\n"
            
            formatted_result = ResponseFormatter.format_context(response)
            debug_info += f"11. Formatted result length: {len(formatted_result)}\n"
            debug_info += f"12. Formatted result preview: {formatted_result[:200]}...\n"
            debug_info += "=== END DEBUG ===\n\n"
            
            return debug_info + formatted_result
        except Exception as e:
            return f"ERROR: {str(e)}"
    
    async def context_code_intelligence(self, file_path: str = "", analysis_type: str = "patterns", depth: str = "shallow") -> str:
        """Умный анализ кода"""
        try:
            data = {
                "file_path": file_path,
                "analysis_type": analysis_type,
                "depth": depth
            }
            response = self.make_request("api/context/code_intelligence", data)
            return ResponseFormatter.format_context(response)
        except Exception as e:
            error_response = await self.handle_error(e, "context_code_intelligence")
            return ResponseFormatter.format_error(error_response) 
    
    async def context_save(self, conversation: str, project: str = "current", tags: List[str] = None, code_snippets: List[str] = None, files_referenced: List[str] = None) -> str:
        """Сохранение контекста (диалог + код + файлы)"""
        try:
            data = {
                "conversation": conversation,
                "project": project,
                "tags": tags or [],
                "code_snippets": code_snippets or [],
                "files_referenced": files_referenced or []
            }
            response = self.make_request("api/context/save", data)
            return ResponseFormatter.format_context(response)
        except Exception as e:
            error_response = await self.handle_error(e, "context_save")
            return ResponseFormatter.format_error(error_response)
    
    async def context_search(self, query: str, project: str = "", include_related: bool = True, qwen_analysis: bool = True, limit: int = 10) -> str:
        """Умный поиск контекста с готовыми цепочками"""
        try:
            data = {
                "query": query,
                "project": project,
                "include_related": include_related,
                "qwen_analysis": qwen_analysis,
                "limit": limit
            }
            response = self.make_request("api/context/search", data)
            
            # 🚨 ПРИНУДИТЕЛЬНЫЙ ТЕСТ: Возвращаем RAW данные напрямую
            if isinstance(response, dict) and response.get('success'):
                data = response.get('data', {})
                return f"🔍 RAW CONTEXT SEARCH:\nQuery: {data.get('search_query', 'Unknown')}\nResults: {len(data.get('contexts', []))}\nAPI Response Keys: {list(data.keys())}\nFirst Context: {str(data.get('contexts', [{}])[0] if data.get('contexts') else 'No contexts')[:300]}..."
            else:
                return f"❌ API ERROR: {response}"
        except Exception as e:
            error_response = await self.handle_error(e, "context_search")
            return ResponseFormatter.format_error(error_response)
    
    async def context_restore(self, project: str = "current", restore_depth: str = "full", include_code: bool = True, include_files: bool = True, time_range: str = "all") -> str:
        """Восстановление полного контекста проекта"""
        try:
            data = {
                "project": project,
                "restore_depth": restore_depth,
                "include_code": include_code,
                "include_files": include_files,
                "time_range": time_range
            }
            response = self.make_request("api/context/restore", data)
            return ResponseFormatter.format_context(response)
        except Exception as e:
            error_response = await self.handle_error(e, "context_restore")
            return ResponseFormatter.format_error(error_response) 