"""인물 이름 매칭 유틸리티 — shot characters ↔ entity name fuzzy matching.

shot_extract의 characters는 이름("백련")이고, entity_canon은 "백련(변신)" 등
괄호 접미사가 붙을 수 있음. base_name 기반으로 매칭.
"""
import re

_PAREN_RE = re.compile(r'\s*[\(（].*$')


def base_name(name: str) -> str:
    """괄호 이전 부분 추출: '백련(변신)' → '백련'."""
    return _PAREN_RE.sub('', name).strip()


def match_shot_char(shot_name: str, entity_name: str) -> bool:
    """shot characters 이름이 entity name과 매칭되는지 판단.

    1) exact match
    2) base_name match (괄호 제거 후)
    3) entity_name이 shot_name으로 시작하는 경우
    """
    if not shot_name or not entity_name:
        return False
    if shot_name == entity_name:
        return True
    if shot_name == base_name(entity_name):
        return True
    if len(shot_name) >= 2 and entity_name.startswith(shot_name):
        return True
    return False


def filter_ve_by_shot_chars(
    director_ve: list,
    shot_char_names: set,
    entity_short_name: dict,
) -> list:
    """director VE(short_id list)에서 shot characters에 해당하는 것만 필터.

    인물(C*)은 shot_char_names와 매칭, 비인물(L*/P*)은 그대로 통과.
    """
    result = []
    for sid in director_ve:
        if not sid.startswith("C"):
            result.append(sid)
            continue
        ename = entity_short_name.get(sid, "")
        if any(match_shot_char(cn, ename) for cn in shot_char_names):
            result.append(sid)
    return result
