# app/sync2/run_sample_demo.py
from __future__ import annotations

import os
from datetime import datetime
from typing import List, Dict, Any

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

sb = get_client()

def now_id(prefix: str) -> str:
    return f"{prefix}-{datetime.now().strftime('%Y%m%d-%H%M%S')}"

# -------------------------------
# 샘플 데이터 (MOTIE 전용)
# v1: 기준선(부트스트랩)
# v2: 이동/변경/퇴사/신규 혼합
# -------------------------------
def sample_rows_v1() -> List[Dict[str, Any]]:
    return [
        {
            "source": "MOTIE",
            "name": "김하나",
            "department": "산업정책실 산업혁신과",
            "position": "사무관",
            "phone": "02-1234-0001",
            "raw": {"note": "baseline"},
        },
        {
            "source": "MOTIE",
            "name": "이지수",
            "department": "무역투자실 FTA정책과",
            "position": "서기관",
            "phone": "02-1234-0002",
            "raw": {"note": "baseline"},
        },
        {
            "source": "MOTIE",
            "name": "박민호",
            "department": "산업정책실 소재부품과",
            "position": "주무관",
            "phone": "02-1234-0003",
            "raw": {"note": "baseline"},
        },
    ]

def sample_rows_v2() -> List[Dict[str, Any]]:
    return [
        # 김하나: 부서 이동(전화 유지) -> MOVE
        {
            "source": "MOTIE",
            "name": "김하나",
            "department": "무역투자실 FTA정책과",
            "position": "사무관",
            "phone": "02-1234-0001",
            "raw": {"note": "moved department"},
        },
        # 이지수: 직위+전화 변경 -> CHANGE_POSITION + CHANGE_PHONE
        {
            "source": "MOTIE",
            "name": "이지수",
            "department": "무역투자실 FTA정책과",
            "position": "국장",
            "phone": "02-9999-0002",
            "raw": {"note": "promoted + new phone"},
        },
        # 최아라: 신규 -> NEW
        {
            "source": "MOTIE",
            "name": "최아라",
            "department": "산업정책실 산업혁신과",
            "position": "사무관",
            "phone": "02-1234-0004",
            "raw": {"note": "new hire"},
        },
        # 박민호: v2에 등장하지 않음 -> DEPARTED 발생 예정
    ]

# -------------------------------
# 배치 실행 유틸
# -------------------------------
def run_batch(batch_id: str, rows: List[Dict[str, Any]], bootstrap: bool = False):
    print(f"[+] start batch: {batch_id} (bootstrap={bootstrap})")
    start_batch(batch_id)
    ingest_staging(batch_id, rows)
    if bootstrap:
        # 최초 기준선: 모두 신규 person_id로 등록
        seed_batch_as_new(batch_id)
    else:
        # 매칭 후보 생성/자동결정(임계 낮게 설정해 테스트가 AUTO로 잘 붙도록)
        build_candidates(batch_id)
        auto_decide(batch_id, hi=0.20, margin=0.05)
    apply_decisions(batch_id)
    finish_batch(batch_id, status="COMPLETED", source_summary={"MOTIE": len(rows)})
    print(f"[+] finished batch: {batch_id}")

def print_summary(title: str, batch_id: str):
    print(f"\n=== {title} (batch_id={batch_id}) ===")
    ev = sb.table("gov_staff_events").select("*").eq("batch_id", batch_id).order("event_id").execute().data or []
    if not ev:
        print("(no events)")
    else:
        for e in ev:
            et = e.get("event_type")
            pid = e.get("person_id")
            src = e.get("source")
            prev = e.get("prev") or {}
            nxt  = e.get("next") or {}
            print(f"- {et:<15} person_id={pid} source={src} prev={prev} next={nxt}")

    cur = sb.table("gov_staff_current").select("*").order("person_id").execute().data or []
    print("\n--- gov_staff_current (snapshot) ---")
    for r in cur:
        print(f"{r['person_id']:>3} {r['source']} {r['name']} | {r.get('department')} | {r.get('position')} | {r.get('phone')} | active={r.get('is_active')}")

def main():
    # 1) 기준선 배치 (부트스트랩)
    b1 = now_id("sample-v1")
    run_batch(b1, sample_rows_v1(), bootstrap=True)
    print_summary("AFTER V1", b1)

    # 2) 변경 배치 (일반 실행)
    b2 = now_id("sample-v2")
    run_batch(b2, sample_rows_v2(), bootstrap=False)
    print_summary("AFTER V2", b2)

if __name__ == "__main__":
    main()
