import os
from typing import List, Dict
from supabase import Client
from .supabase_service import get_supabase

ORG_TABLE = "motie_org"
VIP_TABLE = "motie_vip"

def clear_org(sb: Client | None = None) -> None:
    sb = sb or get_supabase()
    # 전체 삭제
    sb.table(ORG_TABLE).delete().neq("id", -1).execute()

def bulk_insert_org(rows: List[Dict], sb: Client | None = None) -> int:
    """
    rows: [{department, name, position, task, phone}, ...]
    반환: 삽입 건수
    """
    if not rows:
        return 0
    sb = sb or get_supabase()
    res = sb.table(ORG_TABLE).insert(rows).execute()
    return len(res.data or [])

def clear_vip(sb: Client | None = None) -> None:
    sb = sb or get_supabase()
    sb.table(VIP_TABLE).delete().neq("id", -1).execute()

def bulk_insert_vip(rows: List[Dict], sb: Client | None = None) -> int:
    if not rows:
        return 0
    sb = sb or get_supabase()
    res = sb.table(VIP_TABLE).insert(rows).execute()
    return len(res.data or [])

def select_vip_by_department(department: str, positions: List[str], sb: Client | None = None) -> List[Dict]:
    """
    motie_org에서 department 일치 + position IN (...) 조건으로 추출
    """
    sb = sb or get_supabase()
    q = (sb.table(ORG_TABLE)
           .select("department,name,position,task,phone")
           .eq("department", department)
           .in_("position", positions))
    res = q.execute()
    return res.data or []

def search_org(keyword: str, limit: int = 50, sb: Client | None = None) -> List[Dict]:
    """
    이름(name) 또는 부서(department)에 keyword가 '포함'(ILIKE)된 행 검색
    """
    if not keyword:
        return []
    sb = sb or get_supabase()
    pattern = f".{keyword}."  # supabase-py에서 ILIKE는 'name.ilike.%foo%' 형식 → 점(.) 대신 % 로 내부에서 처리됨
    # 일부 버전에서 % 이스케이프 이슈가 있어 문자열로 직접 넣음
    cond = f"name.ilike.%{keyword}%,department.ilike.%{keyword}%"
    res = (sb.table(ORG_TABLE)
             .select("department,name,position,task,phone")
             .or_(cond)
             .limit(limit)
             .execute())
    return res.data or []
