# app/sync2/run_motie_demo.py
from __future__ import annotations
import os
from collections import Counter
from datetime import datetime
from app.sync2.pipeline import (
    start_batch, finish_batch,
    ingest_staging, build_candidates, auto_decide, seed_batch_as_new, apply_decisions,
    load_motie_from_existing
)
from app.services.supabase_service import get_client

sb = get_client()

def run(bootstrap: bool = False):
    batch_id = f"motie-{datetime.now().strftime('%Y%m%d-%H%M%S')}"
    print(f"[+] batch_id = {batch_id}")

    start_batch(batch_id)

    rows = load_motie_from_existing(limit=8000)
    print(f"[+] staging rows(MOTIE) = {len(rows)}")
    ingest_staging(batch_id, rows)

    if bootstrap:
        print("[+] bootstrap mode: create persons & AUTO decisions for all staging rows")
        seed_batch_as_new(batch_id)
        apply_decisions(batch_id)
        finish_batch(batch_id, "COMPLETED", {"MOTIE": len(rows)})
        summary(batch_id)
        return

    print("[+] build candidates…")
    build_candidates(batch_id)
    print("[+] auto decide…")
    auto_decide(batch_id)
    print("[+] apply decisions…")
    apply_decisions(batch_id)
    ss = summary(batch_id)  # <-- 요약 딕셔너리 받기
    finish_batch(batch_id, status="COMPLETED", source_summary=ss)

    summary(batch_id)

def summary(batch_id: str):
    # 이벤트 집계
    ev_rows = sb.table("gov_staff_events") \
        .select("event_type") \
        .eq("batch_id", batch_id) \
        .execute().data or []
    ev = Counter(r.get("event_type") or "UNKNOWN" for r in ev_rows)

    # 의사결정 집계
    dec_rows = sb.table("match_decisions") \
        .select("decision") \
        .eq("batch_id", batch_id) \
        .execute().data or []
    dec = Counter(r.get("decision") or "UNKNOWN" for r in dec_rows)

    # 콘솔 출력(옵션)
    print("\n== Events (by type) ==")
    for k, v in ev.items():
        print(f"  {k:16s} {v}")
    print("== Decisions (by kind) ==")
    for k, v in dec.items():
        print(f"  {k:16s} {v}")

    # finish_batch에 넣어줄 요약 리턴
    return {
        "events": dict(ev),
        "decisions": dict(dec),
    }

if __name__ == "__main__":
    bootstrap = os.getenv("BOOTSTRAP", "0") in ("1", "true", "True")
    run(bootstrap=bootstrap)
