# services/motie_org_service.py

from services.motie_org_parser import get_last_emp_page, parse_employee_page
from supabase import create_client
import os

SUPABASE_URL = os.getenv("SUPABASE_URL")
SUPABASE_KEY = os.getenv("SUPABASE_KEY")
supabase = create_client(SUPABASE_URL, SUPABASE_KEY)

def update_motie_org_table():
    # 1️⃣ 전체 페이지 순회하며 직원 정보 수집
    last_page = get_last_emp_page()
    print(f"🔄 총 {last_page}페이지에서 조직도 수집 시작...")

    all_employees = []

    for page in range(1, last_page + 1):
        print(f"📄 {page} 페이지 수집 중...")
        all_employees.extend(parse_employee_page(page))

    print(f"📦 총 수집된 직원 수: {len(all_employees)}")

    # 2️⃣ Supabase에서 기존 데이터 제거
    try:
        supabase.table("motie_org").delete().neq("name", "").execute()
        print("🧹 motie_org 기존 데이터 초기화 완료")
    except Exception as e:
        print(f"[❌] motie_org 초기화 실패: {e}")

    # 3️⃣ Supabase에 새 데이터 삽입
    try:
        for chunk in chunked(all_employees, 100):  # Supabase 제한 대비 chunking
            supabase.table("motie_org").insert(chunk).execute()
        print("✅ Supabase에 motie_org 조직도 저장 완료")
    except Exception as e:
        print(f"[❌] Supabase 삽입 실패: {e}")

# 🔧 Supabase 요청 chunk 분할 유틸
def chunked(data, size):
    for i in range(0, len(data), size):
        yield data[i:i + size]
