from typing import List, Dict
from .supabase_service import get_client, logger

def _search_table(table: str, keyword: str, limit: int = 10, source: str | None = None) -> List[Dict]:
    sb = get_client()
    # 이름/부서/직위/업무(task)에서 부분 일치(대소문자 무시)
    # Supabase의 ilike는 단일 컬럼에만 걸리므로 or연산으로 결합
    sel = "department,name,position,task,phone"
    q = sb.table(table).select(sel).ilike("name", f"%{keyword}%").limit(limit).execute()
    rows = q.data or []

    if len(rows) < limit:
        remain = limit - len(rows)
        q2 = sb.table(table).select(sel).ilike("department", f"%{keyword}%").limit(remain).execute()
        rows += q2.data or []

    if len(rows) < limit:
        remain = limit - len(rows)
        q3 = sb.table(table).select(sel).ilike("position", f"%{keyword}%").limit(remain).execute()
        rows += q3.data or []

    if len(rows) < limit:
        remain = limit - len(rows)
        q4 = sb.table(table).select(sel).ilike("task", f"%{keyword}%").limit(remain).execute()
        rows += q4.data or []

    # 출처 주입 및 중복 제거(출처 포함해 구분)
    uniq: List[Dict] = []
    seen = set()
    for r in rows:
        if source and "source" not in r:
            r["source"] = source
        key = (r.get("source"), r.get("name"), r.get("department"), r.get("position"), r.get("task"))
        if key not in seen:
            uniq.append(r)
            seen.add(key)
    return uniq[:limit]

def search_people(keyword: str, limit: int = 10) -> List[Dict]:
    """산업부(MOTIE) + 기재부(MOEF) 통합 검색. 결과에 source 필드를 포함합니다."""
    motie = _search_table("motie_org", keyword, limit, source="MOTIE")
    remain = max(0, limit - len(motie))
    moef = _search_table("moef_org", keyword, remain if remain else limit, source="MOEF")
    return (motie + moef)[:limit]
