import json
import os
from pathlib import Path
from typing import Dict, List

class KnowledgeManager:
    def __init__(self):
        self.data_path = Path.home() / ".jarvis_data"
        self.data_path.mkdir(exist_ok=True)
        self.topics = self.load_topics()
    
    def load_topics(self) -> Dict:
        """Загрузка существующих тем"""
        topics = {}
        for topic_file in self.data_path.glob("*.json"):
            try:
                with open(topic_file, 'r', encoding='utf-8') as f:
                    topic_data = json.load(f)
                    topics[topic_data['id']] = topic_data
            except Exception as e:
                print(f"Ошибка загрузки темы {topic_file}: {e}")
        return topics
    
    def create_topic(self, name: str, content: str, tags: List[str] = None):
        """Создание новой темы"""
        topic_id = f"topic_{len(self.topics) + 1:04d}"
        
        topic_data = {
            'id': topic_id,
            'name': name,
            'content': content,
            'tags': tags or [],
            'related_topics': []
        }
        
        self.topics[topic_id] = topic_data
        self.save_topic(topic_id)
        return topic_id
    
    def save_topic(self, topic_id: str):
        """Сохранение темы в файл"""
        topic_file = self.data_path / f"{topic_id}.json"
        with open(topic_file, 'w', encoding='utf-8') as f:
            json.dump(self.topics[topic_id], f, ensure_ascii=False, indent=2)
    
    def search(self, query: str) -> List[Dict]:
        """Простой поиск по темам"""
        results = []
        query_lower = query.lower()
        
        for topic_id, topic_data in self.topics.items():
            if (query_lower in topic_data['name'].lower() or 
                query_lower in topic_data['content'].lower() or
                any(query_lower in tag.lower() for tag in topic_data.get('tags', []))):
                results.append(topic_data)
        
        return results
    
    def get_stats(self) -> Dict:
        """Статистика знаний"""
        return {
            'total_topics': len(self.topics),
            'data_path': str(self.data_path),
            'total_files': len(list(self.data_path.glob("*.json")))
        }