import sqlite3
import json
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)

# 数据库连接
DB_PATH = 'your_database.db'  # 数据库路径，修改为实际路径
# 预定义标签，方便修改
TAG_LIST = ['vixen', 'blacked', 'tushy', 'x-art']

# 预加载标签 ID
def get_all_tag_ids():
    try:
        with sqlite3.connect(DB_PATH) as conn:
            cursor = conn.cursor()
            #cursor.execute("SELECT id, name FROM tags WHERE name IN ('vixen', 'blacked', 'tushy', 'x-art')")
            cursor.execute("SELECT id, name FROM tags WHERE name IN ({})".format(', '.join(['?']*len(TAG_LIST))), TAG_LIST)
            tags = cursor.fetchall()
            # 创建标签名到 tag_id 的映射
            return {tag_name.lower(): tag_id for tag_id, tag_name in tags}
    except Exception as e:
        logger.error(f"Error fetching tag IDs: {e}")
        return {}

# 批量查找 performers 的 performer_id
def get_performers_ids(performer_names):
    try:
        with sqlite3.connect(DB_PATH) as conn:
            cursor = conn.cursor()
            query = "SELECT id, name FROM performers WHERE LOWER(name) IN ({})".format(
                ','.join(['?'] * len(performer_names))
            )
            cursor.execute(query, [name.lower() for name in performer_names])
            performers = cursor.fetchall()
            return {performer_name.lower(): performer_id for performer_id, performer_name in performers}
    except Exception as e:
        logger.error(f"Error fetching performer IDs: {e}")
        return {}

# 插入数据到 performers_tags 表
def insert_performer_tag(performer_id, tag_id):
    try:
        with sqlite3.connect(DB_PATH) as conn:
            cursor = conn.cursor()
            # 检查 performers_tags 中是否已有此条数据
            cursor.execute("SELECT 1 FROM performers_tags WHERE performer_id = ? AND tag_id = ?", (performer_id, tag_id))
            if not cursor.fetchone():
                cursor.execute("INSERT INTO performers_tags (performer_id, tag_id) VALUES (?, ?)", (performer_id, tag_id))
                conn.commit()
                logger.info(f"Inserted performer_id {performer_id} and tag_id {tag_id} into performers_tags.")
            else:
                logger.info(f"Entry for performer_id {performer_id} and tag_id {tag_id} already exists in performers_tags.")
    except Exception as e:
        logger.error(f"Error inserting into performers_tags: {e}")

# 处理 detail.json 文件
def process_detail_json(detail_file):
    try:
        with open(detail_file, 'r', encoding='utf-8') as f:
            data = json.load(f)

        # 获取所有标签的 ID
        tag_ids = get_all_tag_ids()

        # 收集需要查询的 performers.name
        performer_names = [entry.get('person') for entry in data]

        # 批量查询 performers.id
        performer_ids = get_performers_ids(performer_names)

        for entry in data:
            person = entry.get('person')
            vixen_cnt = entry.get('vixen_cnt', 0)
            blacked_cnt = entry.get('blacked_cnt', 0)
            tushy_cnt = entry.get('tushy_cnt', 0)
            x_art_cnt = entry.get('x_art_cnt', 0)

            # 获取 performer_id
            performer_id = performer_ids.get(person.lower())
            if not performer_id:
                continue  # 如果找不到 performer_id，跳过此条数据

            # 处理每个 tag（vixen, blacked, tushy, x-art）
            for tag_name, count in zip(TAG_LIST, [vixen_cnt, blacked_cnt, tushy_cnt, x_art_cnt]):
                if count > 0:
                    tag_id = tag_ids.get(tag_name)
                    if tag_id:
                        insert_performer_tag(performer_id, tag_id)
    except Exception as e:
        logger.error(f"Error processing {detail_file}: {e}")

# 主函数
def main():
    detail_file = 'detail.json'  # 输入文件路径，可以替换成实际路径
    process_detail_json(detail_file)

if __name__ == "__main__":
    main()