"""
需求归属分类写入工具

批量向 MySQL demand_belong_category 表插入 name + category_id + reason。
"""
from __future__ import annotations

import logging
from typing import Any

from supply_agent.tools import tool
from supply_infra.db.repositories.demand_belong_category_repo import (
    DemandBelongCategoryRepository,
)
from supply_infra.db.session import get_session

logger = logging.getLogger(__name__)


def _normalize_items(items: list[dict[str, Any]]) -> tuple[list[dict], list[str]]:
    """校验并规范化待插入行，返回 (rows, errors)。"""
    rows: list[dict] = []
    errors: list[str] = []
    seen_names: set[str] = set()

    for idx, item in enumerate(items):
        if not isinstance(item, dict):
            errors.append(f"第 {idx} 项不是对象")
            continue

        name = item.get("name")
        category_id = item.get("category_id")
        reason = item.get("reason")

        if name is None or (isinstance(name, str) and not name.strip()):
            errors.append(f"第 {idx} 项缺少有效 name")
            continue
        if category_id is None:
            errors.append(f"第 {idx} 项缺少 category_id")
            continue

        try:
            category_id_int = int(category_id)
        except (TypeError, ValueError):
            errors.append(f"第 {idx} 项 category_id 无效: {category_id!r}")
            continue

        name_str = str(name).strip()
        if name_str in seen_names:
            errors.append(f"第 {idx} 项 name 在本次请求中重复: {name_str}")
            continue
        seen_names.add(name_str)

        reason_str: str | None = None
        if reason is not None:
            reason_str = str(reason).strip() or None

        rows.append(
            {
                "name": name_str,
                "category_id": category_id_int,
                "reason": reason_str,
                "is_delete": 0,
            }
        )

    return rows, errors


@tool
def batch_insert_demand_belong_category(items: list[dict[str, Any]]) -> str:
    """
    批量插入需求归属分类

    向 demand_belong_category 表批量写入数据。name 有唯一约束，已存在的名称会被忽略。

    Args:
        items: 待插入列表，每项为 {"name": "需求名称", "category_id": 分类id, "reason": "归属原因"}。
               reason 可选。
               例如：[{"name": "表演需求", "category_id": 19, "reason": "属于表演类内容"},
                     {"name": "理念需求", "category_id": 2, "reason": "偏理念表达"}]

    Returns:
        插入结果摘要，包含成功条数与跳过/失败说明。
    """
    if not items:
        return "items 不能为空"

    rows, errors = _normalize_items(items)
    if not rows:
        detail = "；".join(errors) if errors else "无有效数据"
        return f"没有可插入的数据: {detail}"

    try:
        with get_session() as session:
            repo = DemandBelongCategoryRepository(session)
            inserted = repo.bulk_insert_ignore(rows)

        skipped = len(rows) - inserted
        parts = [f"提交 {len(rows)} 条，成功插入 {inserted} 条"]
        if skipped > 0:
            parts.append(f"因 name 已存在忽略 {skipped} 条")
        if errors:
            parts.append(f"校验失败 {len(errors)} 条: " + "；".join(errors))

        message = "。".join(parts)
        logger.info("batch_insert_demand_belong_category completed: %s", message)
        return message

    except Exception as e:
        logger.error("batch_insert_demand_belong_category failed: %s", e, exc_info=True)
        return f"批量插入需求归属分类失败: {e}"
