# -*- coding: utf-8 -*-
"""
STEP104 patch for workers/publish_worker_step104.py

실행 위치:
  cd /d D:\honghee\blog_api
  python tools\patch_publish_worker_step104.py

전제:
  1) workers\publish_worker_step104.py 존재
  2) workers\publish_modules\*.py 존재
"""

from pathlib import Path
from datetime import datetime
import re
import sys


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

if not TARGET.exists():
    print("[ERROR] not found:", TARGET)
    sys.exit(1)

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

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


# ------------------------------------------------------------
# 1) STEP104 모듈 import 추가
# ------------------------------------------------------------
imports = """
# STEP104 publish behavior modules
from publish_modules.human_typing import human_type_title
from publish_modules.tail_comment import type_tail_comment_after_body
from publish_modules.review_behavior import (
    human_short_review_before_publish,
    human_wait_before_publish as step104_human_wait_before_publish,
)
"""

if "from publish_modules.human_typing import human_type_title" not in text:
    anchor = "from db import get_conn\n"
    if anchor not in text:
        print("[ERROR] import anchor not found")
        sys.exit(1)
    text = text.replace(anchor, anchor + imports + "\n")
    print("[PATCH] STEP104 imports inserted")
else:
    print("[SKIP] STEP104 imports already exists")


# ------------------------------------------------------------
# 2) 제목 입력: 고정 delay → 랜덤 타이핑
# ------------------------------------------------------------
pattern_title = re.compile(
    r"""page\.keyboard\.type\(\s*
\s*publish_title\[:80\],\s*
\s*delay=80\s*
\s*\)""",
    re.MULTILINE,
)

new_title = "human_type_title(page, publish_title[:80])"

text, count_title = pattern_title.subn(new_title, text)

if count_title:
    print("[PATCH] title typing randomized:", count_title)
else:
    print("[WARN] title typing pattern not found. already patched or structure changed.")


# ------------------------------------------------------------
# 3) 본문 입력 성공 후 하단 코멘트 타이핑 + 짧은 검토
# ------------------------------------------------------------
tail_marker = "STEP104-02: 전체 렌더링 붙여넣기 후 하단 코멘트 실제 타이핑"

if tail_marker not in text:
    anchor = """
            # -------------------------------------------------
            # 에디터 포커스 제거
            # -------------------------------------------------
"""
    insert = f"""
            # -------------------------------------------------
            # {tail_marker}
            # -------------------------------------------------

            type_tail_comment_after_body(
                page=page,
                frame=write_frame,
                draft=queue,
                queue=queue,
            )

            human_short_review_before_publish(page)

"""
    if anchor not in text:
        print("[ERROR] editor blur anchor not found")
        sys.exit(1)

    text = text.replace(anchor, insert + anchor, 1)
    print("[PATCH] tail comment typing inserted")
else:
    print("[SKIP] tail comment typing already exists")


# ------------------------------------------------------------
# 4) 최종 발행 전 검토 대기
#    STEP103 5~10분 대기가 있으면 30~120초로 교체
#    없으면 최종 발행 직전 추가
# ------------------------------------------------------------
wait_marker = "STEP104-02: 최종 발행 전 30~120초 검토 대기"

# 기존 STEP103 wait 교체
pattern_step103_wait = re.compile(
    r"""human_wait_before_publish\(\s*
\s*page,\s*
\s*min_seconds=300,\s*
\s*max_seconds=600\s*
\s*\)""",
    re.MULTILINE,
)

replacement_wait = """step104_human_wait_before_publish(
                page,
                min_seconds=30,
                max_seconds=120
            )"""

text, count_wait_replace = pattern_step103_wait.subn(replacement_wait, text)

if count_wait_replace:
    print("[PATCH] STEP103 long wait replaced:", count_wait_replace)

if wait_marker not in text and count_wait_replace == 0:
    anchor = """
            page.wait_for_timeout(1200)

            # -------------------------------------------------
            # 최종 발행
            # -------------------------------------------------
"""
    insert = f"""
            page.wait_for_timeout(1200)

            # -------------------------------------------------
            # {wait_marker}
            # -------------------------------------------------

            step104_human_wait_before_publish(
                page,
                min_seconds=30,
                max_seconds=120
            )

            # -------------------------------------------------
            # 최종 발행
            # -------------------------------------------------
"""
    if anchor not in text:
        print("[ERROR] final publish anchor not found")
        sys.exit(1)

    text = text.replace(anchor, insert, 1)
    print("[PATCH] final publish wait inserted")
elif count_wait_replace:
    print("[INFO] final publish wait replaced with step104 function")
else:
    print("[SKIP] final publish wait already exists")


TARGET.write_text(text, encoding="utf-8")
print("[DONE] patched:", TARGET)
print("[NEXT] test: python workers\\publish_worker_step104.py --realtor-id 1 --limit 1 --no-db-lock")
