"""共享标签加载工具"""

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.models.literature import GlobalLiteratureTag, GlobalTag


async def load_tags_for_literature(db: AsyncSession, literature_ids: list[str]) -> dict[str, list[dict]]:
    """批量加载文献标签，返回 {literature_id: [{name_zh, path, category, is_major}]}"""
    if not literature_ids:
        return {}
    import uuid as _uuid
    uids = [_uuid.UUID(x) if isinstance(x, str) else x for x in literature_ids]
    result = await db.execute(
        select(GlobalLiteratureTag.literature_id, GlobalTag.id, GlobalTag.name_zh, GlobalTag.name_en, GlobalTag.path,
               GlobalTag.tag_category, GlobalLiteratureTag.is_major)
        .join(GlobalTag, GlobalLiteratureTag.tag_id == GlobalTag.id)
        .where(GlobalLiteratureTag.literature_id.in_(uids))
    )
    tags_map: dict[str, list[dict]] = {}
    for lit_id, tid, nz, ne, p, cat, maj in result:
        sid = str(lit_id)
        if sid not in tags_map:
            tags_map[sid] = []
        tags_map[sid].append({"id": str(tid), "name_zh": nz, "name_en": ne, "path": p, "category": cat, "is_major": maj})
    return tags_map
