from __future__ import annotations

from sqlalchemy.dialects.mysql import insert

from supply_infra.db.models.global_tree_element import GlobalTreeElement
from supply_infra.db.repositories.base import BaseRepository

_BATCH_SIZE = 1000


class GlobalTreeElementRepository(BaseRepository[GlobalTreeElement]):
    """全局树元素表 — INSERT IGNORE 按 (name, category_id) 唯一键去重。"""

    model = GlobalTreeElement

    def bulk_insert_ignore(self, rows: list[dict]) -> int:
        """批量插入，MySQL 自动忽略 (name, category_id) 重复行。"""
        if not rows:
            return 0

        inserted = 0
        for i in range(0, len(rows), _BATCH_SIZE):
            batch = rows[i : i + _BATCH_SIZE]
            stmt = insert(GlobalTreeElement).values(batch).prefix_with("IGNORE")
            result = self.session.execute(stmt)
            inserted += result.rowcount
        return inserted
