"""
记忆系统模块 - 使用 SQLite 存储用户偏好和历史记录
"""
import sqlite3
import json
import os
from datetime import datetime
from typing import Dict, List, Optional, Any
import logging

logger = logging.getLogger(__name__)


class MemorySystem:
    """记忆系统，管理用户偏好、历史对话和知识库"""
    
    def __init__(self, db_path: str = "memory.db"):
        """
        初始化记忆系统
        
        Args:
            db_path: 数据库文件路径
        """
        self.db_path = db_path
        self._init_database()
    
    def _init_database(self):
        """初始化数据库表结构"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            # 用户偏好表
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS preferences (
                    key TEXT PRIMARY KEY,
                    value TEXT,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            """)
            
            # 对话历史表
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS conversations (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    user_input TEXT,
                    jarvis_response TEXT,
                    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    context TEXT
                )
            """)
            
            # 知识库表
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS knowledge (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    title TEXT,
                    content TEXT,
                    source TEXT,
                    tags TEXT,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            """)
            
            # 任务计划表
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS tasks (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    title TEXT,
                    description TEXT,
                    due_date TEXT,
                    completed INTEGER DEFAULT 0,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            """)
            
            # 使用统计表
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS usage_stats (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    event_type TEXT,
                    event_data TEXT,
                    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            """)
            
            conn.commit()
            conn.close()
            logger.info("数据库初始化成功")
        except Exception as e:
            logger.error(f"数据库初始化失败: {e}")
            raise
    
    def save_preference(self, key: str, value: Any):
        """保存用户偏好"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            cursor.execute(
                "INSERT OR REPLACE INTO preferences (key, value, updated_at) VALUES (?, ?, ?)",
                (key, json.dumps(value), datetime.now().isoformat())
            )
            conn.commit()
            conn.close()
            logger.debug(f"保存偏好: {key} = {value}")
        except Exception as e:
            logger.error(f"保存偏好失败: {e}")
    
    def get_preference(self, key: str, default: Any = None) -> Any:
        """获取用户偏好"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            cursor.execute("SELECT value FROM preferences WHERE key = ?", (key,))
            result = cursor.fetchone()
            conn.close()
            if result:
                return json.loads(result[0])
            return default
        except Exception as e:
            logger.error(f"获取偏好失败: {e}")
            return default
    
    def save_conversation(self, user_input: str, jarvis_response: str, context: Optional[Dict] = None):
        """保存对话记录"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            cursor.execute(
                "INSERT INTO conversations (user_input, jarvis_response, context) VALUES (?, ?, ?)",
                (user_input, jarvis_response, json.dumps(context) if context else None)
            )
            conn.commit()
            conn.close()
            logger.debug(f"保存对话: {user_input[:50]}...")
        except Exception as e:
            logger.error(f"保存对话失败: {e}")
    
    def get_recent_conversations(self, limit: int = 10) -> List[Dict]:
        """获取最近的对话记录"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            cursor.execute(
                "SELECT user_input, jarvis_response, timestamp FROM conversations ORDER BY timestamp DESC LIMIT ?",
                (limit,)
            )
            results = cursor.fetchall()
            conn.close()
            return [
                {
                    "user_input": r[0],
                    "jarvis_response": r[1],
                    "timestamp": r[2]
                }
                for r in results
            ]
        except Exception as e:
            logger.error(f"获取对话历史失败: {e}")
            return []
    
    def save_knowledge(self, title: str, content: str, source: str = "", tags: List[str] = None):
        """保存知识条目"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            cursor.execute(
                "INSERT INTO knowledge (title, content, source, tags) VALUES (?, ?, ?, ?)",
                (title, content, source, json.dumps(tags) if tags else None)
            )
            conn.commit()
            conn.close()
            logger.info(f"保存知识: {title}")
        except Exception as e:
            logger.error(f"保存知识失败: {e}")
    
    def search_knowledge(self, keyword: str, limit: int = 5) -> List[Dict]:
        """搜索知识库"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            cursor.execute(
                "SELECT title, content, source, tags FROM knowledge WHERE title LIKE ? OR content LIKE ? LIMIT ?",
                (f"%{keyword}%", f"%{keyword}%", limit)
            )
            results = cursor.fetchall()
            conn.close()
            return [
                {
                    "title": r[0],
                    "content": r[1],
                    "source": r[2],
                    "tags": json.loads(r[3]) if r[3] else []
                }
                for r in results
            ]
        except Exception as e:
            logger.error(f"搜索知识库失败: {e}")
            return []
    
    def add_task(self, title: str, description: str = "", due_date: str = ""):
        """添加任务"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            cursor.execute(
                "INSERT INTO tasks (title, description, due_date) VALUES (?, ?, ?)",
                (title, description, due_date)
            )
            conn.commit()
            conn.close()
            logger.info(f"添加任务: {title}")
        except Exception as e:
            logger.error(f"添加任务失败: {e}")
    
    def get_today_tasks(self) -> List[Dict]:
        """获取今日任务"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            today = datetime.now().strftime("%Y-%m-%d")
            cursor.execute(
                "SELECT title, description, due_date, completed FROM tasks WHERE due_date <= ? AND completed = 0 ORDER BY due_date",
                (today,)
            )
            results = cursor.fetchall()
            conn.close()
            return [
                {
                    "title": r[0],
                    "description": r[1],
                    "due_date": r[2],
                    "completed": bool(r[3])
                }
                for r in results
            ]
        except Exception as e:
            logger.error(f"获取任务失败: {e}")
            return []
    
    def log_usage(self, event_type: str, event_data: Dict = None):
        """记录使用统计"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            cursor.execute(
                "INSERT INTO usage_stats (event_type, event_data) VALUES (?, ?)",
                (event_type, json.dumps(event_data) if event_data else None)
            )
            conn.commit()
            conn.close()
        except Exception as e:
            logger.error(f"记录使用统计失败: {e}")

