"""
Core API Routes - основные endpoints системы
"""

from fastapi import APIRouter
from typing import Dict, Any
from .utils import generate_success_response, generate_error_response
import time
import psutil
import os

router = APIRouter(tags=["core"])

def generate_error_response(message: str) -> Dict[str, Any]:
    """Генерация стандартного ответа об ошибке"""
    return {
        "success": False,
        "error": message,
        "timestamp": time.time()
    }

@router.get("/status")
@router.post("/status")
async def get_status():
    """Получить статус системы"""
    try:
        # Импортируем глобальные переменные из основного модуля
        try:
            import nmp_plus_http_api_refactored
            vector_db = nmp_plus_http_api_refactored.vector_db
        except:
            vector_db = None
        
        # Проверяем доступность VectorDB
        vector_db_status = vector_db is not None
        
        # Qwen Engine запущен в отдельном процессе
        qwen_status = True  # Предполагаем что запущен в qwen_consciousness_refactored.py
        
        return {
            "success": True,
            "status": "🧠 NMP Plus HTTP API Active",
            "version": "2.0",
            "components": {
                "vector_db": vector_db_status,
                "data_loader": True,  # VectorDB выполняет функции data_loader
                "qwen_engine": qwen_status  # Запущен в отдельном процессе
            },
            "purpose": "HTTP bridge for MCP commands with modular architecture"
        }
    except Exception as e:
        return generate_error_response(f"Ошибка получения статуса: {e}")

@router.get("/system/monitor")
async def get_system_monitor():
    """Расширенная информация о системе для мониторинга"""
    try:
        # Системная информация
        system_info = {
            "cpu_percent": psutil.cpu_percent(interval=1),
            "memory": psutil.virtual_memory()._asdict(),
            "disk": psutil.disk_usage('/Users/mac4/Development/NMP_Plus')._asdict(),
            "boot_time": psutil.boot_time(),
            "load_avg": os.getloadavg() if hasattr(os, 'getloadavg') else [0, 0, 0]
        }
        
        # Информация о процессах NMP
        nmp_processes = []
        for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_percent', 'cmdline']):
            try:
                if any('nmp' in str(cmd).lower() for cmd in proc.info['cmdline'] or []):
                    nmp_processes.append({
                        'pid': proc.info['pid'],
                        'name': proc.info['name'],
                        'cpu_percent': proc.info['cpu_percent'],
                        'memory_percent': proc.info['memory_percent'],
                        'cmdline': ' '.join(proc.info['cmdline'] or [])[:100]
                    })
            except (psutil.NoSuchProcess, psutil.AccessDenied):
                continue
        
        # Размер базы данных
        db_path = '/Users/mac4/Development/NMP_Plus/data/vectors'
        db_size = 0
        if os.path.exists(db_path):
            for root, dirs, files in os.walk(db_path):
                for file in files:
                    db_size += os.path.getsize(os.path.join(root, file))
        
        # Информация о логах
        logs_info = {}
        logs_path = '/Users/mac4/Development/NMP_Plus/Logwork'
        if os.path.exists(logs_path):
            for root, dirs, files in os.walk(logs_path):
                for file in files:
                    if file.endswith('.log'):
                        file_path = os.path.join(root, file)
                        try:
                            stat = os.stat(file_path)
                            logs_info[file] = {
                                'size': stat.st_size,
                                'modified': stat.st_mtime
                            }
                        except OSError:
                            continue
        
        return generate_success_response({
            "system": system_info,
            "nmp_processes": nmp_processes,
            "database": {
                "path": db_path,
                "size_bytes": db_size,
                "size_mb": round(db_size / (1024 * 1024), 2)
            },
            "logs": logs_info,
            "timestamp": time.time()
        }, "Системная информация получена")
        
    except Exception as e:
        return generate_error_response(f"Ошибка получения системной информации: {e}")

@router.get("/api/status")
@router.post("/api/status") 
async def get_status_api():
    """Дублирующий endpoint для совместимости"""
    return await get_status()

@router.get("/tools/list")
async def tools_list():
    """Список доступных MCP инструментов - динамический из ToolsRegistry"""
    try:
        # Импортируем ToolsRegistry для получения актуального списка
        from mcp_handlers.tools_registry import ToolsRegistry
        
        # Получаем все инструменты из реестра
        tools = ToolsRegistry.get_all_tools()
        
        return {
            "tools": tools,
            "total": len(tools),
            "success": True
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e)) 

@router.get("/monitor/stats")
async def get_monitor_stats():
    """Легкая статистика для веб-мониторинга (без Qwen)"""
    try:
        import lancedb
        import os
        
        # Прямое подключение к LanceDB без Qwen
        db_path = os.path.join(os.path.dirname(__file__), "..", "data", "vectors")
        
        if not os.path.exists(db_path):
            return generate_success_response({
                "total_collections": 0,
                "total_documents": 0,
                "collections": [],
                "status": "no_database"
            }, "База данных не найдена")
        
        db = lancedb.connect(db_path)
        tables = db.table_names()
        total_docs = 0
        
        # Быстрый подсчет без детальной статистики
        for table_name in tables[:10]:  # Ограничиваем до 10 таблиц для скорости
            try:
                table = db.open_table(table_name)
                total_docs += table.count_rows()
            except:
                continue
        
        return generate_success_response({
            "total_collections": len(tables),
            "total_documents": total_docs,
            "collections": tables,
            "status": "lite_mode"
        }, f"Статистика: {len(tables)} коллекций, {total_docs} записей")
        
    except Exception as e:
        return generate_error_response(f"Ошибка получения статистики мониторинга: {e}")

@router.get("/monitor/collections")
async def get_monitor_collections():
    """Легкий список коллекций для мониторинга"""
    try:
        import lancedb
        import os
        
        db_path = os.path.join(os.path.dirname(__file__), "..", "data", "vectors")
        
        if not os.path.exists(db_path):
            return generate_success_response({
                "collections": []
            }, "База данных не найдена")
        
        db = lancedb.connect(db_path)
        tables = db.table_names()
        
        return generate_success_response({
            "collections": tables
        }, f"Найдено {len(tables)} коллекций")
        
    except Exception as e:
        return generate_error_response(f"Ошибка получения коллекций: {e}") 