import sqlite3
from typing import List, Dict, Any, Optional


class TableManager:
    def __init__(self, db_path: str = 'user_data.db'):
        self.db_path = db_path

    def _execute(self, sql: str, params: tuple = ()) -> sqlite3.Cursor:
        """执行SQL语句的通用方法"""
        with sqlite3.connect(self.db_path) as conn:
            conn.row_factory = sqlite3.Row
            cursor = conn.cursor()
            cursor.execute(sql, params)
            conn.commit()
            return cursor


class UserManager(TableManager):
    def add_user(self, qq_id: str, ea_id: str, dog_tag_list: str) -> int:
        """添加用户记录"""
        cursor = self._execute(
            "INSERT INTO users (qq_id, ea_id, dog_tag_list) VALUES (?, ?, ?)",
            (qq_id, ea_id, dog_tag_list)
        )
        return cursor.lastrowid

    def get_user_by_qq(self, qq_id: str) -> Optional[Dict[str, Any]]:
        """通过QQ号查询用户"""
        cursor = self._execute(
            "SELECT * FROM users WHERE qq_id = ?",
            (qq_id,)
        )
        return dict(cursor.fetchone()) if cursor.fetchone() else None

    def update_dog_tags(self, user_id: int, new_tags: str) -> bool:
        """更新用户的狗牌列表"""
        self._execute(
            "UPDATE users SET dog_tag_list = ? WHERE id = ?",
            (new_tags, user_id)
        )
        return True


class DogTagManager(TableManager):
    def create_tag(self, name: str) -> int:
        """创建新狗牌"""
        cursor = self._execute(
            "INSERT INTO dog_tag (name) VALUES (?)",
            (name,)
        )
        return cursor.lastrowid

    def get_all_tags(self) -> List[Dict[str, Any]]:
        """获取所有狗牌"""
        cursor = self._execute("SELECT * FROM dog_tag")
        return [dict(row) for row in cursor.fetchall()]


class QueryRecordManager(TableManager):
    def log_query(self, user_id: str, target_id: str, status: str) -> int:
        """记录查询操作"""
        cursor = self._execute(
            """INSERT INTO query_record 
            (user_id, target_id, status) 
            VALUES (?, ?, ?)""",
            (user_id, target_id, status)
        )
        return cursor.lastrowid

    def get_user_history(self, user_id: str) -> List[Dict[str, Any]]:
        """获取用户查询历史"""
        cursor = self._execute(
            "SELECT * FROM query_record WHERE user_id = ?",
            (user_id,)
        )
        return [dict(row) for row in cursor.fetchall()]


if __name__ == "__main__":
    # 使用示例
    user_db = UserManager()
    user_id = user_db.add_user("123456", "EA_001", "tag1,tag2")
    print(f"Created user with ID: {user_id}")

    tag_db = DogTagManager()
    tag_id = tag_db.create_tag("新狗牌")
    print(f"Created tag with ID: {tag_id}")

    record_db = QueryRecordManager()
    record_id = record_db.log_query("123", "456", "success")
    print(f"Logged query with ID: {record_id}")
