# -*- coding: utf-8 -*-
"""
STEP108-02: Workday latest collected draft priority patch

실행:
  cd /d D:\honghee\blog_api
  python tools\patch_step108_latest_collected_draft.py
"""

from pathlib import Path
from datetime import datetime

ROOT = Path(__file__).resolve().parents[1]
TARGET = ROOT / "core" / "workday_pipeline.py"

if not TARGET.exists():
    raise FileNotFoundError(TARGET)

text = TARGET.read_text(encoding="utf-8", errors="replace")

backup = TARGET.with_name(
    f"workday_pipeline_backup_latest_collected_{datetime.now().strftime('%Y%m%d_%H%M%S')}.py"
)
backup.write_text(text, encoding="utf-8")
print("[BACKUP]", backup)

helper_anchor = """
def fetch_next_pending_queue(conn, realtor_id):
    with conn.cursor() as cur:
        cur.execute(\"\"\"
            SELECT *
            FROM blog_publish_queue
            WHERE realtor_id = %s
              AND COALESCE(queue_status, '') IN ('pending', 'waiting', 'ready', 'failed')
            ORDER BY id DESC
            LIMIT 1
        \"\"\", (int(realtor_id),))
        return cur.fetchone()
"""

helper_insert = helper_anchor + r