# app/sync2/run_sample_newdata.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):
    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():
    """
    초기 '현재 재직' 샘플 (MOTIE):
      - 이지훈    (소재부품과,  주무관, 010-1000-1000, 업무: 소재 총괄) → 이번 배치에서 부서+전화+업무 변경
      - 박서연    (에너지정책과, 사무관, 010-1111-1111, 업무: 에너지 정책) → 이번 배치에서 직위변경
      - 김민수_A  (디지털혁신과, 주무관, 010-2222-2222, 업무: DX 추진)
      - 김민수_B  (무역정책관실, 사무관, 010-3333-3333, 업무: 무역 지원)
      - 최보람    (반도체과,    사무관, 010-4444-4444, 업무: 반도체 진흥) → 이번 배치 미포함(퇴사 이벤트 유도)
      - 홍길동_A  (소재부품과,  주무관, 02-5000-1001)
      - 홍길동_B  (무역정책관실, 주무관, 02-5000-2002)
    """
    persons = ["이지훈", "박서연", "김민수", "김민수", "최보람", "홍길동", "홍길동"]
    created = []
    for nm in persons:
        r = sb.table("person_registry").insert({"canonical_name": nm}).execute().data
        created.append(r[0]["person_id"])
    (pid_이지훈, pid_박서연, pid_김민수A, pid_김민수B,
     pid_최보람, pid_홍A, pid_홍B) = 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},
        {"person_id": pid_박서연, "source": "MOTIE", "name": "박서연", "department": "에너지정책과",         "position": "사무관", "phone": "010-1111-1111", "task": "에너지 정책", "is_active": True, "updated_at": now},
        {"person_id": pid_김민수A,"source": "MOTIE", "name": "김민수", "department": "디지털혁신과",         "position": "주무관", "phone": "010-2222-2222", "task": "DX 추진",    "is_active": True, "updated_at": now},
        {"person_id": pid_김민수B,"source": "MOTIE", "name": "김민수", "department": "무역정책관실",         "position": "사무관", "phone": "010-3333-3333", "task": "무역 지원",  "is_active": True, "updated_at": now},
        {"person_id": pid_최보람, "source": "MOTIE", "name": "최보람", "department": "반도체과",             "position": "사무관", "phone": "010-4444-4444", "task": "반도체 진흥","is_active": True, "updated_at": now},
        {"person_id": pid_홍A,   "source": "MOTIE", "name": "홍길동", "department": "산업정책실 소재부품과", "position": "주무관", "phone": "02-5000-1001",  "task": "-",         "is_active": True, "updated_at": now},
        {"person_id": pid_홍B,   "source": "MOTIE", "name": "홍길동", "department": "무역정책관실",         "position": "주무관", "phone": "02-5000-2002",  "task": "-",         "is_active": True, "updated_at": now},
    ]
    for row in rows:
        sb.table("gov_staff_current").insert(row).execute()

def make_staging_rows() -> List[Dict[str, Any]]:
    """
    이번 배치(스테이징):
      - [AUTO]     이지훈  : (부서 이동 + 전화 변경 + 업무 변경)
      - [AUTO?]    박서연  : (직위변경)
      - [PENDING]  김민수  : (동명이인 2명 존재, 전화 공란 → 모호)
      - [NEW-수동] 정해인  : (후보 없음 → '신규로 생성' 선택 필요)
      - [PENDING]  최수지  : (후보 없음 → 신규 여부 판단)
      - [PENDING]  홍길동×2: (동명이인 동시 이동, 둘 다 후보로 떠서 수동 매칭 필요)
      - [DEPARTED] 최보람  : (이번 배치 미포함 → 자동 퇴사 감지)
    """
    return [
        # 이지훈: 소재부품과 → 전략기획과, 전화/업무 변경
        {"source": "MOTIE", "name": "이지훈", "department": "산업정책실 전략기획과", "position": "주무관", "phone": "010-1000-5555", "task": "전략 조정", "raw": {}},
        # 박서연: 직위 사무관 → 과장
        {"source": "MOTIE", "name": "박서연", "department": "에너지정책과", "position": "과장", "phone": "010-1111-1111", "task": "에너지 정책", "raw": {}},
        # 김민수(모호): 전화 없음, 부서 '정책지원과' → A/B 둘 다 일치 일부(이름/직위 등)
        {"source": "MOTIE", "name": "김민수", "department": "정책지원과", "position": "주무관", "phone": "", "task": "지원", "raw": {}},
        # 정해인: 신규 입사 후보(후보 없음)
        {"source": "MOTIE", "name": "정해인", "department": "에너지정책과", "position": "주무관", "phone": "010-9999-9999", "task": "정책 지원", "raw": {}},
        # 최수지: 신규/모호(후보 없음)
        {"source": "MOTIE", "name": "최수지", "department": "디지털혁신과", "position": "사무관", "phone": "", "task": "DX 추진", "raw": {}},
        # 홍길동 × 2 : 동시에 다른 부서로 이동(동명이인 매칭 필요)
        {"source": "MOTIE", "name": "홍길동", "department": "원전정책과", "position": "주무관", "phone": "", "task": "-", "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("sample2-%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.90, margin=0.15)

    # 자동 적용까지 바로 보고 싶으면 APPLY=1 로 실행
    if os.getenv("APPLY") == "1":
        apply_decisions(batch_id)

    # 요약
    print("[=] Ready. Open /sync → 배치 선택:", batch_id)
    if os.getenv("APPLY") != "1":
        print("[*] 아직 적용 전입니다. 화면 상단의 “적용(Apply Decisions)” 버튼을 눌러 이벤트를 생성하세요.")

    # 소스 건수 요약(대충)
    finish_batch(batch_id, status="COMPLETED", source_summary={"MOTIE": len(stages)})

if __name__ == "__main__":
    run()
