# app/sync2/run_sample_pending.py
from __future__ import annotations
import os
from datetime import datetime
from typing import Dict, Any, List

from app.services.supabase_service import get_client
from app.sync2.pipeline import (
    start_batch, finish_batch,
    ingest_staging, build_candidates, auto_decide, apply_decisions
)

sb = get_client()

def _clear_table_all(table: str, key_col: str, numeric: bool = False):
    """
    Supabase(PostgREST)는 DELETE에 필터가 필요해서,
    - numeric=True  → key_col > 0 로 전부 삭제(시퀀스/양수 PK 가정)
    - numeric=False → key_col != '__never__' 로 전부 삭제(문자열 PK 가정)
    """
    try:
        q = sb.table(table).delete()
        q = q.gt(key_col, 0) if numeric else q.neq(key_col, "__never__")
        q.execute()
    except Exception as e:
        print(f"[WARN] clear {table}: {e}")

def reset_all():
    print("[*] RESET=1 detected → reset all govtrack tables")
    _clear_table_all("gov_staff_events",   "batch_id")                   # text
    _clear_table_all("match_decisions",    "batch_id")                   # text
    _clear_table_all("match_candidates",   "batch_id")                   # text
    _clear_table_all("staging_gov_staff",  "batch_id")                   # text
    _clear_table_all("gov_staff_current",  "person_id", numeric=True)    # bigint
    _clear_table_all("person_registry",    "person_id", numeric=True)    # bigint
    _clear_table_all("ingest_batches",     "batch_id")                   # text

def seed_baseline_current():
    """
    현재 재직(기준) 상태를 몇 명 만들어둠 (source='MOTIE')
      - 이서준(정책과 과장, 010-1000-1000)
      - 김민수A(산업정책과 사무관, 010-1111-1111)
      - 김민수B(에너지과   주무관, 010-2222-2222)
      - 박영희(소재과     주무관, 010-3333-3333)
      - 문지호(반도체과   사무관, 010-4444-4444) ← 이번 배치에서 제외 → DEPARTED 유도
    """
    # person_registry
    created = []
    for nm in ["이서준", "김민수", "김민수", "박영희", "문지호"]:
        r = sb.table("person_registry").insert({"canonical_name": nm}).execute().data
        created.append(r[0]["person_id"])
    pid_이서준, pid_김민수A, pid_김민수B, pid_박영희, pid_문지호 = created

    now = datetime.utcnow().isoformat()
    rows = [
        {"person_id": pid_이서준, "source": "MOTIE", "name": "이서준", "department": "정책과",     "position": "과장",   "phone": "010-1000-1000", "task": "정책 총괄",  "is_active": True, "updated_at": now, "last_seen_batch": None},
        {"person_id": pid_김민수A,"source": "MOTIE", "name": "김민수", "department": "산업정책과", "position": "사무관", "phone": "010-1111-1111", "task": "정책 기획",  "is_active": True, "updated_at": now, "last_seen_batch": None},
        {"person_id": pid_김민수B,"source": "MOTIE", "name": "김민수", "department": "에너지과",   "position": "주무관", "phone": "010-2222-2222", "task": "에너지 업무","is_active": True, "updated_at": now, "last_seen_batch": None},
        {"person_id": pid_박영희, "source": "MOTIE", "name": "박영희", "department": "소재과",     "position": "주무관", "phone": "010-3333-3333", "task": "소재 정책",  "is_active": True, "updated_at": now, "last_seen_batch": None},
        {"person_id": pid_문지호, "source": "MOTIE", "name": "문지호", "department": "반도체과",   "position": "사무관", "phone": "010-4444-4444", "task": "반도체 진흥","is_active": True, "updated_at": now, "last_seen_batch": None},
    ]
    for row in rows:
        sb.table("gov_staff_current").insert(row).execute()

def make_staging_rows() -> List[Dict[str, Any]]:
    """
    이번 배치(스테이징):
      - [AUTO]   이서준: 정책과 → 미래전략과 (MOVE)
      - [KEEP]   김민수A: 동일
      - [KEEP]   김민수B: 동일
      - [KEEP]   박영희  : 동일
      - [PENDING]최수지  : 신규 후보 없음
      - [PENDING]김민수? : 전화 없음 + 애매 → 모호
      - [DEPARTED] 문지호: 이번 배치 미포함
    """
    return [
        {"source": "MOTIE", "name": "이서준", "department": "미래전략과", "position": "과장",   "phone": "010-1000-1000", "task": "정책 총괄",  "raw": {}},
        {"source": "MOTIE", "name": "김민수", "department": "산업정책과", "position": "사무관", "phone": "010-1111-1111", "task": "정책 기획",  "raw": {}},
        {"source": "MOTIE", "name": "김민수", "department": "에너지과",   "position": "주무관", "phone": "010-2222-2222", "task": "এ너지 업무", "raw": {}},
        {"source": "MOTIE", "name": "박영희", "department": "소재과",     "position": "주무관", "phone": "010-3333-3333", "task": "소재 정책",  "raw": {}},
        {"source": "MOTIE", "name": "최수지", "department": "디지털혁신과", "position": "사무관", "phone": "",             "task": "DX 추진",    "raw": {}},
        {"source": "MOTIE", "name": "김민수", "department": "정책지원과", "position": "주무관", "phone": "",             "task": "지원",       "raw": {}},
    ]

def run():
    if os.getenv("RESET") == "1":
        reset_all()

    seed_baseline_current()

    batch_id = datetime.utcnow().strftime("sample-%Y%m%d-%H%M%S")
    print(f"[+] batch_id = {batch_id}")

    start_batch(batch_id)

    stages = make_staging_rows()
    ingest_staging(batch_id, stages)

    build_candidates(batch_id)
    # 임계값/마진은 PENDING이 조금 나오게 다소 빡세게
    auto_decide(batch_id, hi=0.85, margin=0.10)

    apply_decisions(batch_id)

    # 요약 출력(파이썬 카운트)
    events = sb.table("gov_staff_events").select("*").eq("batch_id", batch_id).execute().data or []
    counts: Dict[str, int] = {}
    for e in events:
        et = e.get("event_type", "UNKNOWN")
        counts[et] = counts.get(et, 0) + 1

    finish_batch(batch_id, status="COMPLETED", source_summary={"MOTIE": len(stages)})
    print("[=] Event counts:", counts)
    print("[=] Done. Open:  /sync  → select batch", batch_id)

if __name__ == "__main__":
    run()
