파이썬으로 네이버 쇼핑 커넥트 자동화하기 — 블로그 포스팅부터 인스타그램 릴스 자동 게시까지

블로그게시 예시

 

네이버 쇼핑 커넥트(브랜드 커넥트 제휴)로 받은 상품 링크를 블로그 글에 자동으로 붙이고, 같은 상품으로 인스타그램 릴스 영상까지 만들어 올리는 파이썬 자동화를 만들어 본 기록입니다. 중간에 겪은 삽질(PowerShell 쉼표, URL 인코딩, 에디터가 스타일을 지우는 문제 등)도 함께 정리했습니다.

⚠️ 쇼핑 커넥트는 공개 Open API 가 없습니다. 이 글은 본인 계정으로 로그인한 브라우저가 호출하는 요청을 그대로 재현하는 방식이라, 응답 형식이 예고 없이 바뀔 수 있고 운영 정책상 제한될 수 있습니다. 호출 빈도를 낮게 유지하고, 사용 전 브랜드 커넥트 운영정책을 꼭 확인하세요.


전체 구조

[쇼핑 커넥트]
   │  (로그인 쿠키로 내부 API 호출)
   ├─▶ 상품 조회 / 검색 / 제휴 링크 발급 ─▶ [네이버 블로그 봇] 글 상단 대가성 문구 + 하단 상품 목록
   │
   └─▶ 발급된 링크 목록 ─▶ sqlite 저장
                              │
                              ├─▶ 상품 이미지 → 세로 영상(ffmpeg) + 자막
                              └─▶ 인스타그램 Graph API 로 릴스 게시 (라즈베리파이 cron)

사용한 것: Python 3.9+, requests, playwright, beautifulsoup4, ffmpeg, firebase-admin(토큰·영상 임시 저장), sqlite.


1. 공개 API 가 없을 때: Playwright codegen 으로 흐름 녹화하기

먼저 "사람이 클릭하는 순서"를 코드로 뽑아봤습니다. Playwright 의 codegen 은 브라우저에서 한 동작을 파이썬 코드로 기록하고, 로그인 세션(쿠키)도 파일로 저장해 줍니다.

python -m playwright codegen --target python --save-storage=auth.json -o recorded.py https://brandconnect.naver.com/

로그인 → 상품 찾기 → 상품 클릭 → "링크 발급" → "링크 복사" 까지 한 번 해 보면 이런 코드가 나옵니다.

page.goto("https://brandconnect.naver.com/<SPACE_ID>/affiliate/products")
page.get_by_role("link", name="상품 찾기").click()
with page.expect_popup() as info:
    page.get_by_role("link", name="수수료 5% 판매가 ...").click()
detail = info.value
detail.get_by_role("button", name="링크 발급").click()
detail.get_by_role("button", name="확인").click()

🚨 주의: codegen 은 입력한 값을 그대로 기록합니다. 로그인 과정까지 녹화하면 아이디·비밀번호가 평문으로 파일에 남습니다. 녹화 직후 로그인 부분을 지우고, 그 파일은 절대 커밋/공유하지 마세요. 저는 녹화 후 비밀번호를 바꿨습니다. auth.json(로그인 쿠키)도 .gitignore 에 꼭 넣어 두세요.

또 하나 배운 점: 네이버 로그인은 자동화하면 캡차(영수증 문제 등)가 뜹니다. 로그인은 사람이 하고, 저장된 세션만 재사용하는 구조가 가장 안정적입니다.


2. 버튼 대신 API: 네트워크 요청 캡처

"링크 복사"는 클립보드로만 들어가서 코드로 값을 읽기 애매합니다. 그래서 링크 발급 버튼을 누를 때 어떤 요청이 나가는지 기록했습니다.

log = []

def on_response(resp):
    req = resp.request
    if "gw-brandconnect" not in req.url:
        return
    log.append({
        "method": req.method, "url": req.url, "status": resp.status,
        "post": req.post_data, "body": resp.text()[:3000],
    })

context = browser.new_context(storage_state="auth.json")
context.on("response", on_response)

요청 헤더에는 쿠키가 들어 있으니, 로그로 남길 때 cookie 같은 헤더는 가리는 게 좋습니다.

캡처 결과, 화면 뒤에서는 이런 요청들이 오가고 있었습니다(도메인 gw-brandconnect.naver.com, 헤더 x-space-id: <SPACE_ID>).

용도 요청
상품 단건 GET /affiliate/query/affiliate-products/{상품ID}
추천 상품 GET /affiliate/query/affiliate-products/recommend-by-shopping-promotions?category1Id=&limit= (limit 최대 10)
상품 검색 GET /affiliate/query/affiliate-products/search-by-query?query=&limit=
링크 발급 POST /affiliate/command/affiliate-urls?affiliateProductId={상품ID} 바디 {}
발급 링크 목록 POST /affiliate/query/affiliate-urls/search

재미있던 점은 상품 응답에 이미 shortenUrl 필드가 있다는 것. 발급 전엔 null, 발급 후엔 https://naver.me/xxxx 가 들어 있어서, 굳이 클립보드를 읽을 필요가 없었습니다.

그리고 인증은 네이버 로그인 쿠키(NID_AUT, NID_SES)만 있으면 충분했습니다(쿠키가 없으면 403). 덕분에 Playwright 없이 requests 만으로도 호출할 수 있습니다.

삽질 포인트: 추천 상품 API 에 limit=20 을 보냈더니 400 ConstraintViolationException. 웹 화면이 보내는 값(10)을 넘기면 안 됩니다. 캡처한 값 그대로 쓰기가 기본입니다.


3. 클라이언트 만들기: 이미 있으면 재사용, 없을 때만 발급

Playwright 의 storage_state(JSON) 쿠키를 requests 세션에 싣는 부분입니다.

import json
import requests

def build_session(auth_path: str, space_id: str) -> requests.Session:
    state = json.loads(open(auth_path, encoding="utf-8").read())
    s = requests.Session()
    for c in state.get("cookies", []):
        s.cookies.set(c["name"], c["value"], domain=c.get("domain"), path=c.get("path", "/"))
    s.headers.update({
        "accept": "application/json, text/plain, */*",
        "x-space-id": space_id,
    })
    return s

링크 발급은 중복 발급을 막는 것이 핵심입니다. 로컬 캐시 → 상품 응답의 shortenUrl → (그래도 없으면) 발급 순서로 확인하고, 하루 발급 상한과 호출 간격도 둡니다.

GW = "https://gw-brandconnect.naver.com"

def get_or_issue_link(s, product: dict, cache: dict, today: str, daily_limit: int = 10) -> str:
    pid = str(product["id"])
    if cache["links"].get(pid):                 # 1) 로컬 캐시
        return cache["links"][pid]
    if product.get("shortenUrl"):               # 2) 이미 발급된 링크
        cache["links"][pid] = product["shortenUrl"]
        return product["shortenUrl"]
    if cache["issues"].get(today, 0) >= daily_limit:
        raise RuntimeError(f"오늘 발급 상한({daily_limit}) 도달")

    r = s.post(f"{GW}/affiliate/command/affiliate-urls",   # 3) 새로 발급
               params={"affiliateProductId": pid}, json={}, timeout=20)
    if r.status_code in (401, 403):
        raise RuntimeError("로그인 세션 만료 - 직접 다시 로그인해 쿠키 파일을 교체하세요")
    r.raise_for_status()
    url = r.json()["url"]                      # {"affiliateUrlId": ..., "url": "https://naver.me/..."}
    cache["links"][pid] = url
    cache["issues"][today] = cache["issues"].get(today, 0) + 1
    return url

테스트는 실제 발급이 일어나지 않도록 가짜 request 객체로 작성했습니다.

class FakeRequest:
    def __init__(self, products):
        self.products = {p["id"]: p for p in products}
        self.posts = 0

    def post(self, url, **kw):
        self.posts += 1
        return FakeResp(200, {"affiliateUrlId": 1, "url": f"https://naver.me/new{self.posts}"})

4. 블로그 본문에 넣기: "빨간 대가성 문구"가 사라지는 문제

쇼핑 커넥트는 게시글에 대가성 문구를 눈에 띄게 넣어야 합니다. 그래서 글 맨 위에 빨간 글씨로 넣었는데… 발행해 보니 검은 글씨가 됐습니다.

원인은 제 코드였습니다. 티스토리/AI 가 만든 HTML 을 네이버 스마트에디터에 붙여 넣기 전에 정리하는 sanitize 함수가 <span> 을 풀고 모든 style 을 지우고 있었습니다(에디터가 잘라내는 태그를 줄이려는 의도였음).

해결: 표시(data-keep-color)가 달린 span 만 색/크기를 남기는 예외를 만들었습니다.

import re
from bs4 import BeautifulSoup

KEEP_COLOR = re.compile(r"(?<![-\w])color\s*:\s*(#[0-9a-fA-F]{3,6}|rgb\([\d\s,]+\)|[a-zA-Z]+)")
KEEP_SIZE = re.compile(r"font-size\s*:\s*(\d+(?:\.\d+)?(?:px|pt|em|rem|%))")

def sanitize(html: str) -> str:
    soup = BeautifulSoup(html, "lxml")
    for tag in list(soup.find_all(["div", "span"])):
        if tag.name == "span" and tag.has_attr("data-keep-color"):
            continue                      # 표시된 span 은 남김
        tag.unwrap()
    for span in soup.find_all("span"):
        style = span.get("style", "")
        kept = []
        if m := KEEP_COLOR.search(style):
            kept.append(f"color:{m.group(1)};")
        if m := KEEP_SIZE.search(style):
            kept.append(f"font-size:{m.group(1)};")
        span.attrs = {"style": "".join(kept)} if kept else {}
    return str(soup.body.decode_contents())

disclosure = (
    '<p><span data-keep-color="1" style="color:#e03131;font-size:30px;">'
    "<strong>이 포스팅은 네이버 쇼핑 커넥트 활동의 일환으로,</strong><br>"
    "<strong>판매 발생 시 수수료를 제공받습니다.</strong></span></p>"
)

에디터가 정말 색을 유지했는지는 붙여 넣은 뒤 DOM 의 계산된 스타일로 확인하면 확실합니다.

color = frame.evaluate("""(needle) => {
    const w = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
    let n;
    while ((n = w.nextNode())) {
        if (n.nodeValue.includes(needle)) {
            const cs = getComputedStyle(n.parentElement);
            return cs.color + " / " + cs.fontSize;
        }
    }
    return null;
}""", "쇼핑 커넥트 활동의 일환으로")
print(color)   # rgb(224, 49, 49) / 30px

대표 이미지가 문구보다 위로 올라가는 문제

이미지는 커서 위치에 업로드되는데, 본문을 넣은 뒤 제목을 입력하느라 커서가 제목에 있었습니다. 그래서 이미지가 본문 맨 앞(문구 위)에 꽂혔죠. 업로드 직전에 커서를 문구 끝으로 옮겨서 해결했습니다.

def place_cursor_after_disclosure(page, last_line="판매 발생 시 수수료를 제공받습니다."):
    for fr in page.frames:
        loc = fr.get_by_text(last_line, exact=False)
        if loc.count():
            loc.first.click()
            page.keyboard.press("End")
            return True
    return False

상품 썸네일이 안 보이는 문제

상품 이미지도 같은 표시 방식(data-keep-img)으로 살렸는데, 이번엔 이미지만 들어 있는 <p> 가 통째로 비워졌습니다. "텍스트 없는 문단은 빈 줄로 만든다"는 기존 로직이 이미지를 못 본 것.

# 전: 텍스트도 <br> 도 없으면 비움 -> <p><a><img></a></p> 가 날아감
if not p.get_text(strip=True) and not p.find(["br"]):
# 후: 이미지가 있으면 건드리지 않음
if not p.get_text(strip=True) and not p.find(["br", "img"]):

5. 글 주제와 관련된 상품 고르기

처음엔 카테고리 추천 상품을 넣었더니 "전기요금 절약" 글에 냄비 세트가 붙는 참사가… 그래서 글을 쓰는 AI 에게 상품 검색어도 같이 달라고 했습니다.

- shopping_keywords 에는 이 글을 읽은 독자가 실제로 구매할 만한, 주제와 직접 관련된
  상품 검색어 3~5개를 연관도가 높은 순서로 넣습니다. 쇼핑몰 검색창에 그대로 넣을
  짧은 명사형(1~2단어, 예: "가습기", "무선 청소기")으로 쓰고, 브랜드명·수식어는 넣지 않습니다.

키워드 순서대로 검색해서 품절·중복을 빼고 모으고, 관련 상품이 부족해도 엉뚱한 상품으로 채우지 않습니다.

def search_candidates(client, keywords, per_keyword=10):
    seen, out = set(), []
    for kw in keywords:
        for p in client.search(kw, limit=per_keyword):
            if p.is_linkable and p.id not in seen:   # 판매중 + 활성 + 스토어 정상
                seen.add(p.id)
                out.append(p)
    return out

실제 검색 결과: "가습기" → 미니 가습기, "무선 청소기" → 무선청소기, "전기요금 절약" → 스마트 플러그. 훨씬 자연스러워졌습니다.

 

블로그 게시 예시

 


6. 기존 릴스 파이프라인에 방어 로직 넣기

이미 스레드 글을 릴스로 만드는 파이프라인(큐 동기화 → 영상 제작 → 게시)이 라즈베리파이 cron 으로 돌고 있었는데, 코드를 읽다 보니 위험한 곳이 보였습니다.

① 실패한 항목이 큐를 영원히 막는다. 매번 id 가 가장 작은 1건만 처리하는데, 그게 실패하면 다음 실행에도 또 그것만 시도합니다. → 실패 횟수와 재시도 시각을 기록하고, 3회면 큐에서 뺍니다.

from datetime import datetime, timedelta

MAX_ATTEMPTS = 3
BACKOFF = timedelta(minutes=30)

def record_failure(ref, item, error):
    count = int(item.get("build_fail_count") or 0) + 1
    update = {"build_fail_count": count, "last_build_error": str(error)[:500]}
    if count >= MAX_ATTEMPTS:
        update["status"] = "build_failed"          # 큐에서 제외
    else:
        update["build_retry_after"] = (datetime.now() + BACKOFF * count).isoformat(sep=" ", timespec="seconds")
    ref.update(update)

# 고를 때: 재시도 대기 중이면 건너뛰고, 실패 이력이 적은 것부터
candidates.sort(key=lambda kv: (int(kv[1].get("build_fail_count") or 0), queue_sort_key(kv[0])))

② 숫자가 아닌 키에서 int() 예외로 전체가 죽는다.

def queue_sort_key(key: str) -> tuple:
    raw = key[len("item_"):] if key.startswith("item_") else key
    try:
        return (0, int(raw), "")
    except ValueError:
        return (1, 0, key)          # 숫자 아닌 키는 뒤로

③ 토큰 만료 같은 "전체 장애"를 항목 실패로 세면 안 된다. 토큰이 만료되면 모든 항목이 3번씩 실패해서 큐가 통째로 비워집니다. Graph API 오류 코드로 구분했습니다.

GLOBAL_CODES = {190, 4, 17, 32, 613}   # 190: 토큰 무효, 나머지: 호출 제한

def raise_for_graph_error(r, what):
    if r.status_code == 200:
        return
    code = (r.json().get("error") or {}).get("code")
    if r.status_code >= 500 or code in GLOBAL_CODES:
        raise GlobalPostingError(f"{what}: {r.text[:300]}")   # 실패 횟수 X, 이번 실행만 중단
    raise Exception(f"{what}: {r.text[:300]}")                # 항목 실패로 기록

④ 동기화 경쟁 상태. "스레드에 아직 안 올라간(pending) 글만 릴스로 복사"로 바꿨더니, 스레드 봇이 먼저 게시해 버리면 영원히 복사가 안 되는 틈이 생겼습니다. 그래서 최근 1일 안에 게시된 글도 복사하도록 창을 열어 두었습니다.

⑤ 영상 파일이 계속 쌓인다. 게시가 끝난 항목의 로컬 mp4 는 지우도록 했습니다(자기가 만든 폴더 안의 파일만).


7. 상품 이미지로 세로 릴스 영상 만들기

상품 이미지는 대부분 정사각형이라 1080x1920 으로 그냥 늘리면 찌그러집니다. 흐린 배경 위에 원본 비율 그대로 얹는 ffmpeg 필터를 썼습니다.

import subprocess

def make_vertical_slide(src, dst, w=1080, h=1920):
    vf = (
        "split[a][b];"
        f"[a]scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h},boxblur=30:2[bg];"
        f"[b]scale={w}:{h}:force_original_aspect_ratio=decrease[fg];"
        "[bg][fg]overlay=(W-w)/2:(H-h)/2"
    )
    subprocess.run(["ffmpeg", "-y", "-i", str(src), "-filter_complex", vf,
                    "-frames:v", "1", "-q:v", "2", str(dst)], check=True)

def make_silence(dst, seconds):
    # 나레이션 없이 무음 트랙(업로드 호환용). 기존 조립 스크립트가 오디오 길이로 클립 길이를 정함
    subprocess.run(["ffmpeg", "-y", "-f", "lavfi", "-i", "anullsrc=r=44100:cl=stereo",
                    "-t", str(seconds), "-c:a", "libmp3lame", "-q:a", "9", str(dst)], check=True)

자막: 처음 3초는 빨간 대가성 문구, 그 뒤엔 상품명

자막은 SRT 로 만들고 ffmpeg subtitles 필터로 입힙니다. 여기서 알게 된 팁 두 가지:

  • SRT 안의 <font color="...">, <b> 는 ffmpeg 가 ASS 스타일로 변환해 줍니다.
  • <font size="16"> 도 된다! 공용 스타일(force_style='Fontsize=22')은 다른 영상과 같이 쓰고 있어서 건드리기 싫었는데, SRT 태그로 이 영상만 크기를 덮어쓸 수 있었습니다. (참고로 {\fs16} 같은 ASS 태그는 ffmpeg 의 SRT 파서가 {\an8} 류 말고는 지워버립니다.)
DISCLOSURE = ("이 포스팅은 네이버 쇼핑 커넥트 활동의 일환으로,", "판매 발생 시 수수료를 제공받습니다.")

def srt_time(sec: float) -> str:
    ms = round(sec * 1000)
    h, ms = divmod(ms, 3_600_000)
    m, ms = divmod(ms, 60_000)
    s, ms = divmod(ms, 1000)
    return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"

def build_srt(name: str, total: float, disclosure_sec=3.0, size=16) -> str:
    disclosure = "\n".join(f'<font color="#e03131" size="{size}"><b>{line}</b></font>' for line in DISCLOSURE)
    product = name.replace("<", "(").replace(">", ")")   # 상품명이 태그로 해석되지 않게
    entries = [(0, min(disclosure_sec, total), disclosure)]
    if total > disclosure_sec:
        entries.append((disclosure_sec, total, f'<font size="{size}">{product}</font>'))
    return "\n".join(f"{i}\n{srt_time(a)} --> {srt_time(b)}\n{t}\n" for i, (a, b, t) in enumerate(entries, 1))

슬라이드가 1장뿐인 상품은 문구만 나오고 끝나지 않도록, 그 장의 길이를 (문구 3초 + 3초)로 늘렸습니다.


8. 인스타그램 릴스 게시: 중복 게시만은 막자

게시는 Instagram API(Instagram 로그인) 의 3단계 흐름입니다: 컨테이너 생성 → 처리 완료 대기 → 게시. 영상은 공개 URL 이 필요해서 Firebase Storage 에 잠깐 올렸다가 게시 후 지웁니다.

GRAPH = "https://graph.instagram.com/v21.0"

def create_container(ig_user_id, video_url, caption, token):
    r = requests.post(f"{GRAPH}/{ig_user_id}/media", data={
        "media_type": "REELS", "video_url": video_url, "caption": caption, "access_token": token,
    }, timeout=60)
    raise_for_graph_error(r, "컨테이너 생성 실패")
    return r.json()["id"]

def wait_until_processed(creation_id, token, timeout=300):
    start = time.time()
    while time.time() - start < timeout:
        r = requests.get(f"{GRAPH}/{creation_id}", params={"fields": "status_code", "access_token": token}, timeout=60)
        raise_for_graph_error(r, "상태 조회 실패")
        status = r.json().get("status_code")
        if status == "FINISHED":
            return
        if status == "ERROR":
            raise Exception("영상 처리 실패")
        time.sleep(5)
    raise Exception("영상 처리 타임아웃")

가장 무서운 건 "게시는 됐는데 응답을 못 받아서 다음 실행에 또 올리는" 중복 게시입니다. 그래서 게시 직전에 상태를 publishing 으로 찍고, 응답을 못 받으면 자동 재시도하지 않고 사람이 확인하게 했습니다.

set_status(conn, pid, "publishing")
try:
    media = publish(creation_id, token)
except GlobalPostingError:
    print("게시 결과를 확인하지 못했습니다. 인스타그램에서 확인 후 상태를 직접 바꿔 주세요.")
    return 1                      # publishing 으로 남김 -> 다음 실행에서 안 집음
set_posted(conn, pid, media)

캡션에는 가격, 제휴 링크, 대가성 문구, 해시태그를 넣었습니다. 인스타그램 캡션의 링크는 클릭이 안 되기 때문에 "복사해서 브라우저에 붙여 넣어 주세요" 안내를 같이 적었습니다.

 

인스타 자동 게시 릴스 예시

 


9. Meta 개발자 설정 & 배포 삽질 모음

체크리스트

  1. 인스타그램 계정을 프로페셔널(비즈니스/크리에이터) 로 전환
  2. 앱이 개발 모드면 앱 역할 → Instagram 테스터에 계정 추가 → 인스타그램 앱에서 초대 수락
  3. 권한 및 기능에 instagram_business_content_publish 추가 (기본 세팅엔 basic/comments/messages 만 있을 수 있음!)
  4. Instagram 비즈니스 로그인 설정에 리디렉션 URL 등록
  5. 로그인 동의 → code → 단기 토큰 → 장기(60일) 토큰 교환 (저는 Cloud Functions 로 콜백을 처리)

삽질 1: 앱 ID 가 두 개다

대시보드 맨 위의 Meta 앱 ID 와, Instagram API 설정 화면의 Instagram 앱 ID 는 다릅니다. OAuth client_id 와 토큰 교환에는 Instagram 앱 ID 를 써야 합니다.

삽질 2: PowerShell 에서 --set-env-vars 가 하나로 합쳐짐

# ❌ 쉼표가 PowerShell 배열 구분자로 해석돼 "A=1 B=2 C=3" 한 덩어리로 넘어감
gcloud functions deploy my-func ... --set-env-vars=APP_ID=123,APP_SECRET=xxx,REDIRECT_URI=https://.../

# ✅ 인자 전체를 큰따옴표로 감싸기
gcloud functions deploy my-func ... "--set-env-vars=APP_ID=123,APP_SECRET=xxx,REDIRECT_URI=https://.../"

배포는 "성공"했는데 함수가 Server misconfigured 를 뱉어서 한참 헤맸습니다. 환경변수 이름 목록을 찍어보고서야 APP_ID 하나에 전부 들어간 걸 발견했어요.

삽질 3: redirect URI 인코딩은 "브라우저 주소에서만"

  • 함수 환경변수 / 대시보드 등록값: https://my-callback.example.run.app/ (원래 형태, 끝 / 까지 똑같이)
  • 브라우저로 여는 동의 URL 안에서만: redirect_uri=https%3A%2F%2Fmy-callback.example.run.app%2F

삽질 4: ID 가 두 개다 (또!)

OAuth 가 돌려주는 user_id 는 앱 범위 ID 이고, /me?fields=user_id 는 인스타그램 계정 ID(1784...) 를 줍니다. 같은 계정입니다. 토큰 점검 스크립트에서 둘 중 하나만 맞으면 통과하도록 했습니다.

me = requests.get(f"{GRAPH}/me", params={"fields": "id,user_id,username,account_type",
                                          "access_token": token}, timeout=20).json()
same_account = str(target_id) in (str(me.get("id")), str(me.get("user_id")))

토큰 자동 갱신

장기 토큰은 60일 뒤 만료됩니다. 만료 15일 전부터 cron 에서 자동 갱신하게 했습니다(발급 후 24시간이 지나야 갱신 가능).

r = requests.get("https://graph.instagram.com/refresh_access_token",
                 params={"grant_type": "ig_refresh_token", "access_token": token}, timeout=20)
new_token = r.json()["access_token"]

10. cron 등록

#!/bin/bash
cd /home/pi/myproject
# 이전 실행(영상 제작)이 길어져도 겹쳐 돌지 않게
exec 9>/tmp/reels_sc.lock
flock -n 9 || { echo "이전 실행 진행 중 - 건너뜀"; exit 0; }

python3 sync_products.py || echo "상품 동기화 실패(기존 DB 로 계속)"
python3 ig_token_check.py --refresh-if-needed
python3 build_reels.py
python3 ig_reels_posting.py
# 하루 2번, 다른 봇과 겹치지 않게 30분에
30 10,20 * * * /home/pi/myproject/reels_sc.sh >> /home/pi/myproject/reels_sc.log 2>&1

윈도우에서 .sh 를 편집해 라즈베리파이로 보낼 땐 줄바꿈(CRLF) 을 조심하세요. PowerShell Set-Content 로 고치면 CRLF 가 되어 bash 가 깨집니다. [IO.File]::ReadAllText / WriteAllText 처럼 원본 줄바꿈을 유지하는 방법을 쓰세요.


마치며

정리해 보면 이번 작업에서 가장 도움이 된 원칙은 세 가지였습니다.

  1. 로그인은 사람이, 반복은 코드가 — 캡차·2단계 인증과 싸우지 말고 세션만 재사용하기
  2. 실패는 기록하고 격리하기 — 한 항목의 실패가 큐 전체를 막지 않게, 전체 장애는 항목 탓으로 세지 않게
  3. 중복 발행은 자동 재시도보다 무섭다 — 결과를 모르면 멈추고 사람에게 확인받기

그리고 codegen 녹화 파일, 쿠키 파일, 앱 시크릿은… 정말 조심하세요. 저는 이번에 둘 다 한 번씩 노출시키고 나서 비밀번호와 시크릿을 새로 바꿨습니다. 😅

반응형

 

Python 에서 json

json

 

1. Python JSON 변환

  • 사용자가 Python에서 JSON 객체를 문자열로 변환하는 방법을 질문함.
  • json.dumps() 함수 사용 예시와 옵션(indent, ensure_ascii, sort_keys) 설명 제공.
  • Pretty print 형식도 가능하다는 안내.

2. 대화 요약 요청

  • 사용자가 지금까지의 대화를 정리해서 HTML 형식으로 만들어 달라고 요청함.
  • 이에 따라 대화 내용을 항목별로 정리하여 HTML 문서 구조로 제공.

3. 브라우저 탭 상황

  • 현재 사용자는 Tistory, Naver 블로그 관리 페이지, Bing 검색, Tistory 메인 페이지 등을 열어둔 상태.
  • 이 정보는 단순히 참고용으로만 활용됨.
반응형
Build Log

토스쇼핑 쉐어링크를 Threads에 자동 게시하기까지

상품 조회부터 추적 링크 발급, 게시 문구 생성, 중복 방지, cron 자동화까지 — 하나의 파이프라인을 만들며 실제로 부딪힌 설계 결정과 구현 기법을 정리했다.

Python SQLite Cloud Functions gen2 Cloud Scheduler Threads Graph API Raspberry Pi · cron

무엇을 만들었나

체크리스트 8개 항목 — 전부 완료

토스쇼핑 쉐어링크 Open API로 상품을 조회하고 추적 링크(short_url)를 발급한 뒤, 그 링크로 게시 문구를 만들어 Threads에 자동으로 올리는 파이프라인이다. 인증, 발행, 문구 생성, 중복 방지, 트리거까지 전 구간을 직접 설계했다.

01
Meta 앱 · 권한 준비
DONE
02
OAuth 인증 흐름
DONE
03
2단계 발행 로직
DONE
04
콘텐츠 생성 규칙
DONE
05
중복 게시 방지
DONE
06
자동화 트리거
DONE
07
시크릿 관리
DONE
08
실게시 검증 · 테스트
DONE

순서대로 만든 게 아니라 2 → 3 → 6번을 먼저 뚫고, 4·5·7·8은 그 과정에서 자연히 같이 끝났다.

전체 흐름

get_today_deals() → issue_link() → build_post_content() → publish_once() → PostStore

핵심 구현 기술

코드로 남길 만했던 결정들

1. HTTP 상태 코드가 아니라 응답 바디로 성공/실패를 판정한다

쉐어링크 API는 HTTP 200이어도 바디의 resultType이 FAIL일 수 있다. 반대로 Threads(Meta Graph API)는 HTTP 상태와 error 객체 유무로 판정한다. 두 API가 실패를 표현하는 방식이 완전히 다르다는 걸 먼저 인정하고, 각자에 맞는 판정 함수를 따로 짰다 — 하나의 공통 추상화로 억지로 묶지 않았다.

sharelink/client.py result-based dispatch
if result_type == "SUCCESS":
    return payload.get("success", {})

if result_type == "FAIL":
    error_code = error.get("errorCode")
    if error_code == "INVALID_ARGUMENT":
        raise ShareLinkInvalidArgumentError(...)
    if error_code == _RETRYABLE_ERROR_CODE and attempt < max_retries:
        raise _RetryableBodyError(...)  # 상위 루프에서 백오프 재시도

2. 에러마다 재시도 정책이 다르다 — 하나로 뭉뚱그리지 않는다

"실패하면 재시도"가 아니라, 에러의 성격에 따라 재시도 여부가 갈린다. 두 클라이언트 모두 같은 원칙을 따르되 각 API의 실제 에러 표현에 맞게 구현했다.

상황 ShareLink Threads 정책
인증 실패 HTTP 401 OAuthException (190) 재시도 금지 · 토큰 재발급 필요
호출 속도 제한 HTTP 429 code 4/17/32/613 Retry-After 존중, 백오프 재시도
일시적 서버 오류 HTTP 500 is_transient: true 지수 백오프 재시도
파라미터 오류 INVALID_ARGUMENT 기타 4xx 재시도 금지 · 결과가 항상 같음
미지의 에러 코드 문서에 없는 코드 문서에 없는 코드 재시도 없이 예외 (베타 API 대비)

3. 발행은 2단계다 — 컨테이너를 만들고, 기다리고, 발행한다

Threads는 글을 바로 올리지 않는다. 미디어 컨테이너를 먼저 만들고(특히 이미지는 비동기 처리), 상태가 FINISHED가 될 때까지 폴링한 뒤에야 발행 API를 호출할 수 있다. TEXT는 폴링이 필요 없어서 분기했다.

threads/client.py create → poll → publish
def publish_image(self, image_url, text=None, *, poll_interval_seconds=2.0, timeout_seconds=60.0):
    creation_id = self.create_image_container(image_url, text)
    self.wait_until_container_ready(creation_id, poll_interval_seconds, timeout_seconds)
    return self.publish_container(creation_id)

def wait_until_container_ready(self, creation_id, *, poll_interval_seconds, timeout_seconds):
    deadline = time.monotonic() + timeout_seconds
    while True:
        status, error_message = self.get_container_status(creation_id)
        if status == "FINISHED":
            return
        if status in ("ERROR", "EXPIRED"):
            raise ThreadsContainerError(creation_id, status, error_message)
        if time.monotonic() >= deadline:
            raise ThreadsContainerTimeoutError(creation_id, status)
        time.sleep(poll_interval_seconds)

4. "쓰면 안 되는 필드"는 코드에서 아예 안 보이게 만든다

쉐어링크 API가 돌려주는 product_url은 추적이 안 되는 일반 링크다. 실수로 이걸 게시글에 쓰면 수익이 전혀 집계되지 않는다. 주석으로 "쓰지 마세요"라고 적어두는 대신, 문구 생성 모듈이 product_url을 아예 import도 참조도 하지 않게 만들었다. 리뷰나 주의력에 기대지 않고, 구조로 막는 편이 항상 더 오래 간다.

threads/content.py structural enforcement
# product.product_url 은 이 모듈 어디에서도 참조하지 않는다.
# 게시 링크는 IssuedLink.short_url 하나만 쓴다.
def _build_tail(link, *, hashtags, include_disclosure):
    parts = [link.short_url]
    if hashtags:
        parts.append(" ".join(_normalize_hashtag(t) for t in hashtags))
    if include_disclosure:
        parts.append(AD_DISCLOSURE)
    return "\n\n".join(parts)

글자 수(500자) 초과 처리도 같은 원칙이다. 링크와 광고 고지는 절대 잘리면 안 되는 부분이므로, 초과분은 항상 상품 설명(head) 쪽에서만 줄인다.

threads/content.py truncate head, never tail
def _compose(head, tail):
    text = f"{head}\n\n{tail}"
    if len(text) <= MAX_POST_LENGTH:
        return text

    budget = MAX_POST_LENGTH - len(tail) - 2
    if budget < len(_TRUNCATION_MARK):
        raise ContentGenerationError("링크·고지만으로 이미 글자 수를 초과합니다.")
    truncated_head = head[:budget - len(_TRUNCATION_MARK)].rstrip() + _TRUNCATION_MARK
    return f"{truncated_head}\n\n{tail}"

5. "발행됐는지 모르겠다"는 상태를 SQLite로 정직하게 다룬다

가장 신경 쓴 부분이다. 네트워크가 발행 요청 도중 끊기면, 서버에는 이미 게시됐는데 클라이언트만 실패로 아는 상황이 생길 수 있다. 이걸 자동으로 재시도하면 중복 게시로 이어진다. 그래서 상태를 3단계로 나누고, 애매한 상태는 자동으로 넘어가지 않게 막았다.

reserve() → pending → published / failed
threads/store.py idempotent reservation
def reserve(self, taca_item_id, *, daily_limit=None):
    existing = self.get(taca_item_id)
    if existing is not None:
        if existing.status == "published":
            raise AlreadyPostedError(taca_item_id, existing.media_id)
        if existing.status == "pending":
            # 이전 시도의 결과를 모른다 — 자동 재시도로 넘어가지 않는다
            raise PendingPostConflictError(taca_item_id, existing.creation_id, existing.reserved_at)
        # status == "failed" 는 재시도 허용

    if daily_limit is not None and self.count_published_since(24.0) >= daily_limit:
        raise DailyPostLimitReached(...)

pending에서 멈춘 건은 자동으로 풀리지 않는다. Threads 앱을 직접 열어 실제로 게시됐는지 확인한 뒤 resolve_pending()으로 사람이 결과를 확정해야 다음 시도가 가능하다. 번거롭지만, 중복 게시보다는 훨씬 낫다.

6. private Cloud Function + Cloud Scheduler로 토큰을 조용히 갱신한다

Threads 장기 토큰은 60일마다 만료된다. OAuth 콜백은 공개 엔드포인트여야 하지만, 토큰 갱신 함수는 그럴 필요가 없다 — 오히려 공개해두면 안 된다. 그래서 갱신 함수는 --no-allow-unauthenticated로 배포하고, Cloud Scheduler의 OIDC 토큰으로만 호출되도록 IAM invoker 권한을 딱 그 서비스 계정에만 부여했다.

Cloud Scheduler (매주 일 03:00 KST) → OIDC 토큰 → threads-token-refresh (private) → Firebase RTDB 갱신

겪었던 이슈와 주의사항

코드보다 오래 걸렸던 것들

Infra

gcloud services enable cloudscheduler.googleapis.com 직후 바로 스케줄러 작업을 만들면 SERVICE_DISABLED 에러가 난다. API 목록에는 즉시 나타나도, 실제로 쓸 수 있게 되기까지 전파 지연이 있다 — 90초 정도 기다렸다가 재시도하면 해결된다.

IAM

--no-allow-unauthenticated로 배포한 Cloud Function은 배포한 서비스 계정이라도 자동으로 호출 권한을 갖지 않는다. gcloud run services add-iam-policy-binding ... --role=roles/run.invoker 를 명시적으로 실행해야 Cloud Scheduler가 실제로 호출할 수 있다.

Meta OAuth

redirect URI를 Threads Login 설정에만 등록해도 error_code 1349168(차단된 URL)이 날 수 있다. 앱 대시보드의 App Domains에 도메인만 따로 등록해야 화이트리스트가 완성된다 — 둘 다 챙겨야 한다.

Legal

광고/제휴 고지 문구(AD_DISCLOSURE)는 상수 하나로 관리해서 바꾸기는 쉽게 만들었지만, 문구 자체가 표시광고법 요건을 충분히 충족하는지는 엔지니어링으로 해결되는 문제가 아니다. 코드는 "고지를 빠뜨리지 않는 것"까지만 보장하고, 문구의 적절성은 계속 법무 검토 대상으로 남겨뒀다.

Habit

실제 계정에 처음 게시하기 전, 발행 API를 호출하지 않고 문구·이미지·글자수만 출력하는 드라이런 스크립트를 먼저 돌렸다. 공개적으로 노출되는 작업(실계정 게시, 프로덕션 배포)은 결과를 미리 보여주고 확인받은 뒤에 실행하는 습관이 결국 시간을 아껴줬다.

테스트 전략

네트워크 없이, 그러나 촘촘하게

두 API 클라이언트 모두 실제 HTTP를 타지 않는다. requests.Session을 흉내 낸 FakeSession에 미리 정해둔 응답 큐를 넣어두고, 재시도 횟수까지 len(session.calls)로 정확히 검증한다. 상태 저장소 테스트는 PostStore(":memory:")로 디스크 I/O 없는 SQLite를 썼다 — 파일 경로 정리나 정리(teardown) 걱정 없이 상태 전이만 순수하게 검증할 수 있다.

파일 기법 검증 포인트
test_client.py FakeSession 토큰 재사용, 재시도별 정확한 호출 횟수
test_threads_client.py FakeSession 폴링 분기, 인증/한도/서버 에러 분류
test_content.py 고정 fixture product_url 미사용, 500자 트렁케이션
test_store.py / test_publisher.py in-memory SQLite 중복 게시 방지, pending 충돌, 일일 한도

돌아보며

가장 오래 고민한 건 화려한 기능이 아니라 실패를 어떻게 정직하게 다룰지였다 — 어떤 에러는 재시도해도 되고, 어떤 에러는 절대 안 되고, 어떤 상태는 사람이 봐야만 한다. 이 세 가지를 구분하는 것만으로 코드의 절반이 결정됐다.

다음으로 손댈 곳은 CAROUSEL(여러 이미지) 발행과, 라즈베리파이 운영 중에 실제로 pending 충돌이 얼마나 자주 나는지 지켜보는 것 — 지금은 이론적으로만 대비해둔 경로라 실전 데이터가 필요하다.

토스쇼핑 쉐어링크 × Threads 자동 게시 파이프라인 빌드로그 · Python 3.12
반응형
============================================================
     Lotto AI - New Recommendations for Round #1236
============================================================

[ 추천 1 ] (신뢰도: 98.0%)
 > 추천 번호: (6, 7, 13, 15, 28, 38)
 > 주요 근거:
   - gap: 14.2%
   - moving_average: 12.2%
   - transition_score: 10.0%
 > 조합 특징: odd/even=3/3, sum=107, sum-profile=historical-edge, low-high-balance, overlap-minimized, collective-coverage-maximized
------------------------------------------------------------

[ 추천 2 ] (신뢰도: 55.5%)
 > 추천 번호: (3, 6, 19, 30, 31, 35)
 > 주요 근거:
   - gap: 14.1%
   - moving_average: 12.4%
   - transition_score: 10.5%
 > 조합 특징: odd/even=4/2, sum=124, sum-profile=historical-center, low-high-balance, overlap-minimized, collective-coverage-maximized
------------------------------------------------------------

[ 추천 3 ] (신뢰도: 50.0%)
 > 추천 번호: (3, 7, 15, 20, 35, 42)
 > 주요 근거:
   - gap: 14.3%
   - moving_average: 12.4%
   - transition_score: 10.2%
 > 조합 특징: odd/even=4/2, sum=122, sum-profile=historical-center, low-high-balance, overlap-minimized, collective-coverage-maximized
------------------------------------------------------------

[ 추천 4 ] (신뢰도: 50.0%)
 > 추천 번호: (1, 7, 24, 31, 35, 38)
 > 주요 근거:
   - gap: 14.9%
   - moving_average: 12.5%
   - recent_score: 9.9%
 > 조합 특징: odd/even=4/2, sum=136, sum-profile=historical-center, low-high-balance, overlap-minimized, collective-coverage-maximized
------------------------------------------------------------

[ 추천 5 ] (신뢰도: 50.0%)
 > 추천 번호: (1, 6, 15, 35, 37, 40)
 > 주요 근거:
   - gap: 15.4%
   - moving_average: 12.5%
   - recent_score: 10.2%
 > 조합 특징: odd/even=4/2, sum=134, sum-profile=historical-center, low-high-balance, overlap-minimized, collective-coverage-maximized
------------------------------------------------------------
반응형

네이버 맛집 정보 수집 + 소형 AI JSON 변환 기획서

1. 목표

  • 키워드 성시경 맛집으로 네이버 검색을 수행한다.
  • 검색 결과 목록의 요약문이 아닌, 각 결과의 상세 링크 페이지를 순회한다.
  • 상세 페이지에서 맛집 관련 텍스트를 추출/정제한다.
  • 라즈베리파이에서 구동 가능한 소형 모델(Qwen GGUF)을 사용해 정보를 구조화하고, 최종적으로 JSON 스키마로 출력한다.

2. 현재 문제와 개선 방향

  • 현재 구현은 검색 결과 페이지의 snippet만 읽어서 정보 밀도가 낮다.
  • 개선안은 다음 2단계 수집으로 전환한다.
  1. 검색 결과 페이지에서 상세 링크 목록 수집
  2. 각 상세 링크 페이지 본문에서 텍스트 수집 후 AI 분석

3. 전체 처리 파이프라인

  1. 검색 요청
    • Query: 성시경 맛집
    • User-Agent 포함
  2. 상세 링크 추출
    • 네이버 검색 결과 DOM에서 외부/내부 상세 링크 URL 수집
    • 광고/쇼핑/중복 링크 제거
  3. 상세 페이지 크롤링
    • 링크별 HTML 요청
    • title, 본문 후보(article, main, 블로그 본문 영역 등) 추출
  4. 텍스트 정제
    • 공백/줄바꿈 정규화
    • 메뉴판/가격/주소/전화 패턴 우선 보존
    • 페이지별 길이 제한 (메모리 보호)
  5. AI 구조화
    • 소형 Qwen 모델로 스키마 기반 정보 추출
    • page 단위 1차 JSON 생성
  6. 통합/중복 제거
    • 상호명+주소 기준 유사 항목 병합
  7. 최종 출력
    • restaurants 배열 JSON으로 저장/출력

4. 권장 JSON 스키마

{
  "query": "성시경 맛집",
  "generated_at": "ISO-8601 datetime",
  "restaurants": [
    {
      "name": "상호명",
      "address": "주소",
      "contact": "연락처",
      "menus": ["메뉴1", "메뉴2"],
      "review_summary": "리뷰 요약",
      "source_url": "정보를 추출한 상세 페이지 URL"
    }
  ]
}

5. 라즈베리파이 소형 모델 전략

  • 우선 모델: Qwen/Qwen2.5-0.5B-Instruct-GGUF
  • 권장 파일: qwen2.5-0.5b-instruct-q4_k_m.gguf
  • 이유: 낮은 메모리 사용량, 구조화 추출 작업에 충분한 품질

추론 권장 설정(초안)

  • n_ctx: 1024~2048
  • n_threads: 라즈베리파이 CPU 코어 수 기반(예: 4)
  • temperature: 0.0 (형식 안정성 우선)
  • 출력 실패 시 재시도: 프롬프트에 “JSON만 출력” 강제 후 1회 재시도

6. Hugging Face에서 Qwen 모델 설치/다운로드

6.1 Python 패키지 설치

pip install --upgrade huggingface_hub llama-cpp-python requests beautifulsoup4

6.2 모델 다운로드 코드

from huggingface_hub import hf_hub_download

model_path = hf_hub_download(
    repo_id="Qwen/Qwen2.5-0.5B-Instruct-GGUF",
    filename="qwen2.5-0.5b-instruct-q4_k_m.gguf"
)
print(model_path)

6.3 모델 로드 예시

from llama_cpp import Llama

llm = Llama(
    model_path=model_path,
    n_ctx=1024,
    n_threads=4,
    verbose=False
)

7. 크롤링/분석 구현 포인트

  • 링크 수집 개수 제한: 예) 상위 10~20개 상세 링크
  • 요청 간 지연: 예) 0.5~1.0초(과도 요청 방지)
  • 타임아웃/실패 처리: 실패 링크는 스킵하고 로그 기록
  • 본문 선택자 다중 전략:
    • article, main, .se-main-container, #postViewArea 등 순차 시도
  • 페이지별 추출 결과를 먼저 JSON으로 저장(디버깅 용이)

8. 프롬프트 설계 방향

  • System Prompt:
    • “맛집 정보 추출기”
    • “설명문 금지, JSON만 출력”
    • “스키마 외 키 금지”
  • User Prompt:
    • 페이지 URL + 정제 텍스트 전달
    • 필드별 누락 허용 규칙(null 또는 "") 명시

9. 품질 기준(Definition of Done)

  • 상세 링크 기반으로 최소 N개(예: 5개 이상) 식당 후보가 JSON에 채워짐
  • JSON 파싱 100% 성공(실패 시 재시도 로직으로 보완)
  • 각 항목에 name 또는 address 중 최소 1개 이상 유효값 존재
  • source_url 추적 가능

10. 개발 단계 제안

  1. 링크 수집기 구현/검증
  2. 상세 페이지 본문 추출기 구현/검증
  3. Qwen JSON 추출 파이프라인 연결
  4. 병합/중복 제거 및 최종 JSON 생성
  5. 오류 처리/재시도/로그 보강

11. 주의사항

  • 사이트 이용정책/robots.txt/요청 빈도 제한을 준수한다.
  • 개인 정보 또는 민감 정보는 저장/출력하지 않는다.
  • 모델 출력은 신뢰도 한계가 있으므로 원문 URL 추적 필드를 유지한다.
반응형

 

Python으로 파일에서 특정 단어 찾기와 치환하기

텍스트 파일을 다루다 보면 특정 단어를 찾아서 바꾸거나, 몇 번 등장했는지 세거나, 위치까지 확인해야 할 때가 있습니다. 이 글에서는 Python의 re 모듈과 문자열 메서드를 활용해 그 방법을 정리합니다.

1. 특정 단어 치환하기

import re

replace_dict = {
    "dog": "cat",
    "hello": "hi"
}

with open("input.txt", "r", encoding="utf-8") as f:
    content = f.read()

for old, new in replace_dict.items():
    pattern = r"\b" + re.escape(old) + r"\b"
    content = re.sub(pattern, new, content)

with open("output.txt", "w", encoding="utf-8") as f:
    f.write(content)

\b는 단어 경계를 의미하므로 정확히 일치하는 단어만 치환됩니다.

2. 특정 단어 개수 세기

text = "hello world, hello python, hello AI"
word = "hello"

count = text.count(word)  # 부분 문자열 기준
print(count)  # 3

# 단어 단위로 정확히 세기
pattern = r"\b" + re.escape(word) + r"\b"
matches = re.findall(pattern, text)
print(len(matches))  # 3

3. 접두어가 포함된 단어 추출하기

text = "aaa.ccdh bbb.tttjj ccc.kkk aaa.zzz bbb.123"
prefixes = ["aaa.", "bbb."]

pattern = r"(?:aaa\.|bbb\.)\w+"
matches = re.findall(pattern, text)

print(matches)
# ['aaa.ccdh', 'bbb.tttjj', 'aaa.zzz', 'bbb.123']

4. 파일에서 찾기

with open("input.txt", "r", encoding="utf-8") as f:
    content = f.read()

pattern = r"(?:aaa\.|bbb\.)\w+"
matches = re.findall(pattern, content)

if matches:
    print("찾은 단어들:", matches)
else:
    print("패턴에 맞는 단어가 없습니다.")

5. 위치까지 확인하기

for match in re.finditer(pattern, content):
    print("찾은 단어:", match.group())
    print("시작 위치:", match.start())
    print("끝 위치:", match.end())

이렇게 하면 단어가 어디서 발견되었는지 인덱스까지 알 수 있습니다.

마무리

Python의 re 모듈을 활용하면 단순 치환부터 단어 개수 세기, 위치 추적까지 다양하게 처리할 수 있습니다. 텍스트 데이터 전처리나 로그 분석에 매우 유용하게 활용할 수 있으니 꼭 익혀두세요!

반응형

SQLite 튜토리얼: Oracle 개발자를 위한 핵심 차이점 정리

sqlite

 

SQLite는 가볍고 단순한 구조 덕분에 다양한 환경에서 널리 쓰입니다. 하지만 Oracle SQL에 익숙한 개발자라면 몇 가지 문법 차이 때문에 혼란스러울 수 있습니다. 이번 튜토리얼에서는 WITH 절, DECODE 함수, ROWNUM, 버전 확인, OUTER JOIN을 중심으로 살펴봅니다.

1. WITH 절 (CTE)

SQLite에서도 공통 테이블 표현식(CTE)를 지원합니다.

sql
WITH recent_orders AS (
  SELECT *
  FROM orders
  WHERE order_date > '2026-01-01'
)
SELECT customer_id, COUNT(*)
FROM recent_orders
GROUP BY customer_id;

👉 Oracle과 거의 동일하게 사용할 수 있습니다.

2. DECODE 함수 대체

Oracle의 DECODE는 SQLite에 없습니다. 대신 CASE 문을 사용하세요.

sql
SELECT 
  CASE status
    WHEN 'A' THEN 'Active'
    WHEN 'I' THEN 'Inactive'
    ELSE 'Unknown'
  END AS status_text
FROM users;

👉 CASE 문이 더 범용적이고 가독성도 좋습니다.

3. ROWNUM 대신 쓰는 방법

SQLite에는 ROWNUM이 없습니다. 대신 두 가지 방법을 씁니다.

(1) LIMIT / OFFSET

sql
SELECT *
FROM users
LIMIT 10 OFFSET 20;  -- 21번째 행부터 10개

(2) ROW_NUMBER() 윈도우 함수

sql
SELECT ROW_NUMBER() OVER (ORDER BY id) AS rn, name
FROM users;

👉 SQLite 3.25.0 이상에서 지원됩니다.

4. SQLite 버전 확인

버전 확인은 간단합니다.

  • SQL 쿼리:
  • sql
    SELECT sqlite_version();
    
  • CLI:
  • bash
    sqlite3 --version
    
  • Python:
  • python
    import sqlite3
    print(sqlite3.sqlite_version)
    

5. OUTER JOIN

SQLite는 LEFT OUTER JOIN만 지원합니다.

sql
SELECT u.id, u.name, o.order_date
FROM users u
LEFT OUTER JOIN orders o
  ON u.id = o.user_id;
  • RIGHT OUTER JOIN → 테이블 순서를 바꿔서 LEFT JOIN으로 대체
  • FULL OUTER JOIN → LEFT JOIN과 RIGHT JOIN을 UNION으로 합쳐서 구현

마무리

Oracle에서 SQLite로 넘어올 때 가장 많이 부딪히는 차이점들을 정리했습니다.

  • WITH 절은 그대로 사용 가능
  • DECODE는 CASE로 대체
  • ROWNUM은 LIMIT/OFFSET 또는 ROW_NUMBER()
  • 버전 확인은 sqlite_version()
  • OUTER JOIN은 LEFT만 지원, FULL은 UNION으로 구현

👉 이 튜토리얼을 따라가면 Oracle 개발자도 SQLite 환경에서 빠르게 적응할 수 있습니다.

반응형

티스토리에 작성 했던 글들을 네이버로 이전을 시작하고 한참 ...

이제 블로그 글 이전이 완료 되었습니다. 

 

네이버 일일 현황

 

807번째 글까지 이전이 완료 되기는 했으나, 그렇다고 해서 네이버 블로그에 유입이 늘어나지는 않았습니다.  블로그 글도 결국은 검색에 걸리지 않는 다면, 누군가 와서 클릭해 주어야 한다는 의미 인데, 그렇게 되려면 아무래도 친구 만들기, 이웃 만들기에 노력을 기울여야 할 것 같습니다. 

 

언제 될지는 알 수 없지만, 시작이 반이라 했으니... 어느날에는 다른 일들이 있지 않을까요?

 

아래는 이전에 사용 했던 코드 그대로 입니다.   잘 활용 한다면 자동 글쓰기을 이용해 네이버 블로그에 자동 글쓰기 머신(?)으로 개조(?) 사용해 볼 수 있지 않을까요 ?

from playwright.sync_api import sync_playwright
import time
import os

from naver_blog.tistory_scrape import readTistory

# --- HTML sanitize (Tistory -> Naver editor) ---
import re
from bs4 import BeautifulSoup
from urllib.parse import urljoin

import json
from pathlib import Path

import sqlite3
from datetime import datetime

# sqlite DB 경로(현재 스크립트와 같은 폴더에 생성)
DB_PATH = str(Path(__file__).with_name("tistory_to_naver.db"))

BLOG_ID = "billcoreatech"   # 본인 블로그 ID
TEST_TITLE = "자동화 테스트 제목"
TEST_BODY_HTML = """
<p>이 글은 Playwright 자동화 테스트입니다.</p>
<p><strong>본문 입력 정상 동작 확인용</strong></p>
<p>iframe + contenteditable 기반 입력 테스트</p>
"""

# --- Naver login helpers ---

def _wait_for_any_selector(root, selectors: list[str], *, timeout_ms: int = 15000) -> str | None:
    """여러 셀렉터 중 하나라도 나타나면 해당 셀렉터를 반환."""
    deadline = time.time() + (timeout_ms / 1000)
    last_err = None
    while time.time() < deadline:
        for sel in selectors:
            try:
                loc = root.locator(sel).first
                if loc.count() > 0 and loc.is_visible():
                    return sel
            except Exception as e:
                last_err = e
                continue
        time.sleep(0.2)
    return None


def wait_for_naver_login_page_ready(page, *, timeout_ms: int = 30000) -> None:
    """네이버 로그인 페이지가 '입력 가능한 상태'가 될 때까지 대기합니다."""
    # 로딩 상태(네트워크 idle은 로그인 페이지에서 흔들릴 수 있어 domcontentloaded 우선)
    try:
        page.wait_for_load_state("domcontentloaded", timeout=timeout_ms)
    except Exception:
        pass

    # 실제로 폼이 뜰 때까지(변경 대비 OR)
    sel = _wait_for_any_selector(
        page,
        [
            "input#id",
            "input[name='id']",
            "input[type='password']",
            "button[type='submit']",
        ],
        timeout_ms=timeout_ms,
    )
    if not sel:
        # 보호조치/캡차 등일 수도 있으니 디버그용 정보
        raise RuntimeError(f"네이버 로그인 폼 로딩 감지 실패(timeout={timeout_ms}ms). 현재 URL={page.url}")


def _has_naver_login_cookies(context) -> bool:
    try:
        cookies = context.cookies()
    except Exception:
        return False
    names = {c.get("name") for c in cookies if isinstance(c, dict)}
    # 통상 로그인 세션 쿠키(환경에 따라 다를 수 있어 OR로)
    return ("NID_AUT" in names) or ("NID_SES" in names)


def _looks_like_logged_in_dom(page) -> bool:
    """DOM에 '로그아웃' 흔적이 있는지로 로그인 완료를 보조 판정.

    - 네이버는 서비스/시점에 따라 상단 메뉴 구조가 달라질 수 있어 느슨하게 확인합니다.
    """
    selectors = [
        "a[href*='nidlogout']",
        "text=로그아웃",
        "a:has-text('로그아웃')",
    ]
    for sel in selectors:
        try:
            loc = page.locator(sel).first
            if loc.count() > 0 and loc.is_visible():
                return True
        except Exception:
            continue
    return False


def perform_naver_login(page, *, user_id: str, user_pw: str, timeout_ms: int = 30000) -> None:
    """네이버 로그인 페이지에서 아이디/비번 입력 후 로그인 버튼을 클릭합니다.

    주의:
    - 캡차/보호조치/2FA가 뜨면 이후 단계에서 감지 대기하다가 타임아웃될 수 있습니다.
    - 비밀번호 입력은 보안 정책/브라우저 설정에 따라 자동 입력이 막힐 수 있어, 여러 방식으로 시도합니다.
    """
    wait_for_naver_login_page_ready(page, timeout_ms=timeout_ms)

    # 네이버 로그인 입력 박스 셀렉터(변경 대비 OR)
    id_selectors = [
        "input#id",
        "input[name='id']",
        "#id",
    ]
    pw_selectors = [
        "input#pw",
        "input[name='pw']",
        "input[type='password']",
        "#pw",
    ]

    id_sel = _wait_for_any_selector(page, id_selectors, timeout_ms=timeout_ms)
    pw_sel = _wait_for_any_selector(page, pw_selectors, timeout_ms=timeout_ms)
    if not id_sel or not pw_sel:
        raise RuntimeError("로그인 입력창(id/pw)을 찾지 못했습니다. (보호조치/캡차 화면일 수 있음)")

    # 아이디
    page.locator(id_sel).first.click()
    page.keyboard.press("Control+A")
    page.keyboard.press("Backspace")
    page.keyboard.type(user_id, delay=25)

    # 비밀번호: fill -> type 순으로 시도(일부 환경에서 type이 더 잘 먹힘)
    pw_loc = page.locator(pw_sel).first
    pw_loc.click()
    try:
        pw_loc.fill("")
        pw_loc.fill(user_pw)
    except Exception:
        page.keyboard.press("Control+A")
        page.keyboard.press("Backspace")
        page.keyboard.type(user_pw, delay=25)

    # 로그인 버튼
    btn_selectors = [
        "button#log\.login",
        "#log\\.login",
        "button[type='submit']",
        "input[type='submit']",
        "text=로그인",
    ]
    btn_sel = _wait_for_any_selector(page, btn_selectors, timeout_ms=timeout_ms)
    if btn_sel:
        try:
            page.locator(btn_sel).first.click()
        except Exception:
            # 클릭이 막히면 Enter로 제출 시도
            page.keyboard.press("Enter")
    else:
        page.keyboard.press("Enter")


def goto_blog_section_and_open_write(page, *, timeout_ms: int = 30000):
    """로그인 후 섹션 홈으로 이동한 다음 '글쓰기' 버튼을 클릭해 글쓰기 모드로 진입.

    네이버는 글쓰기 진입이
    - 같은 탭 이동
    - 새 탭(팝업)
    - blog.naver.com/{id}?Redirect=Write
    형태로 바뀔 수 있어, 클릭 후 페이지 컨텍스트의 새 페이지도 감지합니다.

    반환: 글쓰기 화면으로 판단되는 Page 객체(대개 원래 page 또는 새 탭)
    """
    target_url = "https://section.blog.naver.com/BlogHome.naver?directoryNo=0&currentPage=1&groupId=0"

    # 1) 섹션 홈 이동
    page.goto(target_url, wait_until="domcontentloaded")
    try:
        page.wait_for_load_state("networkidle", timeout=timeout_ms)
    except Exception:
        pass

    # 2) '글쓰기' 버튼/링크 찾기
    write_selectors = [
        "a:has-text('글쓰기')",
        "button:has-text('글쓰기')",
        "text=글쓰기",
        "a[href*='Redirect=Write']",
        "a[href*='Write']",
    ]

    sel = _wait_for_any_selector(page, write_selectors, timeout_ms=timeout_ms)
    if not sel:
        raise RuntimeError(f"섹션 홈에서 '글쓰기' 버튼을 찾지 못했습니다. url={page.url}")

    # 3) 클릭 -> 새 탭이 뜰 수도 있어서 expect_page로 감싸서 처리
    ctx = page.context
    new_page = None
    try:
        with ctx.expect_page(timeout=5000) as pinfo:
            page.locator(sel).first.click()
        new_page = pinfo.value
    except Exception:
        # 새 탭이 안 뜨는 케이스면 현재 페이지에서 이동했을 가능성
        try:
            page.locator(sel).first.click()
        except Exception:
            # 클릭이 막히면 Enter
            page.keyboard.press("Enter")

    write_page = new_page or page

    # 4) 글쓰기 화면 로딩 대기(iframe/mainFrame 또는 Redirect=Write URL 등)
    deadline = time.time() + (timeout_ms / 1000)
    while time.time() < deadline:
        try:
            cur = write_page.url or ""
            if "Redirect=Write" in cur or ("write" in cur.lower() and "blog.naver.com" in cur):
                break
        except Exception:
            pass

        # mainFrame이 뜨면 거의 글쓰기 진입
        try:
            if write_page.frame(name="mainFrame"):
                break
        except Exception:
            pass

        time.sleep(0.3)

    # 추가로 mainFrame이 나타날 때까지 조금 더 기다림(네트워크/리다이렉트 변동 대비)
    try:
        write_page.wait_for_timeout(800)
    except Exception:
        pass

    return write_page


def close_other_tabs(context, keep_page):
    """현재 작업 탭을 제외한 나머지 탭을 닫아 탭 누적을 방지합니다."""
    for p in list(context.pages):
        if p is keep_page:
            continue
        try:
            p.close()
        except Exception:
            continue


def wait_for_naver_login_complete(page, *, timeout_ms: int = 300000) -> bool:
    """사용자가 로그인(수동)을 완료할 때까지 자동 감지해서 대기합니다.

    감지 기준:
    - 쿠키(NID_AUT/NID_SES) 생성 또는
    - URL이 로그인 페이지를 벗어남

    반환: True(로그인 완료로 판단) / False(타임아웃)
    """
    deadline = time.time() + (timeout_ms / 1000)
    login_url_prefix = "https://nid.naver.com/nidlogin.login"

    while time.time() < deadline:
        # 1) 쿠키 기반
        try:
            if _has_naver_login_cookies(page.context):
                return True
        except Exception:
            pass

        # 2) URL 기반(리다이렉트/다른 페이지로 이동)
        try:
            cur = page.url or ""
            if (login_url_prefix not in cur) and ("nidlogin.login" not in cur):
                return True
        except Exception:
            pass

        # 3) DOM 기반(로그아웃 요소 등)
        try:
            if _looks_like_logged_in_dom(page):
                return True
        except Exception:
            pass

        time.sleep(0.5)

    return False


def find_main_frame(page):
    # 1순위: name 기준
    frame = page.frame(name="mainFrame")
    if frame:
        return frame

    # 2순위: URL 패턴
    for f in page.frames:
        if "write" in (f.url or "").lower():
            return f

    raise RuntimeError("mainFrame 찾기 실패")

def find_editor_frame(main_frame, *, retries: int = 15, interval: float = 2.0):
    """editor iframe 을 찾되, 로딩이 느릴 수 있으므로 retries 횟수만큼 재시도한다."""
    for attempt in range(retries):
        # URL 기반
        for f in main_frame.child_frames:
            if "editor" in (f.url or "").lower():
                return f

        # contenteditable 기준 fallback
        for f in main_frame.child_frames:
            try:
                if f.locator("[contenteditable='true']").count() > 0:
                    return f
            except:
                pass

        # 페이지 전체 frames 에서도 탐색 (main_frame 이 이미 최상위일 수 있음)
        try:
            page = main_frame.page
            for f in page.frames:
                if f is main_frame:
                    continue
                if "editor" in (f.url or "").lower():
                    return f
        except Exception:
            pass

        if attempt < retries - 1:
            print(f"[find_editor_frame] attempt {attempt+1}/{retries} – not found, waiting {interval}s…")
            time.sleep(interval)

    raise RuntimeError("editor iframe 찾기 실패 (재시도 모두 소진)")

def focus_title_strong(page, title: str):
    # 페이지 또는 프레임들에서 제목 요소를 찾아 포커싱/입력 시도
    page.wait_for_timeout(100)

    selectors = [
        "div.se-component.se-documentTitle span.se-placeholder",
        "div[data-a11y-title='제목'] span.se-placeholder",
        "span.se-placeholder:has-text('제목')",
        "span.__se-node",
        "p.se-text-paragraph",
        "div.se-module.se-title-text",
        "text=제목",
    ]

    def try_on(root):
        # root는 Page 또는 Frame
        for sel in selectors:
            try:
                locator = root.locator(sel)
                if locator.count() > 0:
                    try:
                        locator.first.click()
                        page.wait_for_timeout(120)
                        page.keyboard.type(title, delay=40)
                        return True
                    except Exception:
                        # 클릭 실패 시 다음 선택자 시도
                        pass
            except Exception:
                continue

        # evaluate 폴백
        try:
            result = root.evaluate("""
            (title) => {
                const candidateSelectors = [
                    'span.__se-node',
                    'div.se-component.se-documentTitle span.se-placeholder',
                    '[data-a11y-title="제목"] span.se-placeholder',
                    'p.se-text-paragraph',
                    'div.se-module.se-title-text'
                ];

                let el = null;
                for (const sel of candidateSelectors) {
                    const found = document.querySelector(sel);
                    if (found) { el = found; break; }
                }

                if (!el) {
                    el = Array.from(document.querySelectorAll('span.se-placeholder')).find(s => s.textContent && s.textContent.trim() === '제목');
                }

                if (!el) return { found: false, set: false };

                try { el.click(); } catch(e) {}

                let editable = null;
                if (el.closest) {
                    editable = el.closest('[contenteditable]') || (el.querySelector && el.querySelector('[contenteditable]'));
                }
                if (!editable) {
                    editable = el;
                }

                try {
                    if (editable.isContentEditable || (editable.getAttribute && editable.getAttribute('contenteditable') === 'true')) {
                        editable.focus && editable.focus();
                        // contentEditable이면 내부 노드 중 빈 __se-node가 있으면 채우기
                        // 아니면 innerText로 대체
                        const node = editable.querySelector && editable.querySelector('span.__se-node');
                        if (node && node.innerText.trim() === '') {
                            node.innerText = title;
                        } else {
                            editable.innerText = title;
                        }
                    } else {
                        editable.innerText = title;
                    }

                    const evInput = new Event('input', { bubbles: true });
                    const evChange = new Event('change', { bubbles: true });
                    editable.dispatchEvent && editable.dispatchEvent(evInput);
                    editable.dispatchEvent && editable.dispatchEvent(evChange);

                    return { found: true, set: true };
                } catch (e) {
                    return { found: true, set: false };
                }
            }
            """, title)

            if isinstance(result, dict):
                return result.get('set', False)
        except Exception:
            pass

        return False

    # 1) 현재 페이지에서 시도
    try:
        if try_on(page):
            return
    except Exception:
        pass

    # 2) 모든 프레임에서 시도 (중첩 포함)
    try:
        frames_to_check = list(page.frames)
        for fr in frames_to_check:
            try:
                if try_on(fr):
                    return
            except Exception:
                continue
    except Exception:
        pass

    # 최후 수단: 포커스가 된 상태로 가정하고 키보드로 입력
    page.wait_for_timeout(120)
    page.keyboard.type(title, delay=40)


def sanitize_for_naver(html: str, *, base_url: str | None = None, remove_images: bool = False) -> str:
    """네이버 스마트에디터(스마트에디터 ONE) 입력용으로 본문 HTML을 최대한 안전하게 정리합니다.

    목표
    - 줄바꿈 유지: 블록 단위를 <p>로 통일하고 빈 줄은 <p><br></p>
    - 이미지 유지: <img src="...">를 확정하고 불필요 속성 제거
    - 에디터가 잘라내는 태그 최소화: div/span 등은 풀고(unwrap) 필요한 태그만 남김

    주의
    - 네이버 쪽에서 외부 이미지 표시를 제한할 수 있습니다.
      이 경우엔 '외부 이미지' 정책 때문에 img가 사라지거나 로드 실패할 수 있어, 업로드 방식이 더 확실합니다.

    추가
    - 티스토리 codeblock(<pre data-ke-type="codeblock"><code>...</code></pre>)은
      네이버 에디터에서 줄바꿈이 깨질 수 있어, 코드블록만 별도 변환합니다.
      (코드 내용을 HTML escape 후 줄바꿈을 <br>로 강제)

    remove_images:
      - True: 본문 HTML 내의 <img> 태그를 모두 제거합니다. (이미지는 로컬 다운로드/업로드 플로우로만 처리)
    """

    soup = BeautifulSoup(html or "", "lxml")

    # --- Tistory codeblock normalize ---
    # <pre ... data-ke-type="codeblock"><code>...</code></pre>
    # 또는 data-ke-language가 있는 케이스를 대상으로, 네이버에서 줄바꿈이 유지되도록
    # 내부 텍스트를 escape 후 <br>로 변환한 "pseudo code block"으로 치환합니다.
    # (네이버가 외부 <pre>를 재가공하면서 \n을 공백으로 만들 수 있어 선제 대응)
    def _escape_code_text(s: str) -> str:
        # BeautifulSoup가 특수문자를 escape 해주긴 하지만, 여기서는 명시적으로 처리
        return (s or "").replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")

    def _preserve_indentation(s: str) -> str:
        """코드블록 내 들여쓰기/정렬을 최대한 보존하기 위한 치환.

        - 탭(\t): 4칸 공백으로 변환 후 nbsp 처리
        - 라인 선두/연속 공백: HTML에서 축약되지 않도록 &nbsp;로 보존

        주의: 전체 공백을 전부 nbsp로 바꾸면 복사/편집성이 떨어질 수 있어,
        '연속 공백(2개 이상)'과 '라인 선두'에만 적용합니다.
        """
        if not s:
            return ""

        s = s.replace("\t", "    ")
        lines = s.split("\n")
        out_lines: list[str] = []
        for line in lines:
            if not line:
                out_lines.append("")
                continue

            # 1) 선두 공백은 모두 nbsp로
            m = re.match(r"^( +)", line)
            if m:
                lead = m.group(1)
                rest = line[len(lead):]
                lead_nbsp = "&nbsp;" * len(lead)
            else:
                lead_nbsp = ""
                rest = line

            # 2) 중간의 연속 공백(2개 이상)은 첫 공백만 유지하고 나머지를 nbsp로
            #    예: 'a    b' -> 'a &nbsp;&nbsp;&nbsp;b' (총 4칸 유지)
            def _collapse_spaces(match: re.Match) -> str:
                n = len(match.group(0))
                return " " + ("&nbsp;" * (n - 1))

            rest = re.sub(r" {2,}", _collapse_spaces, rest)
            out_lines.append(lead_nbsp + rest)

        return "\n".join(out_lines)

    for pre in list(soup.find_all("pre")):
        try:
            ke_type = (pre.get("data-ke-type") or "").strip().lower()
            has_code_child = pre.find("code") is not None
            ke_lang = (pre.get("data-ke-language") or "").strip()

            # 티스토리 코드블록의 전형적인 패턴만 대상으로 함(일반 pre는 유지)
            if not (ke_type == "codeblock" or (has_code_child and ke_lang)):
                continue

            code = pre.find("code") or pre

            # code 내부에 <br>가 섞여 있을 수 있어 텍스트로 안전하게 추출
            raw_text = code.get_text()
            # get_text()는 <br>을 개행으로 치환하지 않을 수 있어 폴백 처리
            if "<br" in str(code).lower() and ("\n" not in (raw_text or "")):
                # <br>을 개행으로 보고 다시 추출
                try:
                    tmp = BeautifulSoup(str(code), "lxml")
                    for br in tmp.find_all("br"):
                        br.replace_with("\n")
                    raw_text = tmp.get_text()
                except Exception:
                    pass
            # 줄바꿈 정규화
            raw_text = (raw_text or "").replace("\r\n", "\n").replace("\r", "\n")

            escaped = _escape_code_text(raw_text)
            escaped = _preserve_indentation(escaped)
            # 줄바꿈을 <br>로 강제(마지막 줄이 비어있어도 보이도록)
            html_lines = escaped.split("\n")
            # 빈 코드블럭 방지
            if not html_lines:
                html_lines = [""]

            # 코드블럭을 일반 문단/인라인으로 흡수시키지 않도록 wrapper를 둠
            # - <pre> 자체는 네이버가 제거/변형할 수 있어 사용하지 않음
            # - 대신 p + code 조합으로, 줄바꿈은 <br>로 표현
            # white-space는 에디터가 style을 제거할 수도 있지만, 남아있으면 들여쓰기에 도움이 됨
            code_html = "<p><code style=\"white-space:pre-wrap; font-family:monospace;\">" + "<br>".join(html_lines) + "</code></p>"

            repl = BeautifulSoup(code_html, "lxml")
            new_p = repl.find("p")
            if new_p is not None:
                pre.replace_with(new_p)
        except Exception:
            # 코드블록 변환 실패는 전체 sanitize를 막지 않도록 무시
            continue

    # 1) 위험/불필요 태그 제거
    for tag in soup.find_all(["script", "style", "noscript", "iframe", "object", "embed", "form", "input", "button"]):
        tag.decompose()

    # (추가) RDF/CCL 같은 메타 블록 제거
    for tag in soup.find_all(["rdf:rdf", "rdf", "work", "license"]):
        try:
            tag.decompose()
        except Exception:
            pass

    # 2) 광고/관련글/태그/댓글로 자주 쓰이는 블록 제거 (있으면)
    for sel in [
        ".another_category",
        ".related_posts",
        ".postbtn",
        ".share",
        ".comment",
        "#comment",
    ]:
        for t in soup.select(sel):
            t.decompose()

    # (추가) 티스토리 광고/구독/CCL UI 제거
    for sel in [
        "[data-tistory-react-app]",
        "button.btn_subscription",
        "a.link_ccl",
        ".bundle_ccl",
    ]:
        for t in soup.select(sel):
            try:
                t.decompose()
            except Exception:
                pass

    # 3) div/span은 모두 풀기 (내용만 유지)
    for tag in list(soup.find_all(["div", "span"])):
        # 구독 버튼 등은 위에서 제거하지만, 혹시 남았으면 방어적으로 제거
        if tag.get("data-tistory-react-app"):
            tag.decompose()
            continue
        tag.unwrap()

    # 허용 태그 (최소)
    allowed_tags = {
        "p",
        "br",
        "strong",
        "b",
        "em",
        "i",
        "u",
        "s",
        "blockquote",
        "pre",
        "code",
        "ul",
        "ol",
        "li",
        "hr",
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6",
        "a",
        # 이미지 업로드를 별도로 하므로, 기본은 포함하되 remove_images=True면 제거
        "img",
        "table",
        "thead",
        "tbody",
        "tr",
        "th",
        "td",
    }

    def pick_img_url(tag) -> str | None:
        srcset = tag.get("srcset")
        if srcset:
            parts = [p.strip() for p in srcset.split(",") if p.strip()]
            if parts:
                u = parts[-1].split()[0].strip()
                if u:
                    return u
        for k in ["data-src", "data-original", "data-url", "data-lazy", "data-origin-src", "src"]:
            v = tag.get(k)
            if v and str(v).strip():
                return str(v).strip()
        return None

    def _is_allowed_url(u: str) -> bool:
        u = (u or "").strip().lower()
        return u.startswith("http://") or u.startswith("https://")

    # 4) 허용 태그만 남기고 나머지는 unwrap
    for tag in list(soup.find_all(True)):
        name = tag.name.lower()
        if name not in allowed_tags:
            tag.unwrap()
            continue

        # 이미지 제거 옵션
        if remove_images and name == "img":
            tag.decompose()
            continue

        # 속성 정리
        for attr_name in list(dict(tag.attrs).keys()):
            an = attr_name.lower()
            if an.startswith("on"):
                del tag.attrs[attr_name]
                continue

            if name == "a":
                if an not in {"href", "title", "target", "rel"}:
                    del tag.attrs[attr_name]
            elif name == "img":
                if an not in {"src", "alt"}:
                    del tag.attrs[attr_name]
            else:
                # 나머지는 속성 제거(에디터가 종종 자름)
                del tag.attrs[attr_name]

        # 링크 정리
        if name == "a":
            href = tag.get("href")
            if href and base_url:
                try:
                    tag["href"] = urljoin(base_url, href)
                except (ValueError, Exception):
                    pass  # 잘못된 URL(예: Invalid IPv6)은 원래 href 유지
            tag["rel"] = "noopener noreferrer"
            if "target" not in tag.attrs:
                tag["target"] = "_blank"

        # 이미지 src 확정
        if name == "img":
            url = pick_img_url(tag)
            if url:
                if base_url:
                    try:
                        url = urljoin(base_url, url)
                    except (ValueError, Exception):
                        pass  # 잘못된 URL은 원래 url 유지
                # 네이버 에디터가 data:, blob: 등을 잘라내는 경우가 있어 http(s)만 유지
                if _is_allowed_url(url):
                    tag["src"] = url
                else:
                    tag.decompose()
                    continue
            else:
                tag.decompose()
                continue

            if not tag.get("alt"):
                tag["alt"] = ""

    # 5) 블록 단위 통일
    body = soup.body if soup.body else soup

    def _preserve_text_whitespace(text: str) -> str:
        """일반 텍스트에서도 개행/들여쓰기를 최대한 보존하기 위한 변환.

        - \r\n/\r -> \n
        - 선두 공백: &nbsp;로
        - 연속 공백(2개 이상): 첫 공백만 남기고 나머지 &nbsp;
        - 개행: <br>로 변환하기 위해 '\n'을 유지(나중에 split해서 Tag로 넣음)
        """
        text = (text or "").replace("\r\n", "\n").replace("\r", "\n")
        lines = text.split("\n")
        out_lines: list[str] = []
        for line in lines:
            if line == "":
                out_lines.append("")
                continue
            m = re.match(r"^( +)", line)
            if m:
                lead = m.group(1)
                rest = line[len(lead):]
                lead_nbsp = "&nbsp;" * len(lead)
            else:
                lead_nbsp = ""
                rest = line

            def _collapse_spaces(match: re.Match) -> str:
                n = len(match.group(0))
                return " " + ("&nbsp;" * (n - 1))

            rest = re.sub(r" {2,}", _collapse_spaces, rest)
            out_lines.append(lead_nbsp + rest)
        return "\n".join(out_lines)

    def wrap_text_nodes_with_p(root):
        for node in list(root.contents):
            # NavigableString 처리
            if getattr(node, "name", None) is None:
                txt = str(node)
                if txt.strip():
                    p = soup.new_tag("p")
                    preserved = _preserve_text_whitespace(txt.strip())
                    parts = preserved.split("\n")
                    for i, part in enumerate(parts):
                        if i > 0:
                            p.append(soup.new_tag("br"))
                        # part에는 &nbsp; 등이 들어갈 수 있어 string으로 넣지 않고 파싱해서 삽입
                        frag = BeautifulSoup(part, "lxml")
                        # lxml은 <html><body>... 구조를 만들 수 있어, 텍스트/태그만 꺼내 붙임
                        container = frag.body if frag.body else frag
                        for c in list(container.contents):
                            p.append(c)
                    node.replace_with(p)
                else:
                    node.extract()

    wrap_text_nodes_with_p(body)

    # (추가) p 내부에 순수 텍스트만 있고 \n 이 포함된 경우도 <br>로 치환
    for p in list(body.find_all("p")):
        try:
            # p 내에 자식 태그가 없고 텍스트에 개행이 있으면 분해
            if not p.find(True):
                txt = p.get_text()
                if "\n" in (txt or ""):
                    preserved = _preserve_text_whitespace(txt)
                    p.clear()
                    for i, part in enumerate(preserved.split("\n")):
                        if i > 0:
                            p.append(soup.new_tag("br"))
                        frag = BeautifulSoup(part, "lxml")
                        container = frag.body if frag.body else frag
                        for c in list(container.contents):
                            p.append(c)
        except Exception:
            continue

    # 6) 연속 <br> 또는 빈 영역을 <p><br></p>로 보정
    for p in list(body.find_all("p")):
        # p 안에 아무 것도 없거나 공백만 있으면 <br> 넣기
        if not p.get_text(strip=True) and not p.find(["br"]):
            p.clear()
            p.append(soup.new_tag("br"))

    # body 직계에 img 등이 있고 p가 없으면 img 앞뒤를 p로 구분(줄바꿈 효과)
    # -> 이미지 제거(remove_images)인 경우엔 굳이 이 로직을 태울 필요가 없음
    if not remove_images:
        new_children = []
        for child in list(body.contents):
            if getattr(child, "name", None) == "img":
                new_children.append(BeautifulSoup("<p><br></p>", "lxml").p)
                p = soup.new_tag("p")
                p.append(child.extract())
                new_children.append(p)
                new_children.append(BeautifulSoup("<p><br></p>", "lxml").p)
            else:
                new_children.append(child)

        body.clear()
        for c in new_children:
            body.append(c)

    cleaned = "".join(str(x) for x in body.contents)
    cleaned = re.sub(r"\n{3,}", "\n\n", cleaned)
    return cleaned.strip()


def _find_editable_in_frame(frame):
    """네이버 글쓰기(스마트에디터)에서 실제 본문 입력 노드를 최대한 찾아 반환합니다.

    반환: (Frame, css_selector) 또는 (None, None)

    메모:
    - 네이버 글쓰기 페이지는 같은 프레임 안에서도 contenteditable 후보가 여러 개일 수 있어
      '본문'에 가까운 셀렉터를 우선합니다.
    """
    # about:blank 같은 빈 프레임은 후보에서 제외
    try:
        if not frame.url or frame.url.startswith("about:"):
            return None, None
    except Exception:
        return None, None

    candidate_selectors = [
        # SmartEditor ONE 본문에서 자주 보이는 루트(우선순위 높음)
        "div.se2_inputarea[contenteditable='true']",
        "div.se-editable[contenteditable='true']",
        "div.se-component-content[contenteditable='true']",
        "div[role='textbox'][contenteditable='true']",
        # 마지막 폴백
        "[contenteditable='true']",
    ]

    # locator.count()가 프레임 로딩 타이밍에 따라 0이 나오는 경우가 있어 evaluate로도 확인
    for sel in candidate_selectors:
        try:
            # 1) locator 기반
            loc = frame.locator(sel)
            if loc.count() > 0:
                return frame, sel
        except Exception:
            pass

        try:
            # 2) evaluate 기반
            exists = frame.evaluate("""(sel) => document.querySelector(sel) !== null""", sel)
            if exists:
                return frame, sel
        except Exception:
            continue

    return None, None


def _find_best_editor_target_from_page(page):
    """page 전체 frames에서 본문 편집 대상(Frame+selector)을 찾습니다."""
    try:
        frames = list(page.frames)
    except Exception:
        frames = []

    for fr in frames:
        found_fr, found_sel = _find_editable_in_frame(fr)
        if found_fr:
            return found_fr, found_sel
    return None, None


def _find_best_editor_target(main_frame):
    """main_frame부터 하위 프레임까지 훑어서 본문 편집 대상(Frame+selector)을 찾습니다."""

    queue = [main_frame]
    visited = set()

    while queue:
        fr = queue.pop(0)
        if fr in visited:
            continue
        visited.add(fr)

        found_fr, found_sel = _find_editable_in_frame(fr)
        if found_fr:
            return found_fr, found_sel

        try:
            queue.extend(list(fr.child_frames))
        except Exception:
            pass

    return None, None


def set_body_text_mode(target_frame, selector: str, text: str):
    """가장 안정적인 방식: 텍스트를 줄 단위로 입력(Enter로 줄바꿈)."""

    # 줄바꿈 정규화
    lines = (text or "").replace("\r\n", "\n").replace("\r", "\n").split("\n")
    # 너무 긴 문서를 한 번에 넣지 않도록 적당히 처리

    # 클릭/포커스는 JS에서, 실제 입력은 playwright keyboard로
    target_frame.evaluate(
        """
        (selector) => {
            const nodes = Array.from(document.querySelectorAll(selector)).filter(el => el && el.isConnected);
            if (!nodes.length) throw new Error('no editor for text mode');
            const scored = nodes.map(el => {
                const r = el.getBoundingClientRect ? el.getBoundingClientRect() : { width: 0, height: 0 };
                const area = (r.width || 0) * (r.height || 0);
                return { el, area };
            }).sort((a,b) => b.area - a.area);
            const editor = scored[0].el;
            editor.focus();
            try { editor.innerHTML=''; } catch(e) {}
        }
        """,
        selector,
    )

    # 실제 키 입력
    for i, line in enumerate(lines):
        if line:
            target_frame.page.keyboard.type(line, delay=10)
        # 줄바꿈
        if i < len(lines) - 1:
            target_frame.page.keyboard.press("Enter")


# 기존 set_body를 mode 지원으로 확장

def set_body(editor_frame, html, *, base_url: str | None = None, page=None, mode: str = "auto"):
    """본문 입력.

    mode:
      - auto: paste -> insertHTML -> range -> text 폴백
      - paste: paste만 시도(실패 시 auto 폴백)
      - insertHTML: insertHTML 우선(실패 시 range -> text)
      - range: range 우선(실패 시 text)
      - text: 텍스트 키입력(줄바꿈 Enter)
    """

    # 이미지 업로드는 별도 플로우로 처리하므로 본문에서는 <img>를 제거
    html = sanitize_for_naver(html, base_url=base_url, remove_images=True)

    # 1) editor_frame(기존 로직)에서 탐색
    target_frame, target_selector = _find_best_editor_target(editor_frame)

    # 2) 실패하면 page 전체에서 탐색
    if not target_frame and page is not None:
        target_frame, target_selector = _find_best_editor_target_from_page(page)

    if not target_frame:
        raise RuntimeError(
            f"본문 편집 영역을 찾지 못했습니다. editor_frame_url={getattr(editor_frame, 'url', None)}"
        )

    print(f"[set_body] target_frame_url={target_frame.url} selector={target_selector} mode={mode}")

    try:
        target_frame.wait_for_load_state("domcontentloaded", timeout=5000)
    except Exception:
        pass

    if mode == "text":
        _soup = BeautifulSoup(html, "lxml")
        txt = "\n".join(_soup.stripped_strings)
        set_body_text_mode(target_frame, target_selector, txt)
        return

    # JS 내부에서 어떤 method를 시도할지 결정
    js_mode = mode
    if js_mode not in {"auto", "paste", "insertHTML", "range"}:
        js_mode = "auto"

    result = target_frame.evaluate(
        """
        ({ html, selector, mode }) => {
            const nodes = Array.from(document.querySelectorAll(selector)).filter(el => el && el.isConnected);
            if (!nodes.length) {
                return { ok: false, method: 'none', reason: 'no_candidates', htmlLen: 0, textLen: 0 };
            }

            // 가장 화면에 보이는 큰 영역 우선
            const scored = nodes.map(el => {
                const r = el.getBoundingClientRect ? el.getBoundingClientRect() : { width: 0, height: 0 };
                const area = Math.max(0, r.width) * Math.max(0, r.height);
                const style = window.getComputedStyle ? window.getComputedStyle(el) : null;
                const visible = style ? (style.visibility !== 'hidden' && style.display !== 'none') : true;
                return { el, area, visible };
            }).sort((a,b) => {
                const as = (a.visible ? 1e12 : 0) + a.area;
                const bs = (b.visible ? 1e12 : 0) + b.area;
                return bs - as;
            });

            const editor = scored[0].el;
            editor.scrollIntoView && editor.scrollIntoView({ block: 'center' });
            editor.focus && editor.focus();

            const beforeTextLen = (editor.innerText || '').trim().length;
            const beforeHtmlLen = (editor.innerHTML || '').length;

            const measure = () => {
                const textLen = (editor.innerText || '').trim().length;
                const htmlLen = (editor.innerHTML || '').length;
                const changed = (textLen !== beforeTextLen) || (htmlLen !== beforeHtmlLen);
                const enough = (textLen >= 20) || (htmlLen >= 50);
                return { changed, enough, textLen, htmlLen };
            };

            // 일부 에디터는 이벤트 처리 후 비동기로 DOM을 갱신하므로, 0ms 지연 후 재측정을 지원
            const measureSoon = () => new Promise(resolve => {
                setTimeout(() => resolve(measure()), 0);
            });

            const tryPaste = async () => {
                // 1) ClipboardEvent + DataTransfer
                try {
                    const dt = new DataTransfer();
                    dt.setData('text/html', html);
                    const tmp = document.createElement('div');
                    tmp.innerHTML = html;
                    const text = (tmp.innerText || tmp.textContent || '').trim();
                    dt.setData('text/plain', text);

                    try {
                        editor.dispatchEvent(new InputEvent('beforeinput', {
                            bubbles: true,
                            cancelable: true,
                            inputType: 'insertFromPaste',
                            dataTransfer: dt,
                        }));
                    } catch(e) {}

                    try {
                        const pasteEvt = new ClipboardEvent('paste', {
                            bubbles: true,
                            cancelable: true,
                            clipboardData: dt,
                        });
                        editor.dispatchEvent(pasteEvt);
                    } catch(e) {
                        // ClipboardEvent 생성이 막히면 다음 경로로
                        throw e;
                    }

                    let m = measure();
                    if (m.enough) return true;
                    m = await measureSoon();
                    return m.enough;
                } catch(e) {
                    // 2) navigator.clipboard를 사용할 수 있으면 시도 (권한/보안 정책에 따라 실패 가능)
                    try {
                        const tmp = document.createElement('div');
                        tmp.innerHTML = html;
                        const text = (tmp.innerText || tmp.textContent || '').trim();

                        if (navigator.clipboard && navigator.clipboard.write) {
                            const item = new ClipboardItem({
                                'text/plain': new Blob([text], { type: 'text/plain' }),
                                'text/html': new Blob([html], { type: 'text/html' }),
                            });
                            await navigator.clipboard.write([item]);

                            // 일부 환경에서 execCommand('paste')가 동작할 수 있음
                            try { document.execCommand && document.execCommand('paste'); } catch(e2) {}

                            let m = measure();
                            if (m.enough) return true;
                            m = await measureSoon();
                            return m.enough;
                        }
                    } catch(e3) {
                        // ignore
                    }

                    return false;
                }
            };

            const tryInsertHTML = () => {
                try {
                    try { editor.innerHTML = ''; } catch(e) {}
                    return !!(document.execCommand && document.execCommand('insertHTML', false, html));
                } catch(e) {
                    return false;
                }
            };

            const tryRange = () => {
                try {
                    const range = document.createRange();
                    range.selectNodeContents(editor);
                    range.collapse(false);
                    const sel = window.getSelection();
                    sel.removeAllRanges();
                    sel.addRange(range);
                    const tpl = document.createElement('template');
                    tpl.innerHTML = html;
                    range.insertNode(tpl.content);
                    return true;
                } catch(e) {
                    return false;
                }
            };

            // async 체인
            return (async () => {
                let ok = false;
                let method = 'none';

                const chainAuto = ['paste', 'insertHTML', 'range'];
                const chain = (mode === 'paste') ? ['paste', ...chainAuto.filter(x=>x!=='paste')]
                            : (mode === 'insertHTML') ? ['insertHTML', 'range']
                            : (mode === 'range') ? ['range']
                            : chainAuto;

                for (const m of chain) {
                    if (m === 'paste') {
                        if (await tryPaste()) { ok = true; method = 'paste'; break; }
                    } else if (m === 'insertHTML') {
                        if (tryInsertHTML()) {
                            let res = measure();
                            if (!res.enough) res = await measureSoon();
                            ok = res.enough || res.changed;
                            method = 'insertHTML';
                            if (ok) break;
                        }
                    } else if (m === 'range') {
                        if (tryRange()) {
                            let res = measure();
                            if (!res.enough) res = await measureSoon();
                            ok = res.enough || res.changed;
                            method = 'range';
                            if (ok) break;
                        }
                    }
                }

                editor.dispatchEvent(new Event('input', { bubbles: true }));
                editor.dispatchEvent(new Event('change', { bubbles: true }));

                let final = measure();
                if (!final.enough) final = await measureSoon();

                return {
                    ok,
                    method,
                    reason: ok ? 'inserted' : 'failed',
                    htmlLen: final.htmlLen,
                    textLen: final.textLen,
                    picked: { area: scored[0].area, visible: scored[0].visible },
                    before: { textLen: beforeTextLen, htmlLen: beforeHtmlLen },
                };
            })();
        }
        """,
        {"html": html, "selector": target_selector, "mode": js_mode},
    )

    if isinstance(result, dict):
        print(
            f"[set_body] ok={result.get('ok')} method={result.get('method')} htmlLen={result.get('htmlLen')} textLen={result.get('textLen')} "
            f"reason={result.get('reason')} before={result.get('before')} picked={result.get('picked')}"
        )

    # 최후 폴백: JS가 실패로 판단하면 텍스트 모드
    if not isinstance(result, dict) or not result.get('ok'):
        print("[set_body] JS 삽입 실패 -> 텍스트 모드 폴백")
        _soup = BeautifulSoup(html, "lxml")
        txt = "\n".join(_soup.stripped_strings)
        set_body_text_mode(target_frame, target_selector, txt)


def _open_image_upload_ui(page) -> bool:
    """네이버 글쓰기에서 '사진/이미지' 업로드 UI를 열어 file input이 나타나게 시도합니다."""

    button_selectors = [
        "button:has-text('사진')",
        "button:has-text('이미지')",
        "button:has-text('포토')",
        "button:has-text('첨부')",
        "button[aria-label*='사진']",
        "button[aria-label*='이미지']",
        "a:has-text('사진')",
        "a:has-text('이미지')",
        "span:has-text('사진')",
        "span:has-text('이미지')",
    ]

    for fr in list(page.frames):
        for sel in button_selectors:
            try:
                loc = fr.locator(sel)
                if loc.count() == 0:
                    continue
                loc.first.click(timeout=800)
                page.wait_for_timeout(300)
                return True
            except Exception:
                continue

    return False


def _find_file_input_for_images(page):
    """page/frames에서 이미지 업로드용 file input을 찾아 (frame, locator) 반환."""
    candidate_selectors = [
        "input[type='file'][accept*='image']",
        "input[type='file']",
    ]

    for fr in list(page.frames):
        for sel in candidate_selectors:
            try:
                loc = fr.locator(sel)
                if loc.count() > 0:
                    return fr, loc.first
            except Exception:
                continue
    return None, None


def _try_upload_via_filechooser(page, paths: list[str], *, timeout_ms: int = 15000) -> bool:
    """클릭 시 OS 파일 선택창(file chooser)이 뜨는 흐름을 Playwright로 처리.

    네이버 에디터는 어떤 경우엔 input[type=file]가 노출되지 않고,
    '사진/이미지' 버튼 클릭 시 filechooser 이벤트가 발생합니다.
    이 경우 expect_file_chooser + set_files 로 업로드를 진행합니다.

    반환: filechooser로 업로드를 시도했으면 True, 이벤트가 안 떠서 못했으면 False
    """
    try:
        # 업로드 버튼을 다시 한번 열어주며(성공/실패 상관없이) filechooser를 유도
        with page.expect_file_chooser(timeout=timeout_ms) as fc_info:
            _open_image_upload_ui(page)
        chooser = fc_info.value
        chooser.set_files(paths)
        return True
    except Exception:
        return False


def _try_upload_via_windows_dialog(paths: list[str], *, timeout_ms: int = 20000) -> bool:
    """Windows '열기' 파일 선택 대화상자가 떠 있는 경우를 pywinauto로 제어.

    전제:
    - Chromium/Playwright가 OS 파일 대화상자를 띄운 상태에서 이 함수가 호출되어야 합니다.

    주의:
    - 환경/언어(한글/영문 Windows)에 따라 컨트롤 이름이 다를 수 있어
      여러 후보를 순차 시도합니다.
    """
    try:
        from pywinauto import Application  # type: ignore
    except Exception:
        return False

    if not paths:
        return False

    # 여러 파일은 줄바꿈으로 전달(Windows 공통 동작)
    file_text = "\n".join(paths)
    first_parent = None
    try:
        first_parent = str(Path(paths[0]).parent)
    except Exception:
        first_parent = None

    deadline = time.time() + (timeout_ms / 1000)
    last_err = None
    while time.time() < deadline:
        try:
            # connect가 실패하는 경우가 있어(권한/포커스/멀티창) Desktop 탐색도 시도
            try:
                app = Application(backend="uia").connect(title_re=r"^(열기|Open)$")
                dlg = app.window(title_re=r"^(열기|Open)$")
            except Exception:
                app = Application(backend="uia")
                dlg = app.window(title_re=r"^(열기|Open)$")

            dlg.wait("visible", timeout=2)

            # 파일명 입력 박스 후보
            edit = None
            for c in [
                lambda: dlg.child_window(auto_id="1148", control_type="Edit"),  # common file name box
                lambda: dlg.child_window(title_re=r"파일 이름|File name", control_type="Edit"),
                lambda: dlg.child_window(control_type="Edit"),
            ]:
                try:
                    e = c()
                    if e.exists():
                        edit = e
                        break
                except Exception:
                    continue
            if edit is None:
                return False

            # 1) 가장 안정적인 방식: 파일명 칸에 '전체 경로'들을 줄바꿈으로 입력
            #    (폴더 탐색/클릭 없이도 다중 선택 가능)
            try:
                edit.set_edit_text("")
                edit.set_edit_text(file_text)
            except Exception:
                # 2) 실패하면: 먼저 폴더 경로를 파일명에 넣고 Enter로 이동한 뒤,
                #    파일명만(여러 개면 줄바꿈) 입력
                if first_parent:
                    try:
                        edit.set_edit_text("")
                        edit.set_edit_text(first_parent)
                        dlg.type_keys("{ENTER}")
                        time.sleep(0.4)

                        names = []
                        for p in paths:
                            try:
                                pp = Path(p)
                                names.append(pp.name)
                            except Exception:
                                continue
                        if names:
                            edit.set_edit_text("")
                            edit.set_edit_text("\n".join(names))
                    except Exception:
                        pass

            # 열기 버튼 후보
            btn = None
            for c in [
                lambda: dlg.child_window(title_re=r"열기|Open", control_type="Button"),
                lambda: dlg.child_window(auto_id="1", control_type="Button"),
            ]:
                try:
                    b = c()
                    if b.exists():
                        btn = b
                        break
                except Exception:
                    continue
            if btn is None:
                # Enter로 대체 시도
                try:
                    dlg.type_keys("{ENTER}")
                    return True
                except Exception:
                    return False

            btn.click_input()
            return True
        except Exception as e:
            last_err = e
            time.sleep(0.3)

    return False


def _wait_for_image_upload_settled(page, *, timeout_ms: int = 120000) -> dict:
    """이미지 파일 set_input_files 이후 업로드/삽입이 끝나고 팝업이 정리될 때까지 대기.

    네이버 에디터는 시점에 따라
    - 파일 선택 즉시 본문에 삽입
    - 업로드 팝업/레이어에서 '확인/완료/적용'을 눌러야 삽입
    - 업로드 진행률이 끝날 때까지 대기 필요
    가 섞여서 나타날 수 있어, 여러 신호를 느슨하게 조합합니다.

    추가: 대기 중 배열 선택 UI(se-image-type-label)가 뜨면 자동 처리합니다.
    """
    deadline = time.time() + (timeout_ms / 1000)

    # 클릭 가능한 '완료/확인' 계열 버튼 후보(팝업/레이어)
    confirm_selectors = [
        "button:has-text('완료')",
        "button:has-text('확인')",
        "button:has-text('적용')",
        "button:has-text('등록')",
        "button:has-text('넣기')",
        "button:has-text('삽입')",
        "button:has-text('닫기')",
        "text=완료",
        "text=확인",
    ]

    # 업로드 진행 중일 때 보이는 텍스트/요소 후보(있으면 사라질 때까지 기다리는 용도)
    busy_text_selectors = [
        "text=업로드",
        "text=Uploading",
        "text=전송",
        "text=진행",
    ]

    # 에디터 본문에서 업로드된 이미지를 감지하기 위한 셀렉터
    # (단순 img 태그가 아니라, 네이버 에디터의 이미지 컴포넌트로 한정)
    uploaded_img_selectors = [
        ".se-component.se-image img",
        ".se-image-resource img",
        "img[src*='postfiles']",
        "img[src*='blogfiles']",
        "img[src*='pstatic']",
        "img[data-src]",
    ]

    # 시작 시점의 img 개수를 기록(기존 이미지와 새 이미지를 구분)
    initial_img_count = 0
    try:
        for fr in list(page.frames):
            try:
                initial_img_count += fr.locator("img").count()
            except Exception:
                pass
    except Exception:
        pass

    last_click = 0.0
    layout_handled = False

    while time.time() < deadline:
        # 0) 배열 선택 UI가 대기 중에 나타났으면 처리 (안전망)
        if not layout_handled:
            try:
                roots = [page] + list(page.frames)
                for root in roots:
                    try:
                        labels = root.locator(".se-image-type-label")
                        if labels.count() >= 1 and labels.nth(0).is_visible():
                            print("[upload_settle] layout choice UI detected during settle wait → handling")
                            ch = _handle_multi_image_layout_choice(page, prefer="개별", timeout_ms=15000)
                            print(f"[upload_settle] layout_choice={ch}")
                            layout_handled = True
                            break
                    except Exception:
                        continue
            except Exception:
                pass

        # 1) 본문에 이미지가 들어갔는지(iframe 포함) 확인
        #    — 네이버 에디터 이미지 컴포넌트 셀렉터를 우선 체크
        try:
            for fr in list(page.frames):
                for sel in uploaded_img_selectors:
                    try:
                        if fr.locator(sel).count() > 0:
                            return {"ok": True, "reason": "img_tag_detected"}
                    except Exception:
                        continue
        except Exception:
            pass

        # 1-b) 구체 셀렉터로 못 잡으면, img 총 개수가 늘었는지로 판단
        try:
            current_img_count = 0
            for fr in list(page.frames):
                try:
                    current_img_count += fr.locator("img").count()
                except Exception:
                    pass
            if current_img_count > initial_img_count:
                return {"ok": True, "reason": "img_tag_detected"}
        except Exception:
            pass

        # 2) 가능한 '완료/확인' 버튼이 있으면 한 번씩 눌러보기(너무 자주 누르지 않게 throttle)
        if time.time() - last_click > 1.2:
            for sel in confirm_selectors:
                try:
                    loc = page.locator(sel).first
                    if loc.count() > 0 and loc.is_visible() and loc.is_enabled():
                        loc.click(timeout=800)
                        last_click = time.time()
                        page.wait_for_timeout(400)
                        break
                except Exception:
                    continue

        # 3) 업로드가 돈다면(텍스트가 보인다면) 잠깐 기다리기
        busy_seen = False
        for sel in busy_text_selectors:
            try:
                loc = page.locator(sel).first
                if loc.count() > 0 and loc.is_visible():
                    busy_seen = True
                    break
            except Exception:
                continue
        if busy_seen:
            time.sleep(0.5)
            continue

        # 4) 아무 신호가 없으면 짧게 폴링
        time.sleep(0.3)

    return {"ok": False, "reason": "upload_settle_timeout"}


def _handle_multi_image_layout_choice(page, *, prefer: str = "개별사진", timeout_ms: int = 15000) -> dict:
    """이미지 2장 이상 업로드 시 나타나는 '배열 방식' 선택(UI가 뜨면 클릭).

    네이버 에디터는 다중 이미지 업로드 후
    - 개별
    - 콜라보(콜라주)
    - 슬라이드/모음
    같은 선택 화면이 뜨는 경우가 있어, 자동으로 기본값(개별)을 선택하고 진행합니다.

    반환: {ok:bool, reason:str}
    """
    deadline = time.time() + (timeout_ms / 1000)

    # 텍스트 기반으로 '배열/레이아웃/콜라보' 화면 감지
    trigger_texts = [
        "배열",
        "레이아웃",
        "콜라보",
        "콜라주",
        "슬라이드",
        "개별사진",
        "개별",
    ]

    # 선택 후보(우선 prefer)
    option_selectors = [
        f"button:has-text('{prefer}')",
        f"label:has-text('{prefer}')",
        f"span:has-text('{prefer}')",
        # fallback: '개별사진' -> '개별'
        "button:has-text('개별사진')",
        "label:has-text('개별사진')",
        "span:has-text('개별사진')",
        "button:has-text('개별')",
        "label:has-text('개별')",
        "span:has-text('개별')",
    ]

    # 다음/확인/적용/완료
    confirm_selectors = [
        "button:has-text('확인')",
        "button:has-text('완료')",
        "button:has-text('적용')",
        "button:has-text('등록')",
        "button:has-text('넣기')",
        "button:has-text('삽입')",
        "button:has-text('다음')",
    ]

    def _text_seen() -> bool:
        """page와 모든 iframe에서 배열 선택 텍스트가 보이는지 확인."""
        roots = [page] + list(page.frames)
        for root in roots:
            for t in trigger_texts:
                try:
                    loc = root.get_by_text(t).first
                    if loc.count() > 0 and loc.is_visible():
                        return True
                except Exception:
                    continue
        return False

    def _label_seen_in_any_root() -> bool:
        """page와 모든 iframe에서 .se-image-type-label 요소가 보이는지 확인."""
        roots = [page] + list(page.frames)
        for root in roots:
            try:
                labels = root.locator(".se-image-type-label")
                if labels.count() >= 1:
                    if labels.nth(0).is_visible():
                        return True
            except Exception:
                continue
        return False

    # --- 배열 UI가 뜰 때까지 대기(즉시 안 뜨는 경우: 업로드 서버 처리 시간) ---
    # 최대 timeout_ms 의 절반을 대기에 사용하고, 나머지를 클릭 시도에 사용
    wait_deadline = time.time() + min(timeout_ms / 1000 * 0.6, 12.0)
    appeared = _text_seen() or _label_seen_in_any_root()
    if not appeared:
        print("[layout] waiting for layout choice UI to appear...")
        while time.time() < wait_deadline:
            if _text_seen() or _label_seen_in_any_root():
                appeared = True
                print("[layout] layout choice UI appeared")
                break
            time.sleep(0.5)

    if not appeared:
        print("[layout] layout choice UI not appeared within wait period")
        return {"ok": True, "reason": "no_layout_choice_ui"}

    # --- 배열 UI가 보이면 클릭 시도 루프 ---
    attempt = 0
    while time.time() < deadline:
        attempt += 1
        roots = [page] + list(page.frames)

        # 0) 가장 확실한 케이스: se-image-type-label 클릭 (page + 모든 frame)
        label_clicked = False
        for root in roots:
            try:
                labels = root.locator(".se-image-type-label")
                cnt = labels.count()
                if cnt < 1:
                    continue
                first = labels.nth(0)
                if not first.is_visible():
                    continue

                print(f"[layout] attempt={attempt} found {cnt} .se-image-type-label in {getattr(root, 'url', 'page')[:80]}")

                # 클릭 시도 (3단계 폴백)
                click_ok = False
                try:
                    first.click(timeout=2000)
                    click_ok = True
                except Exception:
                    try:
                        first.click(timeout=2000, force=True)
                        click_ok = True
                    except Exception:
                        try:
                            bb = first.bounding_box()
                            if bb:
                                # page 레벨 mouse 사용(frame mouse는 좌표 오프셋 문제 가능)
                                page.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2)
                                click_ok = True
                        except Exception:
                            pass

                if not click_ok:
                    # JS 강제 클릭 폴백
                    try:
                        js_ok = root.evaluate("""() => {
                            const labels = document.querySelectorAll('.se-image-type-label');
                            if (labels.length < 1) return false;
                            const el = labels[0];
                            el.scrollIntoView({block:'center'});
                            const opts = {bubbles:true, cancelable:true, composed:true};
                            el.dispatchEvent(new PointerEvent('pointerdown', opts));
                            el.dispatchEvent(new MouseEvent('mousedown', opts));
                            el.dispatchEvent(new MouseEvent('mouseup', opts));
                            el.dispatchEvent(new MouseEvent('click', opts));
                            return true;
                        }""")
                        if js_ok:
                            click_ok = True
                    except Exception:
                        pass

                if click_ok:
                    print(f"[layout] se-image-type-label clicked OK")
                    label_clicked = True
                    try:
                        page.wait_for_timeout(800)
                    except Exception:
                        time.sleep(0.8)
                    break
                else:
                    print(f"[layout] se-image-type-label click FAILED (all methods)")
            except Exception:
                continue

        # 1) 옵션 선택 (page + 모든 frame)
        option_clicked = False
        for root in roots:
            for sel in option_selectors:
                try:
                    loc = root.locator(sel).first
                    if loc.count() > 0 and loc.is_visible() and loc.is_enabled():
                        try:
                            loc.click(timeout=1200)
                        except Exception:
                            try:
                                loc.click(timeout=1200, force=True)
                            except Exception:
                                bb = loc.bounding_box()
                                if bb:
                                    page.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2)
                        try:
                            page.wait_for_timeout(400)
                        except Exception:
                            time.sleep(0.4)
                        option_clicked = True
                        print(f"[layout] option '{sel}' clicked in root={getattr(root, 'url', 'page')[:80]}")
                        break
                except Exception:
                    continue
            if option_clicked:
                break

        # label이나 option을 클릭한 뒤 UI 안정화 대기
        if label_clicked or option_clicked:
            try:
                page.wait_for_timeout(500)
            except Exception:
                time.sleep(0.5)

        # 2) 확인/적용/완료 계열 누르기
        if _robust_click_in_page_or_frames(page, confirm_selectors, timeout_ms=2000):
            print("[layout] confirm button clicked → layout_choice_confirmed")
            return {"ok": True, "reason": "layout_choice_confirmed"}

        # 3) UI가 사라졌으면 끝 (label도, 텍스트도 안 보이면)
        if not _text_seen() and not _label_seen_in_any_root():
            print("[layout] layout UI disappeared → done")
            return {"ok": True, "reason": "layout_choice_disappeared"}

        time.sleep(0.4)

    print(f"[layout] timeout after {attempt} attempts")
    return {"ok": False, "reason": "layout_choice_timeout"}


def _collect_downloaded_image_paths(out_dir: str) -> list[str]:
    """readTistory()가 저장한 images.json을 읽어 실제 존재하는 다운로드 이미지 경로를 수집."""
    d = Path(out_dir)
    img_json = d / "images.json"
    if not img_json.exists():
        return []

    try:
        data = json.loads(img_json.read_text(encoding="utf-8"))
    except Exception:
        return []

    paths: list[str] = []
    for item in data:
        if not isinstance(item, dict):
            continue
        p = item.get("path")
        if not p:
            continue
        pp = Path(p)
        if pp.exists():
            paths.append(str(pp))
    return paths


def _clear_out_dir_images(out_dir: str) -> dict:
    """이전 실행에서 내려받은 이미지/메타 파일을 삭제합니다.

    - images.json 삭제
    - out_dir 하위의 일반적인 이미지 확장자 파일 삭제

    목적: 이번 실행에서 다운로드된 이미지 목록과 파일만 업로드 되도록 정리
    """
    d = Path(out_dir)
    if not d.exists():
        return {"ok": True, "deleted": 0, "reason": "dir_not_exists"}

    deleted = 0
    # images.json
    try:
        j = d / "images.json"
        if j.exists():
            j.unlink()
            deleted += 1
    except Exception:
        pass

    exts = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"}
    for p in d.glob("**/*"):
        try:
            if p.is_file() and p.suffix.lower() in exts:
                p.unlink()
                deleted += 1
        except Exception:
            continue

    return {"ok": True, "deleted": deleted}


def _html_has_img(html: str) -> bool:
    try:
        soup = BeautifulSoup(html or "", "lxml")
        return soup.find("img") is not None
    except Exception:
        return "<img" in (html or "").lower()


def upload_images_in_batch(page, *, out_dir: str) -> dict:
    """다운로드된 이미지를 네이버 글쓰기에서 일괄 업로드합니다."""
    paths = _collect_downloaded_image_paths(out_dir)
    print(f"[upload] local images: {len(paths)}")
    if not paths:
        return {"ok": True, "reason": "no_local_images", "count": 0}

    # 0) 먼저 filechooser 이벤트로 끝낼 수 있는지 시도(일부 UI에서 input[type=file]가 안 잡힘)
    if _try_upload_via_filechooser(page, paths):
        print("[upload] used filechooser")
        # 다중 이미지일 때 배열 방식 선택 UI가 뜨면 처리
        # (업로드 서버 처리 시간에 따라 UI가 늦게 뜰 수 있어 timeout을 넉넉히 설정)
        if len(paths) >= 2:
            try:
                ch = _handle_multi_image_layout_choice(page, prefer="개별", timeout_ms=30000)
                print(f"[upload] layout_choice={ch}")
            except Exception as e:
                print(f"[upload] layout_choice_failed: {e}")
        settled = _wait_for_image_upload_settled(page, timeout_ms=180000)
        print(f"[upload] settled={settled}")
        return {"ok": True, "count": len(paths), "settled": settled, "via": "filechooser"}

    # 1) 안 되면 기존 방식: input[type=file] 찾아 set_input_files
    opened = _open_image_upload_ui(page)
    print(f"[upload] upload_ui_opened={opened}")
    page.wait_for_timeout(300)

    fr, file_input = _find_file_input_for_images(page)
    if file_input is not None:
        try:
            file_input.set_input_files(paths)
            print(f"[upload] set_input_files OK: {len(paths)} files (frame={getattr(fr,'url',None)})")

            if len(paths) >= 2:
                try:
                    ch = _handle_multi_image_layout_choice(page, prefer="개별", timeout_ms=30000)
                    print(f"[upload] layout_choice={ch}")
                except Exception as e:
                    print(f"[upload] layout_choice_failed: {e}")

            settled = _wait_for_image_upload_settled(page, timeout_ms=180000)
            print(f"[upload] settled={settled}")

            if not settled.get("ok"):
                return {"ok": True, "count": len(paths), "warn": settled, "via": "set_input_files"}

            return {"ok": True, "count": len(paths), "settled": settled, "via": "set_input_files"}
        except Exception as e:
            print(f"[upload] set_input_files_failed: {e}")

    # 2) 마지막 백업: OS 파일 선택창이 이미 떠 있는 상태면 pywinauto로 파일명 입력 후 열기
    dlg_ok = _try_upload_via_windows_dialog(paths)
    if dlg_ok:
        settled = _wait_for_image_upload_settled(page, timeout_ms=180000)
        print(f"[upload] settled={settled}")
        return {"ok": True, "count": len(paths), "settled": settled, "via": "pywinauto_dialog"}

    return {"ok": False, "reason": "file_input_not_found_and_dialog_control_failed"}


def _safe_click_any(page, selectors: list[str], *, timeout_ms: int = 1500) -> bool:
    """여러 셀렉터 중 화면에서 클릭 가능한 것이 있으면 클릭하고 True."""
    for sel in selectors:
        try:
            loc = page.locator(sel).first
            if loc.count() > 0 and loc.is_visible() and loc.is_enabled():
                loc.click(timeout=timeout_ms)
                return True
        except Exception:
            continue
    return False


def _robust_click_in_page_or_frames(page, selectors: list[str], *, timeout_ms: int = 3000) -> bool:
    """page 및 모든 frame에서 selectors 중 하나를 최대한 '어떻게든' 클릭.

    네이버 에디터는
    - iframe 내부
    - overlay가 클릭을 가로채는 타이밍
    - 버튼이 보이지만 playwright 기본 click이 실패
    같은 경우가 있어 단계적 폴백을 둡니다.
    """

    def _try_click_in_root(root) -> bool:
        for sel in selectors:
            try:
                loc = root.locator(sel).first
                if loc.count() == 0:
                    continue
                if not loc.is_visible():
                    continue

                # 1) 일반 클릭
                try:
                    loc.click(timeout=timeout_ms)
                    return True
                except Exception:
                    pass

                # 2) trial 클릭(가능 여부 테스트) 후 force 클릭
                try:
                    loc.click(trial=True, timeout=timeout_ms)
                except Exception:
                    pass
                try:
                    loc.click(force=True, timeout=timeout_ms)
                    return True
                except Exception:
                    pass

                # 3) 좌표 클릭 폴백
                try:
                    bb = loc.bounding_box()
                    if bb:
                        root.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2)
                        return True
                except Exception:
                    pass
            except Exception:
                continue
        return False

    # page 먼저
    if _try_click_in_root(page):
        return True
    # frames
    for fr in list(page.frames):
        try:
            if _try_click_in_root(fr):
                return True
        except Exception:
            continue
    return False


def _diagnose_click_intercept(page, loc) -> dict:
    """클릭이 막힐 때(투명 오버레이 등) 화면 최상단 요소가 무엇인지 진단."""
    try:
        bb = loc.bounding_box()
        if not bb:
            return {"ok": False, "reason": "no_bounding_box"}
        x = bb["x"] + bb["width"] / 2
        y = bb["y"] + bb["height"] / 2
        info = page.evaluate(
            """([x,y]) => {
                const el = document.elementFromPoint(x,y);
                if (!el) return {found:false};
                const cs = window.getComputedStyle(el);
                const path = [];
                let cur = el;
                for (let i=0; i<6 && cur; i++) {
                    const id = cur.id ? ('#'+cur.id) : '';
                    const cls = cur.className && typeof cur.className==='string' ? ('.'+cur.className.split(/\s+/).filter(Boolean).slice(0,3).join('.')) : '';
                    path.push(cur.tagName.toLowerCase()+id+cls);
                    cur = cur.parentElement;
                }
                return {
                    found:true,
                    tag: el.tagName,
                    id: el.id || null,
                    className: (typeof el.className==='string' ? el.className : null),
                    pointerEvents: cs.pointerEvents,
                    opacity: cs.opacity,
                    zIndex: cs.zIndex,
                    text: (el.innerText || '').slice(0,80),
                    path
                };
            }""",
            [x, y],
        )
        return {"ok": True, "x": x, "y": y, "top": info}
    except Exception as e:
        return {"ok": False, "reason": f"diagnose_failed: {e}"}


def _attempt_close_common_overlays(page) -> bool:
    """발행 버튼을 가리는 투명/반투명 오버레이를 닫기 시도."""
    # 1) ESC로 닫히는 레이어가 많음
    try:
        page.keyboard.press("Escape")
        page.wait_for_timeout(200)
    except Exception:
        pass

    # 2) 흔한 dim/backdrop 후보를 클릭해 닫기(너무 위험한 광역 클릭은 피하고, role/aria 기반 위주)
    overlay_selectors = [
        "[role='dialog']",
        "[aria-modal='true']",
        "div[role='presentation']",
        "div[class*='dim']",
        "div[class*='Dim']",
        "div[class*='overlay']",
        "div[class*='Overlay']",
        "div[class*='backdrop']",
        "div[class*='Backdrop']",
    ]
    closed = False
    for sel in overlay_selectors:
        try:
            loc = page.locator(sel).first
            if loc.count() > 0 and loc.is_visible():
                # dim 영역은 중앙 클릭으로 닫히는 케이스가 있어 bbox 클릭
                bb = loc.bounding_box()
                if bb:
                    page.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2)
                    page.wait_for_timeout(250)
                    closed = True
        except Exception:
            continue
    return closed


def _js_force_click(page, selector: str) -> bool:
    """Playwright click이 계속 막힐 때 JS 이벤트를 직접 발생(최후 수단)."""
    try:
        ok = page.evaluate(
            """(sel) => {
                const el = document.querySelector(sel);
                if (!el) return false;
                el.scrollIntoView({block:'center', inline:'center'});
                const opts = {bubbles:true, cancelable:true, composed:true};
                el.dispatchEvent(new PointerEvent('pointerdown', opts));
                el.dispatchEvent(new MouseEvent('mousedown', opts));
                el.dispatchEvent(new MouseEvent('mouseup', opts));
                el.dispatchEvent(new MouseEvent('click', opts));
                return true;
            }""",
            selector,
        )
        return bool(ok)
    except Exception:
        return False


def close_help_dialog_if_present(page) -> bool:
    """글쓰기 화면 우측 상단에 뜨는 '도움말/가이드' 계열 다이얼로그를 닫습니다.

    네이버 스마트에디터의 도움말은 표준 ARIA role을 사용하지 않는 경우가 많아,
    1) 에디터 전용 클래스(se-help, se-guide, coaching 등)를 JS로 직접 스캔
    2) z-index가 높은 오버레이 내부의 X/닫기 버튼을 자동 감지
    3) page + 모든 iframe에서 시도
    """
    deadline = time.time() + 10.0

    # 약간 대기 후 시작(말풍선 애니메이션 대비)
    try:
        page.wait_for_timeout(500)
    except Exception:
        time.sleep(0.5)

    # ---------- JS 기반: 에디터 프레임 내 도움말 오버레이 X 버튼 탐색 및 클릭 ----------
    _JS_FIND_AND_CLOSE_HELP = """() => {
        // 1단계: 네이버 에디터 전용 도움말/가이드/코칭 클래스 패턴으로 오버레이 탐색
        const helpPatterns = [
            'se-help', 'se-guide', 'se-tooltip', 'se-coach', 'se-popover',
            'help_popup', 'helpPopup', 'guide_popup', 'guidePopup',
            'coaching', 'onboarding', 'tooltip_layer', 'tooltipLayer',
            'help_layer', 'helpLayer', 'guide_layer', 'guideLayer',
            'help-balloon', 'helpBalloon', 'help_area', 'helpArea',
            'noti_popup', 'notiPopup', 'notice_popup', 'noticePopup',
        ];

        const rolePatterns = ['dialog', 'tooltip', 'alertdialog'];
        const textPatterns = ['도움말', '가이드', 'help', 'guide', '안내', '팁'];

        function isVisible(el) {
            if (!el) return false;
            const r = el.getBoundingClientRect();
            if (r.width < 10 || r.height < 10) return false;
            const cs = window.getComputedStyle(el);
            if (cs.display === 'none' || cs.visibility === 'hidden' || cs.opacity === '0') return false;
            return true;
        }

        function findCloseButtonInside(container) {
            // X 닫기 버튼 찾기 (여러 패턴)
            const closeSelectors = [
                'button[class*="close"]', 'button[class*="Close"]',
                'a[class*="close"]', 'a[class*="Close"]',
                'span[class*="close"]', 'span[class*="Close"]',
                'div[class*="close"]', 'div[class*="Close"]',
                'button[class*="cancel"]', 'button[class*="Cancel"]',
                '[aria-label*="닫기"]', '[aria-label*="Close"]', '[aria-label*="close"]',
                '[title*="닫기"]', '[title*="Close"]', '[title*="close"]',
                'button:last-child', // 종종 X가 마지막 자식
            ];

            for (const sel of closeSelectors) {
                try {
                    const els = container.querySelectorAll(sel);
                    for (const el of els) {
                        if (isVisible(el)) return el;
                    }
                } catch(e) {}
            }

            // SVG 아이콘이 있는 button/a 찾기
            const btnsWithSvg = container.querySelectorAll('button, a, [role="button"]');
            for (const b of btnsWithSvg) {
                if (!isVisible(b)) continue;
                if (b.querySelector('svg') || b.querySelector('img')) {
                    const r = b.getBoundingClientRect();
                    // X 닫기 버튼은 보통 작은 크기(40px 이하)
                    if (r.width <= 50 && r.height <= 50) return b;
                }
                // 텍스트가 X, ×, ✕ 인 경우
                const txt = (b.textContent || '').trim();
                if (txt === 'X' || txt === '×' || txt === '✕' || txt === '✖' || txt === '닫기') {
                    return b;
                }
            }

            // span/div 중 X 텍스트를 가진 것
            const allSpans = container.querySelectorAll('span, div, i');
            for (const s of allSpans) {
                if (!isVisible(s)) continue;
                const txt = (s.textContent || '').trim();
                if ((txt === 'X' || txt === '×' || txt === '✕' || txt === '✖') && s.getBoundingClientRect().width <= 40) {
                    return s;
                }
            }

            // 컨테이너 우측 끝에 있는 클릭 가능한 요소 찾기 (X 아이콘은 보통 오른쪽 끝에 위치)
            const containerRect = container.getBoundingClientRect();
            const rightEdge = containerRect.right;
            const allClickable = container.querySelectorAll('button, a, [role="button"], span, div');
            let rightMost = null;
            let rightMostX = -Infinity;
            for (const el of allClickable) {
                if (!isVisible(el)) continue;
                const r = el.getBoundingClientRect();
                // 크기가 적당히 작은 요소만 (닫기 버튼 크기)
                if (r.width > 60 || r.height > 60) continue;
                if (r.width < 5 || r.height < 5) continue;
                // 컨테이너 우측 20% 이내
                if (r.left > containerRect.left + containerRect.width * 0.7) {
                    if (r.right > rightMostX) {
                        rightMostX = r.right;
                        rightMost = el;
                    }
                }
            }
            if (rightMost) return rightMost;

            return null;
        }

        function clickElement(el) {
            try {
                el.scrollIntoView({block:'center', inline:'center'});
                const opts = {bubbles:true, cancelable:true, composed:true};
                el.dispatchEvent(new PointerEvent('pointerdown', opts));
                el.dispatchEvent(new MouseEvent('mousedown', opts));
                el.dispatchEvent(new MouseEvent('mouseup', opts));
                el.dispatchEvent(new MouseEvent('click', opts));
                return true;
            } catch(e) {
                return false;
            }
        }

        // --- 메인 탐색 로직 ---
        const results = [];

        // (A) 클래스 패턴으로 도움말 컨테이너 찾기
        const allElements = document.querySelectorAll('*');
        for (const el of allElements) {
            if (!isVisible(el)) continue;
            const cls = (typeof el.className === 'string' ? el.className : '').toLowerCase();
            const role = (el.getAttribute('role') || '').toLowerCase();
            const text = (el.innerText || '').slice(0, 100).toLowerCase();

            let isHelp = false;

            // 클래스 패턴 매치
            for (const pat of helpPatterns) {
                if (cls.includes(pat.toLowerCase())) { isHelp = true; break; }
            }

            // role 패턴 매치(+ 텍스트 내용이 도움말 관련)
            if (!isHelp) {
                for (const rp of rolePatterns) {
                    if (role === rp) {
                        for (const tp of textPatterns) {
                            if (text.includes(tp)) { isHelp = true; break; }
                        }
                        if (isHelp) break;
                    }
                }
            }

            if (!isHelp) continue;

            // 도움말 컨테이너 발견 → X 닫기 버튼 찾기
            const closeBtn = findCloseButtonInside(el);
            const r = el.getBoundingClientRect();
            results.push({
                found: true,
                cls: (typeof el.className === 'string' ? el.className.slice(0, 120) : ''),
                rect: {x: r.x, y: r.y, w: r.width, h: r.height},
                hasCloseBtn: !!closeBtn,
                closeBtnTag: closeBtn ? closeBtn.tagName : null,
                closeBtnCls: closeBtn ? (typeof closeBtn.className === 'string' ? closeBtn.className.slice(0, 80) : '') : null,
            });

            if (closeBtn) {
                const clicked = clickElement(closeBtn);
                return {ok: true, method: 'class_pattern', clicked: clicked, detail: results[results.length - 1]};
            }
        }

        // (B) z-index가 높은(100 이상) visible 오버레이 스캔
        const overlays = [];
        for (const el of allElements) {
            if (!isVisible(el)) continue;
            const cs = window.getComputedStyle(el);
            const z = parseInt(cs.zIndex, 10);
            if (isNaN(z) || z < 100) continue;
            const r = el.getBoundingClientRect();
            // 너무 큰 요소(전체화면)나 너무 작은 요소는 제외
            if (r.width > window.innerWidth * 0.8 && r.height > window.innerHeight * 0.8) continue;
            if (r.width < 30 || r.height < 30) continue;

            overlays.push({el, z, r});
        }
        // z-index 높은 순으로 정렬
        overlays.sort((a, b) => b.z - a.z);

        for (const ov of overlays.slice(0, 5)) {
            const closeBtn = findCloseButtonInside(ov.el);
            if (closeBtn) {
                const clicked = clickElement(closeBtn);
                return {
                    ok: true, method: 'z_index_overlay', clicked: clicked, zIndex: ov.z,
                    cls: (typeof ov.el.className === 'string' ? ov.el.className.slice(0, 80) : ''),
                };
            }
        }

        // (C) 위 방법 모두 실패 → 우측 상단 영역의 작은 버튼/클릭가능 요소를 클릭
        //     도움말 X는 보통 화면 우측 상단에 위치
        const vpW = window.innerWidth;
        const candidates = [];
        for (const el of document.querySelectorAll('button, a, [role="button"], span')) {
            if (!isVisible(el)) continue;
            const r = el.getBoundingClientRect();
            // 우측 30% 영역, 상단 25% 영역 내의 작은 요소
            if (r.left > vpW * 0.7 && r.top < window.innerHeight * 0.25) {
                if (r.width <= 50 && r.height <= 50 && r.width >= 8 && r.height >= 8) {
                    const txt = (el.textContent || '').trim();
                    const aria = el.getAttribute('aria-label') || el.getAttribute('title') || '';
                    const hasSvg = !!el.querySelector('svg');
                    const isCloselike = (
                        txt === 'X' || txt === '×' || txt === '✕' || txt === '닫기' ||
                        aria.includes('닫기') || aria.includes('close') || aria.includes('Close') ||
                        hasSvg || txt === ''
                    );
                    if (isCloselike) {
                        candidates.push({el, r, score: (hasSvg ? 10 : 0) + (txt === '' ? 5 : 0) + (r.left / vpW * 10)});
                    }
                }
            }
        }
        // 가장 우측에 있는 후보 클릭
        candidates.sort((a, b) => b.score - a.score || b.r.left - a.r.left);
        if (candidates.length > 0) {
            const clicked = clickElement(candidates[0].el);
            return {ok: true, method: 'top_right_scan', clicked: clicked, count: candidates.length};
        }

        return {ok: false, reason: 'no_help_overlay_found', scanned: results.length};
    }"""

    def _try_js_close_in_root(root) -> dict:
        """단일 root(page or frame)에서 JS 기반 도움말 닫기를 시도."""
        try:
            return root.evaluate(_JS_FIND_AND_CLOSE_HELP)
        except Exception as e:
            return {"ok": False, "reason": f"js_error: {e}"}

    # ---------- 기존 Playwright 셀렉터 기반 닫기 (보조) ----------
    def _try_playwright_close(root) -> bool:
        """Playwright 셀렉터로 닫기 버튼을 찾아 클릭."""
        close_selectors = [
            # 네이버 에디터 전용 패턴
            "[class*='se-help'] button",
            "[class*='se-guide'] button",
            "[class*='se-tooltip'] button",
            "[class*='se-coach'] button",
            "[class*='se-help'] [class*='close']",
            "[class*='se-guide'] [class*='close']",
            "[class*='help'] [class*='close']",
            "[class*='guide'] [class*='close']",
            "[class*='tooltip'] [class*='close']",
            "[class*='coaching'] [class*='close']",
            # 표준 ARIA
            "button[aria-label*='닫기']",
            "button[title*='닫기']",
            "[role='button'][aria-label*='닫기']",
            "button[aria-label*='Close']",
            "button[title*='Close']",
            # 일반
            "button:has-text('닫기')",
            "button:has(svg)",
        ]
        for sel in close_selectors:
            try:
                loc = root.locator(sel).first
                if loc.count() > 0 and loc.is_visible():
                    try:
                        loc.click(timeout=800, force=True)
                        return True
                    except Exception:
                        bb = loc.bounding_box()
                        if bb:
                            page.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2)
                            return True
            except Exception:
                continue
        return False

    # ---------- 메인 루프 ----------
    attempt = 0
    debug_dumped = False

    while time.time() < deadline:
        attempt += 1

        # (1) JS 기반 닫기 — page + 모든 frame
        roots = [page] + list(page.frames)
        for root in roots:
            result = _try_js_close_in_root(root)
            if result.get("ok"):
                print(f"[help] JS close success: {result}")
                try:
                    page.wait_for_timeout(500)
                except Exception:
                    time.sleep(0.5)
                return True

        # (2) Playwright 셀렉터 기반 닫기
        for root in roots:
            try:
                if _try_playwright_close(root):
                    print(f"[help] Playwright close success in {getattr(root, 'url', 'page')[:60]}")
                    try:
                        page.wait_for_timeout(500)
                    except Exception:
                        time.sleep(0.5)
                    return True
            except Exception:
                continue

        # (3) ESC 키
        try:
            page.keyboard.press("Escape")
            page.wait_for_timeout(300)
        except Exception:
            pass

        # ESC 후 닫혔는지 빠르게 확인
        esc_closed = True
        for root in roots:
            r = _try_js_close_in_root(root)
            if r.get("ok"):
                # 아직 닫히지 않았다는 의미(새로 찾았으니까)
                esc_closed = False
                print(f"[help] found again after ESC, JS re-close: {r}")
                try:
                    page.wait_for_timeout(300)
                except Exception:
                    time.sleep(0.3)
                break

        # 아무것도 못 찾았으면 (JS가 no_help_overlay_found 반환) → 이미 닫힌 것
        all_not_found = True
        for root in roots:
            r = _try_js_close_in_root(root)
            if r.get("ok"):
                all_not_found = False
                break
        if all_not_found:
            print(f"[help] no overlay found → considered closed (attempt={attempt})")
            return True

        # (4) 디버그 덤프 (첫 1회만)
        if not debug_dumped:
            debug_dumped = True
            try:
                # 각 frame에서 도움말 관련 요소 진단 로그
                for idx, root in enumerate(roots[:6]):
                    try:
                        diag = root.evaluate("""() => {
                            const all = document.querySelectorAll('*');
                            const hits = [];
                            const patterns = ['help','guide','tooltip','coach','popup','balloon','noti','onboard'];
                            for (const el of all) {
                                const cls = (typeof el.className === 'string' ? el.className : '').toLowerCase();
                                const r = el.getBoundingClientRect();
                                if (r.width < 10 || r.height < 10) continue;
                                const cs = window.getComputedStyle(el);
                                if (cs.display === 'none' || cs.visibility === 'hidden') continue;
                                for (const p of patterns) {
                                    if (cls.includes(p)) {
                                        hits.push({
                                            tag: el.tagName, cls: cls.slice(0,100),
                                            rect: {x:r.x|0, y:r.y|0, w:r.width|0, h:r.height|0},
                                            children: el.children.length,
                                            text: (el.innerText||'').replace(/\\s+/g,' ').slice(0,50),
                                        });
                                        break;
                                    }
                                }
                            }
                            return hits.slice(0, 10);
                        }""")
                        if diag:
                            print(f"[help][diag] root[{idx}] url={getattr(root, 'url', 'page')[:60]} hits={diag}")
                    except Exception as e:
                        print(f"[help][diag] root[{idx}] failed: {e}")
            except Exception:
                pass

            try:
                p = Path(__file__).with_name("debug_help_overlay.png")
                page.screenshot(path=str(p), full_page=True)
                print(f"[help][diag] screenshot saved: {p}")
            except Exception:
                pass

        try:
            page.wait_for_timeout(400)
        except Exception:
            time.sleep(0.4)

    print(f"[help] timeout after {attempt} attempts")
    return False


def publish_post(page, *, timeout_ms: int = 60000) -> dict:
    """네이버 블로그 에디터에서 '발행'을 2단계로 눌러 최종 게시까지 진행.

    흐름(일반적):
    1) 우측 상단 '발행'
    2) 발행 설정/확인 다이얼로그에서 '발행' 또는 '확인'
    3) 게시 완료 후 게시글 화면(또는 완료 토스트)로 전환
    """
    print("[publish] start")

    # ── 0단계: 이미지 업로드/개별사진 선택 직후의 에디터 안정화 대기 ──
    # 이미지 업로드 → 개별사진 클릭까지 걸리는 시간만큼, 도움말 닫기 전에도 에디터가 안정화되어야 함
    try:
        pre_help_delay = float(os.getenv("NAVER_PRE_HELP_DELAY", "3.0").strip() or "3.0")
    except Exception:
        pre_help_delay = 3.0
    if pre_help_delay > 0:
        print(f"[publish] pre-help stabilization wait {pre_help_delay}s")
        try:
            page.wait_for_timeout(int(pre_help_delay * 1000))
        except Exception:
            time.sleep(pre_help_delay)

    # ── 1단계: 도움말 닫기 (반복 시도 + 확인 루프) ──
    # close_help_dialog_if_present는 내부에서 JS 전면 스캔 + Playwright + ESC 등을 시도하고
    # True(닫힘/없음) 또는 False(타임아웃)를 반환.
    # True가 돌아와도 혹시 남아있을 수 있어, 한 번 더 호출해서 '찾을 게 없음'을 확인.
    help_confirmed_closed = False
    for help_attempt in range(1, 4):  # 최대 3회
        try:
            result = close_help_dialog_if_present(page)
            print(f"[publish] help close attempt={help_attempt} result={result}")
        except Exception as e:
            print(f"[publish] help close attempt={help_attempt} error={e}")
            result = False

        if result:
            # 닫기 성공 후 잠깐 대기하고 재확인
            try:
                page.wait_for_timeout(800)
            except Exception:
                time.sleep(0.8)

            # 한 번 더 호출해서 정말 닫혔는지(= 찾을 게 없는지) 확인
            try:
                result2 = close_help_dialog_if_present(page)
                print(f"[publish] help re-verify attempt={help_attempt} result={result2}")
            except Exception:
                result2 = True  # 에러면 없는 것으로 간주

            if result2:
                help_confirmed_closed = True
                print(f"[publish] help confirmed closed after {help_attempt} attempts")
                break
            else:
                print(f"[publish] help still present after attempt={help_attempt}, retrying...")
        else:
            # False = 타임아웃까지 못 닫음 → 한 번 더 시도
            print(f"[publish] help close timed out attempt={help_attempt}")

        try:
            page.wait_for_timeout(500)
        except Exception:
            time.sleep(0.5)

    if not help_confirmed_closed:
        print("[publish] WARNING: help dialog may still be open after all attempts, proceeding anyway")

    # ── 2단계: 도움말 닫힌 뒤 UI 재배치 안정화 대기 ──
    try:
        delay1 = float(os.getenv("NAVER_PUBLISH_DELAY1", "2.0").strip() or "2.0")
    except Exception:
        delay1 = 2.0
    if delay1 > 0:
        print(f"[publish] post-help stabilization wait {delay1}s")
        try:
            page.wait_for_timeout(int(delay1 * 1000))
        except Exception:
            time.sleep(delay1)

    # ── 3단계: 발행 버튼이 클릭 가능해질 때까지 대기 ──
    publish_ready_selectors = [
        ".publish_btn__m9KHH",
        ".publish_btn__m9KHH button",
        "[class*='publish_btn__']",
        "[class*='publish_btn__'] button",
        "button:has-text('발행')",
        "a:has-text('발행')",
        "[role='button'][aria-label*='발행']",
    ]

    def _any_visible_enabled_in_page_or_frames() -> bool:
        roots = [page] + list(page.frames)
        for root in roots:
            for sel in publish_ready_selectors:
                try:
                    loc = root.locator(sel).first
                    if loc.count() > 0 and loc.is_visible() and loc.is_enabled():
                        return True
                except Exception:
                    continue
        return False

    # 디버그: frame 구조 로그
    try:
        fr_urls = []
        for fr in list(page.frames):
            try:
                fr_urls.append(fr.url)
            except Exception:
                fr_urls.append("(no-url)")
        print(f"[publish] frames={len(fr_urls)}")
        for u in fr_urls[:8]:
            print(f"  - frame: {u}")
    except Exception:
        pass

    print("[publish] waiting publish button visible/enabled")
    deadline_ready = time.time() + (timeout_ms / 1000)
    while time.time() < deadline_ready:
        if _any_visible_enabled_in_page_or_frames():
            break
        time.sleep(0.3)
    print("[publish] trying first click")

    # '발행'은 다이얼로그/팝업에도 동일 텍스트가 있을 수 있어,
    # 1차 발행은 헤더/상단 영역을 최대한 우선으로 잡습니다.
    # 사용자 확인: 발행 버튼이 특정 클래스(publish_btn__m9KHH)로 감싸진 케이스가 있음
    publish_selectors = [
        # 가장 구체적인 후보(네이버 에디터 버전에 따라 해시 클래스가 바뀔 수 있어도 우선)
        ".publish_btn__m9KHH",
        ".publish_btn__m9KHH button",
        ".publish_btn__m9KHH a",
        # 클래스가 바뀌는 케이스 대응
        "[class*='publish_btn__']",
        "[class*='publish_btn__'] button",
        "[class*='publish_btn__'] a",
        # 접근성 role 기반(있으면 가장 안정적)
        "[role='button'][aria-label*='발행']",
        # 상단 헤더/툴바로 스코프 제한(오탐 방지)
        "header button:has-text('발행')",
        "header a:has-text('발행')",
        "[role='banner'] button:has-text('발행')",
        "[role='banner'] a:has-text('발행')",
        "[class*='header'] button:has-text('발행')",
        "[class*='Header'] button:has-text('발행')",
        "[class*='toolbar'] button:has-text('발행')",
        "[class*='ToolBar'] button:has-text('발행')",
        # 범용 fallback
        "button:has-text('발행')",
        "a:has-text('발행')",
        "button[aria-label*='발행']",
        "text=발행",
    ]

    # 1차 발행 버튼 대기/클릭
    # - page 뿐 아니라 iframe 안에 버튼이 있을 수 있어 _wait_for_any_selector 대신 robust click으로 바로 시도
    if not _robust_click_in_page_or_frames(page, publish_selectors, timeout_ms=3000):
        return {"ok": False, "reason": "publish_button_not_found"}

    # '보이지만 클릭이 안 됨' 케이스 대응:
    # - 오버레이가 남아 클릭을 가로채는 경우가 있어 ESC로 1회 정리
    # - 상단 고정 버튼이라 scrollIntoView가 의미 없을 수 있지만, 포커스/레이아웃 안정화 용으로 시도
    try:
        page.keyboard.press("Escape")
        page.wait_for_timeout(200)
    except Exception:
        pass

    if not _robust_click_in_page_or_frames(page, publish_selectors, timeout_ms=3000):
        # === 진단/해소: 투명 오버레이 클릭 가로채기 여부 ===
        diag = None
        try:
            publish_loc = page.locator(".publish_btn__m9KHH").first
            if publish_loc.count() == 0:
                publish_loc = page.locator("button:has-text('발행')").first
            if publish_loc.count() > 0:
                diag = _diagnose_click_intercept(page, publish_loc)
                print(f"[publish][diag] {diag}")
        except Exception:
            pass

        # 오버레이/모달 닫기 시도 후 재시도
        _attempt_close_common_overlays(page)
        try:
            page.wait_for_timeout(400)
        except Exception:
            pass

        if _robust_click_in_page_or_frames(page, publish_selectors, timeout_ms=3000):
            pass
        else:
            # JS 강제 클릭(가장 구체 selector부터)
            if _js_force_click(page, ".publish_btn__m9KHH") or _js_force_click(page, ".publish_btn__m9KHH button"):
                pass
            else:
                try:
                    page.keyboard.press("Enter")
                except Exception:
                    pass
                # 마지막 폴백: 화면에서 '발행' 텍스트 노드의 bbox를 직접 클릭
                try:
                    loc = page.get_by_text("발행", exact=True).first
                    if loc.count() > 0 and loc.is_visible():
                        bb = loc.bounding_box()
                        if bb:
                            page.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2)
                        else:
                            return {"ok": False, "reason": "publish_click_failed", "diag": diag}
                    else:
                        return {"ok": False, "reason": "publish_click_failed", "diag": diag}
                except Exception:
                    return {"ok": False, "reason": "publish_click_failed", "diag": diag}

    print("[publish] first click done; waiting dialog")

    # 2차 발행 전 잠깐 대기(발행 설정 다이얼로그 렌더링 시간)
    try:
        delay2 = float(os.getenv("NAVER_PUBLISH_DELAY2", "1.0").strip() or "1.0")
    except Exception:
        delay2 = 1.0
    if delay2 > 0:
        try:
            page.wait_for_timeout(int(delay2 * 1000))
        except Exception:
            time.sleep(delay2)

    # 2차 다이얼로그 발행(또는 확인/완료)
    # - 1차 발행 클릭 후 '발행 설정' 다이얼로그가 뜨고, 그 안의 '발행' 버튼을 눌러야 최종 게시됨
    # - 헤더의 1차 발행 버튼과 혼동하지 않도록, 다이얼로그/모달 컨텍스트 내부를 우선 검색

    # 다이얼로그 감지 셀렉터(1차 발행 클릭 후 나타나는 설정/확인 레이어)
    dialog_container_selectors = [
        "[role='dialog']",
        "[aria-modal='true']",
        "div[class*='layer']",
        "div[class*='Layer']",
        "div[class*='modal']",
        "div[class*='Modal']",
        "div[class*='popup']",
        "div[class*='Popup']",
        "div[class*='dialog']",
        "div[class*='Dialog']",
        "div[class*='publish_layer']",
        "div[class*='PublishLayer']",
        "div[class*='setting']",
    ]

    # 다이얼로그 안에서 찾을 2차 발행 버튼 셀렉터
    dialog_confirm_selectors = [
        # 가장 구체적: 사용자 확인된 2차 발행 버튼 클래스
        ".confirm_btn__WEaBq",
        ".confirm_btn__WEaBq button",
        "[class*='confirm_btn__']",
        "[class*='confirm_btn__'] button",
        "button:has-text('발행')",
        "button:has-text('확인')",
        "button:has-text('완료')",
        "button:has-text('등록')",
    ]

    # 범용 (다이얼로그 스코프 제한 없이)
    fallback_confirm_selectors = [
        ".confirm_btn__WEaBq",
        ".confirm_btn__WEaBq button",
        "[class*='confirm_btn__']",
        "[class*='confirm_btn__'] button",
        "button:has-text('발행')",
        "text=발행",
        "button:has-text('확인')",
        "button:has-text('완료')",
        "button:has-text('등록')",
    ]

    deadline = time.time() + (timeout_ms / 1000)
    clicked2 = False

    def _try_click_in_dialog(root) -> bool:
        """다이얼로그 컨테이너 내부에서 발행/확인 버튼을 스코프 한정하여 클릭 시도."""
        for dc_sel in dialog_container_selectors:
            try:
                containers = root.locator(dc_sel)
                for ci in range(min(containers.count(), 5)):
                    container = containers.nth(ci)
                    if not container.is_visible():
                        continue
                    for btn_sel in dialog_confirm_selectors:
                        try:
                            btn = container.locator(btn_sel).first
                            if btn.count() > 0 and btn.is_visible() and btn.is_enabled():
                                try:
                                    btn.click(timeout=2000)
                                    return True
                                except Exception:
                                    try:
                                        btn.click(timeout=2000, force=True)
                                        return True
                                    except Exception:
                                        bb = btn.bounding_box()
                                        if bb:
                                            root.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2)
                                            return True
                        except Exception:
                            continue
            except Exception:
                continue
        return False

    while time.time() < deadline:
        # (★) 최우선: confirm_btn__WEaBq 클래스로 2차 발행 버튼 직접 검색 (page + 모든 frame)
        direct_selectors = [
            ".confirm_btn__WEaBq",
            ".confirm_btn__WEaBq button",
            "[class*='confirm_btn__']",
            "[class*='confirm_btn__'] button",
        ]
        roots = [page] + list(page.frames)
        for root in roots:
            for sel in direct_selectors:
                try:
                    loc = root.locator(sel).first
                    if loc.count() > 0 and loc.is_visible() and loc.is_enabled():
                        try:
                            loc.click(timeout=2000)
                            clicked2 = True
                        except Exception:
                            try:
                                loc.click(timeout=2000, force=True)
                                clicked2 = True
                            except Exception:
                                bb = loc.bounding_box()
                                if bb:
                                    page.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2)
                                    clicked2 = True
                        if clicked2:
                            print(f"[publish] 2nd button found via direct selector: {sel}")
                            break
                except Exception:
                    continue
            if clicked2:
                break
        if clicked2:
            try:
                page.wait_for_timeout(600)
            except Exception:
                pass
            break

        # (A) 다이얼로그 컨텍스트 내부 검색 (page + 모든 frame)
        roots = [page] + list(page.frames)
        for root in roots:
            try:
                if _try_click_in_dialog(root):
                    clicked2 = True
                    break
            except Exception:
                continue
        if clicked2:
            try:
                page.wait_for_timeout(600)
            except Exception:
                pass
            break

        # (B) 다이얼로그를 못 찾으면 범용 fallback (1차 버튼과 같은 걸 다시 누르는 리스크가 있지만 최후 수단)
        #     단, 1차 버튼과 구분하기 위해 publish_btn 클래스가 아닌 버튼만 시도
        for root in roots:
            for sel in fallback_confirm_selectors:
                try:
                    locs = root.locator(sel)
                    for li in range(min(locs.count(), 5)):
                        loc = locs.nth(li)
                        if not loc.is_visible() or not loc.is_enabled():
                            continue
                        # 1차 발행 버튼(헤더)은 publish_btn 클래스를 가짐 → 건너뛰기
                        try:
                            cls = loc.get_attribute("class") or ""
                            parent_cls = loc.evaluate("el => el.parentElement ? (el.parentElement.className || '') : ''") or ""
                        except Exception:
                            cls = ""
                            parent_cls = ""
                        if "publish_btn" in cls or "publish_btn" in parent_cls:
                            continue  # 1차 버튼 스킵
                        try:
                            loc.click(timeout=2000)
                            clicked2 = True
                            break
                        except Exception:
                            try:
                                loc.click(timeout=2000, force=True)
                                clicked2 = True
                                break
                            except Exception:
                                bb = loc.bounding_box()
                                if bb:
                                    root.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2)
                                    clicked2 = True
                                    break
                except Exception:
                    continue
                if clicked2:
                    break
            if clicked2:
                break
        if clicked2:
            try:
                page.wait_for_timeout(600)
            except Exception:
                pass
            break

        # (C) JS 강제 클릭: 다이얼로그 내부 발행 버튼을 JS로 직접 찾아 클릭
        for root in roots:
            try:
                js_ok = root.evaluate("""() => {
                    const opts = {bubbles:true, cancelable:true, composed:true};
                    function forceClick(el) {
                        el.scrollIntoView({block:'center'});
                        el.dispatchEvent(new PointerEvent('pointerdown', opts));
                        el.dispatchEvent(new MouseEvent('mousedown', opts));
                        el.dispatchEvent(new MouseEvent('mouseup', opts));
                        el.dispatchEvent(new MouseEvent('click', opts));
                        return true;
                    }

                    // 1) confirm_btn 클래스로 직접 찾기
                    const confirmBtn = document.querySelector('[class*="confirm_btn__"]');
                    if (confirmBtn && confirmBtn.offsetWidth > 0 && confirmBtn.offsetHeight > 0) {
                        // 자신이 button이면 바로 클릭, 아니면 내부 button 찾기
                        const btn = confirmBtn.tagName === 'BUTTON' ? confirmBtn : (confirmBtn.querySelector('button') || confirmBtn);
                        return forceClick(btn);
                    }

                    // 2) 다이얼로그/모달 컨테이너 안의 '발행' 버튼을 찾아 클릭
                    const dialogs = document.querySelectorAll('[role=dialog], [aria-modal=true], [class*=layer], [class*=Layer], [class*=modal], [class*=Modal], [class*=popup], [class*=Popup]');
                    for (const d of dialogs) {
                        if (d.offsetWidth === 0 || d.offsetHeight === 0) continue;
                        const btns = d.querySelectorAll('button');
                        for (const b of btns) {
                            const txt = (b.innerText || '').trim();
                            if (txt === '발행' || txt === '확인' || txt === '완료' || txt === '등록') {
                                if (b.offsetWidth > 0 && b.offsetHeight > 0) {
                                    return forceClick(b);
                                }
                            }
                        }
                    }
                    return false;
                }""")
                if js_ok:
                    clicked2 = True
                    break
            except Exception:
                continue
        if clicked2:
            try:
                page.wait_for_timeout(600)
            except Exception:
                pass
            break

        # 아직 다이얼로그 로딩 중이면 잠깐 대기
        time.sleep(0.3)

    print(f"[publish] second click clicked2={clicked2}")

    if not clicked2:
        # 2차 버튼이 안 나타나는 UI도 있어서, 여기서 바로 성공/실패 단정하지 않고 다음 전환 감지로 넘어감
        pass

    # 게시 완료 전환 감지: URL 변화 or '작성완료/발행완료' 텍스트 or blog.naver.com 포스트 화면 등
    done_selectors = [
        "text=발행이 완료",
        "text=발행 완료",
        "text=작성 완료",
        "text=게시",
    ]

    while time.time() < deadline:
        try:
            u = page.url or ""
            # 작성 페이지는 대개 write/Redirect=Write 류, 완료 후에는 /PostView.naver 또는 blog.naver.com/*/ 등으로 전환되는 경향
            if "PostView" in u or ("blog.naver.com" in u and "Redirect=Write" not in u and "write" not in u.lower()):
                return {"ok": True, "reason": "url_changed", "url": u}
        except Exception:
            pass

        for sel in done_selectors:
            try:
                loc = page.locator(sel).first
                if loc.count() > 0 and loc.is_visible():
                    return {"ok": True, "reason": "done_text", "url": page.url}
            except Exception:
                continue

        time.sleep(0.5)

    return {"ok": False, "reason": "publish_timeout", "url": page.url}


def _init_db(db_path: str = DB_PATH) -> None:
    Path(db_path).parent.mkdir(parents=True, exist_ok=True)
    with sqlite3.connect(db_path) as con:
        con.execute(
            """
            CREATE TABLE IF NOT EXISTS post_map (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                tistory_post_id TEXT NOT NULL,
                naver_written_at TEXT NOT NULL,
                tistory_url TEXT,
                created_at TEXT NOT NULL DEFAULT (strftime('%Y%m%d%H%M%S','now')),
                UNIQUE(tistory_post_id, naver_written_at)
            );
            """
        )
        con.execute("CREATE INDEX IF NOT EXISTS ix_post_map_written_at ON post_map(naver_written_at);")


def _get_recent_records(limit: int = 10, db_path: str = DB_PATH) -> list[dict]:
    _init_db(db_path)
    with sqlite3.connect(db_path) as con:
        con.row_factory = sqlite3.Row
        rows = con.execute(
            """
            SELECT tistory_post_id, naver_written_at, tistory_url, created_at
            FROM post_map
            ORDER BY naver_written_at DESC
            LIMIT ?;
            """,
            (limit,),
        ).fetchall()
    return [dict(r) for r in rows]


def _save_record(*, tistory_post_id: str, naver_written_at: str, tistory_url: str, db_path: str = DB_PATH) -> None:
    _init_db(db_path)
    with sqlite3.connect(db_path) as con:
        con.execute(
            """
            INSERT OR IGNORE INTO post_map (tistory_post_id, naver_written_at, tistory_url, created_at)
            VALUES (?, ?, ?, ?);
            """,
            (tistory_post_id, naver_written_at, tistory_url, datetime.now().strftime("%Y%m%d%H%M%S")),
        )


def _tistory_post_id_from_url(url: str) -> str:
    """티스토리 URL에서 포스팅 번호를 추출합니다. (예: .../4 -> '4')

    숫자가 없으면 path 전체를 식별자로 사용합니다.
    """
    try:
        from urllib.parse import urlparse
    except Exception:
        urlparse = None

    if urlparse is None:
        return (url or "").strip() or "index"

    p = urlparse(url)
    path = (p.path or "").strip("/")
    if not path:
        return "index"
    last = path.split("/")[-1]
    if last.isdigit():
        return last
    return path


def _get_last_processed_post_id(db_path: str = DB_PATH) -> int:
    """DB에 저장된 마지막 처리 티스토리 포스팅 번호(INT)를 반환합니다. 없으면 0."""
    _init_db(db_path)
    with sqlite3.connect(db_path) as con:
        row = con.execute("SELECT MAX(CAST(tistory_post_id AS INTEGER)) FROM post_map").fetchone()
    try:
        return int(row[0] or 0)
    except Exception:
        return 0


def _is_already_processed(post_id: int, db_path: str = DB_PATH) -> bool:
    """해당 post_id가 DB에 이미 저장(처리완료)되어 있으면 True."""
    _init_db(db_path)
    with sqlite3.connect(db_path) as con:
        row = con.execute(
            "SELECT 1 FROM post_map WHERE tistory_post_id = ? LIMIT 1;",
            (str(post_id),),
        ).fetchone()
    return row is not None


def _build_tistory_url_for_post_id(post_id: int) -> str:
    # 현재는 같은 blog 도메인에서 숫자 포스팅 번호 방식을 가정
    return f"https://billcorea.tistory.com/{post_id}"


def _fetch_next_valid_post(*, start_from: int, max_tries: int = 50, out_dir: str = r".\\out_tistory_tmp"):
    """start_from 다음 번호부터 티스토리 글을 순차 탐색하여 '정상 글' 1개를 반환

    정상 기준(최소): title/content_text 중 하나라도 있고, content_html이 비어있지 않음(스킨에 따라 최소 내용)
    """
    pid = start_from
    last_err = None
    for _ in range(max_tries):
        pid += 1

        # 이미 처리된 번호면 스킵
        try:
            if _is_already_processed(pid):
                print(f"[flow] skip already-processed post_id={pid}")
                continue
        except Exception as e:
            # DB 확인 실패는 치명적이진 않게 처리(그래도 진행)
            print(f"[flow] warn: processed-check failed post_id={pid} err={e}")

        url = _build_tistory_url_for_post_id(pid)
        try:
            post = readTistory(url=url, out=out_dir, no_images=False, save_raw_html=False)
            # 간단한 정상성 체크
            if post and (post.content_html and post.content_html.strip()) and (post.title and post.title.strip() and post.title != "(no title)"):
                return post

            # 비정상 글 -> 다음 번호로 계속
            last_err = f"invalid_content pid={pid} url={url}"
            print(f"[flow] skip invalid post_id={pid} url={url}")
        except Exception as e:
            last_err = f"fetch_failed pid={pid} url={url} err={e}"
            print(f"[flow] skip fetch-failed post_id={pid} url={url} err={e}")
            continue

    raise RuntimeError(f"다음 정상 포스팅을 찾지 못했습니다. start_from={start_from} last_err={last_err}")


def main():
    with sync_playwright() as p:
        # 시작 시 최근 저장 기록 출력
        recent = _get_recent_records(limit=5)
        if recent:
            print("[db] 최근 저장 기록(최신 10개):")
            for r in recent:
                print(f"  - tistory_post_id={r.get('tistory_post_id')} naver_written_at={r.get('naver_written_at')} url={r.get('tistory_url')}")
        else:
            print("[db] 저장 기록 없음")

        # 반복 처리 개수(기본 1). 환경변수 NAVER_MAX_POSTS 로 조절
        max_posts = 40

        out_dir = r".\\out_tistory_tmp"

        browser = p.chromium.launch(
            headless=False,
            args=["--disable-blink-features=AutomationControlled"]
        )
        context = browser.new_context()
        page = context.new_page()

        # 1️⃣ 네이버 로그인 페이지 이동 + 로딩 완료 자동 대기 (1회만 수행)
        resp = page.goto("https://nid.naver.com/nidlogin.login", wait_until="domcontentloaded")
        try:
            status = resp.status if resp else None
        except Exception:
            status = None
        print(f"[naver] login goto status={status} url={page.url}")

        # 자동 로그인(옵션): 환경변수로 주입
        # - NAVER_AUTO_LOGIN=1 이고, N_ACCOUNT_ID / N_ACCOUNT_PW 가 있으면 자동 입력 및 클릭
        auto_login = os.getenv("NAVER_AUTO_LOGIN", "").strip() == "1"
        n_id = os.getenv("N_ACCOUNT_ID", "").strip()
        n_pw = os.getenv("N_ACCOUNT_PW", "").strip()

        wait_for_naver_login_page_ready(page, timeout_ms=30000)
        if auto_login and n_id and n_pw:
            print("[naver] auto login: trying to fill id/pw and click login")
            perform_naver_login(page, user_id=n_id, user_pw=n_pw, timeout_ms=30000)
        else:
            print("👉 네이버 로그인 진행 중... (수동 입력/2FA 가능) 로그인 완료 감지까지 자동 대기합니다")

        ok = wait_for_naver_login_complete(page, timeout_ms=300000)
        if not ok:
            raise RuntimeError("네이버 로그인 완료를 시간 내에 감지하지 못했습니다. (캡차/2FA/보호조치 여부 확인)")

        print("[naver] login detected")

        for i in range(max_posts):
            # ✅ DB 기준 다음 포스팅 가져오기
            last_id = _get_last_processed_post_id()
            print(f"[flow] cycle={i+1}/{max_posts} last_processed_tistory_post_id={last_id}")

            # 매 사이클마다 out_dir 정리(이전 이미지 잔재 방지)
            cleared = _clear_out_dir_images(out_dir)
            print(f"[flow] cleared_out_dir_images={cleared}")

            post = _fetch_next_valid_post(start_from=last_id, max_tries=20, out_dir=out_dir)
            print(f"[flow] picked_next_post_id={_tistory_post_id_from_url(post.url)} title={post.title}")

            # 2️⃣ 섹션 홈으로 이동 -> '글쓰기' 클릭 -> 글쓰기 화면 진입(대기 포함)
            write_page = goto_blog_section_and_open_write(page, timeout_ms=45000)
            if write_page is not page:
                try:
                    page.close()
                except Exception:
                    pass
                page = write_page
            close_other_tabs(context, page)

            # 글쓰기 페이지는 iframe 로딩이 더 중요해서 networkidle은 보조로만
            try:
                page.wait_for_load_state("networkidle", timeout=15000)
            except Exception:
                pass
            time.sleep(2)

            # 3️⃣ iframe 탐색 (mainFrame 도 로딩 지연 가능하므로 재시도)
            main_frame = None
            for _mf_try in range(10):
                try:
                    main_frame = find_main_frame(page)
                    break
                except RuntimeError:
                    print(f"[find_main_frame] attempt {_mf_try+1}/10 – not found, waiting 2s…")
                    time.sleep(2)
            if main_frame is None:
                raise RuntimeError("mainFrame 찾기 실패 (재시도 모두 소진)")

            editor_frame = find_editor_frame(main_frame)

            content = post.content_html
            content = re.sub('inventory', '', content)
            content = re.sub('반응형', '', content)
            content = re.sub('System - START', '', content)
            content = re.sub('System - END', '', content)
            content = re.sub('PostListinCategory - START', '', content)
            content = re.sub('PostListinCategory - END', '', content)

            title = post.title
            tistory_post_id = _tistory_post_id_from_url(post.url)

            content += '''
            ***이 글은 Tistory(티스토리)에 게시 되었던 글들을 네이버블로그로 이전 작업중에 발행(게시) 되는 글 입니다.
            ***이 글을 작성하는 {0} 시점에는 다른 세상(?)이 되었을 수도 있습니다.  
            
            #블로그글이전 #티스토리 #네이버 #billcorea
            '''.format(datetime.now().strftime('%Y-%m-%d %H:%M'))

            # 4️⃣ 제목 + 본문 입력
            set_body(editor_frame, content, base_url=post.url, page=page, mode="auto")
            focus_title_strong(page, title)

            # 이미지 개수와 무관하게, 다음 단계(업로드/발행)를 막는 도움말/가이드 오버레이를 선제적으로 닫기
            try:
                close_help_dialog_if_present(page)
            except Exception as e:
                print(f"[help] pre-upload close failed: {e}")

            # 5️⃣ 이미지 일괄 업로드
            up = upload_images_in_batch(page, out_dir=out_dir)
            print(f"[upload] result={up}")

            # 업로드 직후 에디터가 리렌더링/포커스 이동을 하면서 상단 버튼이 잠깐 클릭 불가가 되는 경우가 있어 안정화 대기
            try:
                page.keyboard.press("Escape")
            except Exception:
                pass
            try:
                page.wait_for_timeout(30000)
            except Exception:
                time.sleep(13.0)

            # 6️⃣ 발행
            pub = publish_post(page, timeout_ms=90000)
            print(f"[publish] result={pub}")
            if not pub.get("ok"):
                raise RuntimeError(f"발행 실패: {pub}")

            # ✅ DB 저장: 티스토리 포스팅 번호 + 네이버 기록 시각(현재 시각)
            naver_written_at = datetime.now().strftime("%Y%m%d%H%M%S")
            _save_record(tistory_post_id=tistory_post_id, naver_written_at=naver_written_at, tistory_url=post.url)
            print(f"[db] saved: tistory_post_id={tistory_post_id} naver_written_at={naver_written_at}")

            # 다음 사이클로 넘어가기 전에 잠깐 안정화
            try:
                page.wait_for_timeout(12000)
            except Exception:
                pass

            # 다음 반복 전 보조 탭 정리
            close_other_tabs(context, page)

            print("✅ 반복 작업 완료 ... 5 초 기다리면 다음 작업 시작....")
            time.sleep(15.0)

        #input("👉 화면 확인 후 Enter 누르면 종료")

        browser.close()

if __name__ == "__main__":
    main()

 

 

p.s 네이버에는 코드 전체가 노출이 되지 않아 첨부로 올렸는 데, 티스토리는 코드 블럭에 전체 코드가 들어 가네요. ㅋㅋㅋ

 

https://blog.naver.com/billcoreatech/224313042726

 

블로그 이전 완료...

티스토리에 있는 글들을 이곳 네이버 블로그로 이전을 끝냈습니다. 무엇이 달라지게 될 지는 아직 모르겠지...

blog.naver.com

 

네이버 블로그 링크 입니다. 첨부 파일이 필요하신 분들에게... 

반응형

 

Python에서 5100개 키워드 포함 여부 빠르게 검사하기

대규모 로그 처리나 텍스트 분석을 하다 보면, 한 문장에 수천 개의 키워드 중 하나라도 포함되어 있는지 빠르게 확인해야 할 때가 있습니다. 단순히 re.search를 5100번 반복하는 방식은 성능이 매우 떨어지므로, 더 효율적인 방법을 소개합니다.

❌ 잘못된 접근: [...] 문자 클래스

정규식에서 [...]는 문자 클래스로 동작합니다.
예: [abc] → "a" 또는 "b" 또는 "c"라는 단일 문자 매치.
따라서 5100개의 키워드를 [...] 안에 넣는 것은 "5100개의 문자열 중 하나"가 아니라 "5100개의 문자 중 하나"를 찾는 것에 불과합니다.

✅ 올바른 접근 방법

1. Set 기반 검색


# 5100개 키워드 준비
keywords = ["error", "warning", "critical", "timeout", "failed", ...]
keywords_set = {k.lower() for k in keywords}  # 모두 소문자로 변환

sentence = "System reported CRITICAL failure at 12:00"

# 방법 1: 단어 단위 검색
words = set(sentence.lower().split())
if words & keywords_set:
    print("포함됨 (단어 단위)")

# 방법 2: 문장 전체에서 부분 문자열 검색
if any(k in sentence.lower() for k in keywords_set):
    print("포함됨 (부분 문자열)")
  

- 단어 단위 검색: 로그가 공백으로 구분된 경우 최적
- 부분 문자열 검색: 문장 내 임의 위치 검색 가능

2. Aho-Corasick 알고리즘


import ahocorasick

keywords = ["error", "warning", "critical", "timeout", "failed", ...]
keywords = [k.lower() for k in keywords]

A = ahocorasick.Automaton()
for idx, keyword in enumerate(keywords):
    A.add_word(keyword, (idx, keyword))
A.make_automaton()

sentence = "System reported CRITICAL failure"
for end_index, (idx, keyword) in A.iter(sentence.lower()):
    print("포함:", keyword)
    break  # 하나라도 찾으면 종료
  

- 대규모 키워드 검색에 가장 빠른 방법
- 대소문자 무시: 키워드와 문장을 모두 .lower() 처리

3. OR 정규식


import re

keywords = ["error", "warning", "critical", "timeout", "failed", ...]
pattern = re.compile("|".join(map(re.escape, keywords)), re.IGNORECASE)

sentence = "System reported CRITICAL failure"
if pattern.search(sentence):
    print("포함됨")
  

⚠️ 단점: 5100개 키워드라면 정규식이 너무 커져 성능 저하 가능.

📊 방법 비교

방법 속도 메모리 적합 상황
Set 검색 빠름 중간 단순 포함 여부
Aho-Corasick 매우 빠름 중간 대규모 키워드 검색
OR 정규식 중간 높음 키워드 수 적을 때

🎯 결론

- 5100개 키워드라면 [] 안에 넣는 건 잘못된 방식입니다.
- 실제로는 Set 검색 또는 Aho-Corasick을 쓰는 것이 최적입니다.
- 로그 분석, 보안 탐지, 대규모 텍스트 필터링에 특히 유용합니다.

반응형

티스토리에 있는 글을 자동으로 이전 하는 작업을 시작합니다.   (feat 블로그 글 이전 하기 ...)

 

스크립트 자동화를 통해서 티스토리에 게시 했던 글을 네이버 블로그로 이전 하는 작업을 시작 했습니다.

 

이제 완전 자동화가 가능 합니다. 다만, 네이버 블로그에 자동 글쓰기 탐지(?)가 있을까 싶어서, 한번에 6개의 글을 자동으로 이전 합니다.  

 

소스 코드를 보고 수정하실 수 있습니다.  네이버블로그에 새싹(?)이 자라기 시작 했습니다.

 

네이버에 방문객이 늘어나는중!

 

언제 될지 모르겠지만, 800여개의 글을 전부다 옮겨 보겠습니다.

 

from playwright.sync_api import sync_playwright
import time
import os

from naver_blog.tistory_scrape import readTistory

# --- HTML sanitize (Tistory -> Naver editor) ---
import re
from bs4 import BeautifulSoup
from urllib.parse import urljoin

import json
from pathlib import Path

import sqlite3
from datetime import datetime

# sqlite DB 경로(현재 스크립트와 같은 폴더에 생성)
DB_PATH = str(Path(__file__).with_name("tistory_to_naver.db"))

BLOG_ID = "billcoreatech"   # 본인 블로그 ID
TEST_TITLE = "자동화 테스트 제목"
TEST_BODY_HTML = """
<p>이 글은 Playwright 자동화 테스트입니다.</p>
<p><strong>본문 입력 정상 동작 확인용</strong></p>
<p>iframe + contenteditable 기반 입력 테스트</p>
"""

# --- Naver login helpers ---

def _wait_for_any_selector(root, selectors: list[str], *, timeout_ms: int = 15000) -> str | None:
    """여러 셀렉터 중 하나라도 나타나면 해당 셀렉터를 반환."""
    deadline = time.time() + (timeout_ms / 1000)
    last_err = None
    while time.time() < deadline:
        for sel in selectors:
            try:
                loc = root.locator(sel).first
                if loc.count() > 0 and loc.is_visible():
                    return sel
            except Exception as e:
                last_err = e
                continue
        time.sleep(0.2)
    return None


def wait_for_naver_login_page_ready(page, *, timeout_ms: int = 30000) -> None:
    """네이버 로그인 페이지가 '입력 가능한 상태'가 될 때까지 대기합니다."""
    # 로딩 상태(네트워크 idle은 로그인 페이지에서 흔들릴 수 있어 domcontentloaded 우선)
    try:
        page.wait_for_load_state("domcontentloaded", timeout=timeout_ms)
    except Exception:
        pass

    # 실제로 폼이 뜰 때까지(변경 대비 OR)
    sel = _wait_for_any_selector(
        page,
        [
            "input#id",
            "input[name='id']",
            "input[type='password']",
            "button[type='submit']",
        ],
        timeout_ms=timeout_ms,
    )
    if not sel:
        # 보호조치/캡차 등일 수도 있으니 디버그용 정보
        raise RuntimeError(f"네이버 로그인 폼 로딩 감지 실패(timeout={timeout_ms}ms). 현재 URL={page.url}")


def _has_naver_login_cookies(context) -> bool:
    try:
        cookies = context.cookies()
    except Exception:
        return False
    names = {c.get("name") for c in cookies if isinstance(c, dict)}
    # 통상 로그인 세션 쿠키(환경에 따라 다를 수 있어 OR로)
    return ("NID_AUT" in names) or ("NID_SES" in names)


def _looks_like_logged_in_dom(page) -> bool:
    """DOM에 '로그아웃' 흔적이 있는지로 로그인 완료를 보조 판정.

    - 네이버는 서비스/시점에 따라 상단 메뉴 구조가 달라질 수 있어 느슨하게 확인합니다.
    """
    selectors = [
        "a[href*='nidlogout']",
        "text=로그아웃",
        "a:has-text('로그아웃')",
    ]
    for sel in selectors:
        try:
            loc = page.locator(sel).first
            if loc.count() > 0 and loc.is_visible():
                return True
        except Exception:
            continue
    return False


def perform_naver_login(page, *, user_id: str, user_pw: str, timeout_ms: int = 30000) -> None:
    """네이버 로그인 페이지에서 아이디/비번 입력 후 로그인 버튼을 클릭합니다.

    주의:
    - 캡차/보호조치/2FA가 뜨면 이후 단계에서 감지 대기하다가 타임아웃될 수 있습니다.
    - 비밀번호 입력은 보안 정책/브라우저 설정에 따라 자동 입력이 막힐 수 있어, 여러 방식으로 시도합니다.
    """
    wait_for_naver_login_page_ready(page, timeout_ms=timeout_ms)

    # 네이버 로그인 입력 박스 셀렉터(변경 대비 OR)
    id_selectors = [
        "input#id",
        "input[name='id']",
        "#id",
    ]
    pw_selectors = [
        "input#pw",
        "input[name='pw']",
        "input[type='password']",
        "#pw",
    ]

    id_sel = _wait_for_any_selector(page, id_selectors, timeout_ms=timeout_ms)
    pw_sel = _wait_for_any_selector(page, pw_selectors, timeout_ms=timeout_ms)
    if not id_sel or not pw_sel:
        raise RuntimeError("로그인 입력창(id/pw)을 찾지 못했습니다. (보호조치/캡차 화면일 수 있음)")

    # 아이디
    page.locator(id_sel).first.click()
    page.keyboard.press("Control+A")
    page.keyboard.press("Backspace")
    page.keyboard.type(user_id, delay=25)

    # 비밀번호: fill -> type 순으로 시도(일부 환경에서 type이 더 잘 먹힘)
    pw_loc = page.locator(pw_sel).first
    pw_loc.click()
    try:
        pw_loc.fill("")
        pw_loc.fill(user_pw)
    except Exception:
        page.keyboard.press("Control+A")
        page.keyboard.press("Backspace")
        page.keyboard.type(user_pw, delay=25)

    # 로그인 버튼
    btn_selectors = [
        "button#log\.login",
        "#log\\.login",
        "button[type='submit']",
        "input[type='submit']",
        "text=로그인",
    ]
    btn_sel = _wait_for_any_selector(page, btn_selectors, timeout_ms=timeout_ms)
    if btn_sel:
        try:
            page.locator(btn_sel).first.click()
        except Exception:
            # 클릭이 막히면 Enter로 제출 시도
            page.keyboard.press("Enter")
    else:
        page.keyboard.press("Enter")


def goto_blog_section_and_open_write(page, *, timeout_ms: int = 30000):
    """로그인 후 섹션 홈으로 이동한 다음 '글쓰기' 버튼을 클릭해 글쓰기 모드로 진입.

    네이버는 글쓰기 진입이
    - 같은 탭 이동
    - 새 탭(팝업)
    - blog.naver.com/{id}?Redirect=Write
    형태로 바뀔 수 있어, 클릭 후 페이지 컨텍스트의 새 페이지도 감지합니다.

    반환: 글쓰기 화면으로 판단되는 Page 객체(대개 원래 page 또는 새 탭)
    """
    target_url = "https://section.blog.naver.com/BlogHome.naver?directoryNo=0&currentPage=1&groupId=0"

    # 1) 섹션 홈 이동
    page.goto(target_url, wait_until="domcontentloaded")
    try:
        page.wait_for_load_state("networkidle", timeout=timeout_ms)
    except Exception:
        pass

    # 2) '글쓰기' 버튼/링크 찾기
    write_selectors = [
        "a:has-text('글쓰기')",
        "button:has-text('글쓰기')",
        "text=글쓰기",
        "a[href*='Redirect=Write']",
        "a[href*='Write']",
    ]

    sel = _wait_for_any_selector(page, write_selectors, timeout_ms=timeout_ms)
    if not sel:
        raise RuntimeError(f"섹션 홈에서 '글쓰기' 버튼을 찾지 못했습니다. url={page.url}")

    # 3) 클릭 -> 새 탭이 뜰 수도 있어서 expect_page로 감싸서 처리
    ctx = page.context
    new_page = None
    try:
        with ctx.expect_page(timeout=5000) as pinfo:
            page.locator(sel).first.click()
        new_page = pinfo.value
    except Exception:
        # 새 탭이 안 뜨는 케이스면 현재 페이지에서 이동했을 가능성
        try:
            page.locator(sel).first.click()
        except Exception:
            # 클릭이 막히면 Enter
            page.keyboard.press("Enter")

    write_page = new_page or page

    # 4) 글쓰기 화면 로딩 대기(iframe/mainFrame 또는 Redirect=Write URL 등)
    deadline = time.time() + (timeout_ms / 1000)
    while time.time() < deadline:
        try:
            cur = write_page.url or ""
            if "Redirect=Write" in cur or ("write" in cur.lower() and "blog.naver.com" in cur):
                break
        except Exception:
            pass

        # mainFrame이 뜨면 거의 글쓰기 진입
        try:
            if write_page.frame(name="mainFrame"):
                break
        except Exception:
            pass

        time.sleep(0.3)

    # 추가로 mainFrame이 나타날 때까지 조금 더 기다림(네트워크/리다이렉트 변동 대비)
    try:
        write_page.wait_for_timeout(800)
    except Exception:
        pass

    return write_page


def wait_for_naver_login_complete(page, *, timeout_ms: int = 300000) -> bool:
    """사용자가 로그인(수동)을 완료할 때까지 자동 감지해서 대기합니다.

    감지 기준:
    - 쿠키(NID_AUT/NID_SES) 생성 또는
    - URL이 로그인 페이지를 벗어남

    반환: True(로그인 완료로 판단) / False(타임아웃)
    """
    deadline = time.time() + (timeout_ms / 1000)
    login_url_prefix = "https://nid.naver.com/nidlogin.login"

    while time.time() < deadline:
        # 1) 쿠키 기반
        try:
            if _has_naver_login_cookies(page.context):
                return True
        except Exception:
            pass

        # 2) URL 기반(리다이렉트/다른 페이지로 이동)
        try:
            cur = page.url or ""
            if (login_url_prefix not in cur) and ("nidlogin.login" not in cur):
                return True
        except Exception:
            pass

        # 3) DOM 기반(로그아웃 요소 등)
        try:
            if _looks_like_logged_in_dom(page):
                return True
        except Exception:
            pass

        time.sleep(0.5)

    return False


def find_main_frame(page):
    # 1순위: name 기준
    frame = page.frame(name="mainFrame")
    if frame:
        return frame

    # 2순위: URL 패턴
    for f in page.frames:
        if "write" in (f.url or "").lower():
            return f

    raise RuntimeError("mainFrame 찾기 실패")

def find_editor_frame(main_frame):
    # URL 기반
    for f in main_frame.child_frames:
        if "editor" in (f.url or "").lower():
            return f

    # contenteditable 기준 fallback
    for f in main_frame.child_frames:
        try:
            if f.locator("[contenteditable='true']").count() > 0:
                return f
        except:
            pass

    raise RuntimeError("editor iframe 찾기 실패")

def focus_title_strong(page, title: str):
    # 페이지 또는 프레임들에서 제목 요소를 찾아 포커싱/입력 시도
    page.wait_for_timeout(100)

    selectors = [
        "div.se-component.se-documentTitle span.se-placeholder",
        "div[data-a11y-title='제목'] span.se-placeholder",
        "span.se-placeholder:has-text('제목')",
        "span.__se-node",
        "p.se-text-paragraph",
        "div.se-module.se-title-text",
        "text=제목",
    ]

    def try_on(root):
        # root는 Page 또는 Frame
        for sel in selectors:
            try:
                locator = root.locator(sel)
                if locator.count() > 0:
                    try:
                        locator.first.click()
                        page.wait_for_timeout(120)
                        page.keyboard.type(title, delay=40)
                        return True
                    except Exception:
                        # 클릭 실패 시 다음 선택자 시도
                        pass
            except Exception:
                continue

        # evaluate 폴백
        try:
            result = root.evaluate("""
            (title) => {
                const candidateSelectors = [
                    'span.__se-node',
                    'div.se-component.se-documentTitle span.se-placeholder',
                    '[data-a11y-title="제목"] span.se-placeholder',
                    'p.se-text-paragraph',
                    'div.se-module.se-title-text'
                ];

                let el = null;
                for (const sel of candidateSelectors) {
                    const found = document.querySelector(sel);
                    if (found) { el = found; break; }
                }

                if (!el) {
                    el = Array.from(document.querySelectorAll('span.se-placeholder')).find(s => s.textContent && s.textContent.trim() === '제목');
                }

                if (!el) return { found: false, set: false };

                try { el.click(); } catch(e) {}

                let editable = null;
                if (el.closest) {
                    editable = el.closest('[contenteditable]') || (el.querySelector && el.querySelector('[contenteditable]'));
                }
                if (!editable) {
                    editable = el;
                }

                try {
                    if (editable.isContentEditable || (editable.getAttribute && editable.getAttribute('contenteditable') === 'true')) {
                        editable.focus && editable.focus();
                        // contentEditable이면 내부 노드 중 빈 __se-node가 있으면 채우기
                        // 아니면 innerText로 대체
                        const node = editable.querySelector && editable.querySelector('span.__se-node');
                        if (node && node.innerText.trim() === '') {
                            node.innerText = title;
                        } else {
                            editable.innerText = title;
                        }
                    } else {
                        editable.innerText = title;
                    }

                    const evInput = new Event('input', { bubbles: true });
                    const evChange = new Event('change', { bubbles: true });
                    editable.dispatchEvent && editable.dispatchEvent(evInput);
                    editable.dispatchEvent && editable.dispatchEvent(evChange);

                    return { found: true, set: true };
                } catch (e) {
                    return { found: true, set: false };
                }
            }
            """, title)

            if isinstance(result, dict):
                return result.get('set', False)
        except Exception:
            pass

        return False

    # 1) 현재 페이지에서 시도
    try:
        if try_on(page):
            return
    except Exception:
        pass

    # 2) 모든 프레임에서 시도 (중첩 포함)
    try:
        frames_to_check = list(page.frames)
        for fr in frames_to_check:
            try:
                if try_on(fr):
                    return
            except Exception:
                continue
    except Exception:
        pass

    # 최후 수단: 포커스가 된 상태로 가정하고 키보드로 입력
    page.wait_for_timeout(120)
    page.keyboard.type(title, delay=40)


def sanitize_for_naver(html: str, *, base_url: str | None = None, remove_images: bool = False) -> str:
    """네이버 스마트에디터(스마트에디터 ONE) 입력용으로 본문 HTML을 최대한 안전하게 정리합니다.

    목표
    - 줄바꿈 유지: 블록 단위를 <p>로 통일하고 빈 줄은 <p><br></p>
    - 이미지 유지: <img src="...">를 확정하고 불필요 속성 제거
    - 에디터가 잘라내는 태그 최소화: div/span 등은 풀고(unwrap) 필요한 태그만 남김

    주의
    - 네이버 쪽에서 외부 이미지 표시를 제한할 수 있습니다.
      이 경우엔 '외부 이미지' 정책 때문에 img가 사라지거나 로드 실패할 수 있어, 업로드 방식이 더 확실합니다.

    추가
    - 티스토리 codeblock(<pre data-ke-type="codeblock"><code>...</code></pre>)은
      네이버 에디터에서 줄바꿈이 깨질 수 있어, 코드블록만 별도 변환합니다.
      (코드 내용을 HTML escape 후 줄바꿈을 <br>로 강제)

    remove_images:
      - True: 본문 HTML 내의 <img> 태그를 모두 제거합니다. (이미지는 로컬 다운로드/업로드 플로우로만 처리)
    """

    soup = BeautifulSoup(html or "", "lxml")

    # --- Tistory codeblock normalize ---
    # <pre ... data-ke-type="codeblock"><code>...</code></pre>
    # 또는 data-ke-language가 있는 케이스를 대상으로, 네이버에서 줄바꿈이 유지되도록
    # 내부 텍스트를 escape 후 <br>로 변환한 "pseudo code block"으로 치환합니다.
    # (네이버가 외부 <pre>를 재가공하면서 \n을 공백으로 만들 수 있어 선제 대응)
    def _escape_code_text(s: str) -> str:
        # BeautifulSoup가 특수문자를 escape 해주긴 하지만, 여기서는 명시적으로 처리
        return (s or "").replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")

    def _preserve_indentation(s: str) -> str:
        """코드블록 내 들여쓰기/정렬을 최대한 보존하기 위한 치환.

        - 탭(\t): 4칸 공백으로 변환 후 nbsp 처리
        - 라인 선두/연속 공백: HTML에서 축약되지 않도록 &nbsp;로 보존

        주의: 전체 공백을 전부 nbsp로 바꾸면 복사/편집성이 떨어질 수 있어,
        '연속 공백(2개 이상)'과 '라인 선두'에만 적용합니다.
        """
        if not s:
            return ""

        s = s.replace("\t", "    ")
        lines = s.split("\n")
        out_lines: list[str] = []
        for line in lines:
            if not line:
                out_lines.append("")
                continue

            # 1) 선두 공백은 모두 nbsp로
            m = re.match(r"^( +)", line)
            if m:
                lead = m.group(1)
                rest = line[len(lead):]
                lead_nbsp = "&nbsp;" * len(lead)
            else:
                lead_nbsp = ""
                rest = line

            # 2) 중간의 연속 공백(2개 이상)은 첫 공백만 유지하고 나머지를 nbsp로
            #    예: 'a    b' -> 'a &nbsp;&nbsp;&nbsp;b' (총 4칸 유지)
            def _collapse_spaces(match: re.Match) -> str:
                n = len(match.group(0))
                return " " + ("&nbsp;" * (n - 1))

            rest = re.sub(r" {2,}", _collapse_spaces, rest)
            out_lines.append(lead_nbsp + rest)

        return "\n".join(out_lines)

    for pre in list(soup.find_all("pre")):
        try:
            ke_type = (pre.get("data-ke-type") or "").strip().lower()
            has_code_child = pre.find("code") is not None
            ke_lang = (pre.get("data-ke-language") or "").strip()

            # 티스토리 코드블록의 전형적인 패턴만 대상으로 함(일반 pre는 유지)
            if not (ke_type == "codeblock" or (has_code_child and ke_lang)):
                continue

            code = pre.find("code") or pre

            # code 내부에 <br>가 섞여 있을 수 있어 텍스트로 안전하게 추출
            raw_text = code.get_text()
            # get_text()는 <br>을 개행으로 치환하지 않을 수 있어 폴백 처리
            if "<br" in str(code).lower() and ("\n" not in (raw_text or "")):
                # <br>을 개행으로 보고 다시 추출
                try:
                    tmp = BeautifulSoup(str(code), "lxml")
                    for br in tmp.find_all("br"):
                        br.replace_with("\n")
                    raw_text = tmp.get_text()
                except Exception:
                    pass
            # 줄바꿈 정규화
            raw_text = (raw_text or "").replace("\r\n", "\n").replace("\r", "\n")

            escaped = _escape_code_text(raw_text)
            escaped = _preserve_indentation(escaped)
            # 줄바꿈을 <br>로 강제(마지막 줄이 비어있어도 보이도록)
            html_lines = escaped.split("\n")
            # 빈 코드블럭 방지
            if not html_lines:
                html_lines = [""]

            # 코드블럭을 일반 문단/인라인으로 흡수시키지 않도록 wrapper를 둠
            # - <pre> 자체는 네이버가 제거/변형할 수 있어 사용하지 않음
            # - 대신 p + code 조합으로, 줄바꿈은 <br>로 표현
            # white-space는 에디터가 style을 제거할 수도 있지만, 남아있으면 들여쓰기에 도움이 됨
            code_html = "<p><code style=\"white-space:pre-wrap; font-family:monospace;\">" + "<br>".join(html_lines) + "</code></p>"

            repl = BeautifulSoup(code_html, "lxml")
            new_p = repl.find("p")
            if new_p is not None:
                pre.replace_with(new_p)
        except Exception:
            # 코드블록 변환 실패는 전체 sanitize를 막지 않도록 무시
            continue

    # 1) 위험/불필요 태그 제거
    for tag in soup.find_all(["script", "style", "noscript", "iframe", "object", "embed", "form", "input", "button"]):
        tag.decompose()

    # (추가) RDF/CCL 같은 메타 블록 제거
    for tag in soup.find_all(["rdf:rdf", "rdf", "work", "license"]):
        try:
            tag.decompose()
        except Exception:
            pass

    # 2) 광고/관련글/태그/댓글로 자주 쓰이는 블록 제거 (있으면)
    for sel in [
        ".another_category",
        ".related_posts",
        ".postbtn",
        ".share",
        ".comment",
        "#comment",
    ]:
        for t in soup.select(sel):
            t.decompose()

    # (추가) 티스토리 광고/구독/CCL UI 제거
    for sel in [
        "[data-tistory-react-app]",
        "button.btn_subscription",
        "a.link_ccl",
        ".bundle_ccl",
    ]:
        for t in soup.select(sel):
            try:
                t.decompose()
            except Exception:
                pass

    # 3) div/span은 모두 풀기 (내용만 유지)
    for tag in list(soup.find_all(["div", "span"])):
        # 구독 버튼 등은 위에서 제거하지만, 혹시 남았으면 방어적으로 제거
        if tag.get("data-tistory-react-app"):
            tag.decompose()
            continue
        tag.unwrap()

    # 허용 태그 (최소)
    allowed_tags = {
        "p",
        "br",
        "strong",
        "b",
        "em",
        "i",
        "u",
        "s",
        "blockquote",
        "pre",
        "code",
        "ul",
        "ol",
        "li",
        "hr",
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6",
        "a",
        # 이미지 업로드를 별도로 하므로, 기본은 포함하되 remove_images=True면 제거
        "img",
        "table",
        "thead",
        "tbody",
        "tr",
        "th",
        "td",
    }

    def pick_img_url(tag) -> str | None:
        srcset = tag.get("srcset")
        if srcset:
            parts = [p.strip() for p in srcset.split(",") if p.strip()]
            if parts:
                u = parts[-1].split()[0].strip()
                if u:
                    return u
        for k in ["data-src", "data-original", "data-url", "data-lazy", "data-origin-src", "src"]:
            v = tag.get(k)
            if v and str(v).strip():
                return str(v).strip()
        return None

    def _is_allowed_url(u: str) -> bool:
        u = (u or "").strip().lower()
        return u.startswith("http://") or u.startswith("https://")

    # 4) 허용 태그만 남기고 나머지는 unwrap
    for tag in list(soup.find_all(True)):
        name = tag.name.lower()
        if name not in allowed_tags:
            tag.unwrap()
            continue

        # 이미지 제거 옵션
        if remove_images and name == "img":
            tag.decompose()
            continue

        # 속성 정리
        for attr_name in list(dict(tag.attrs).keys()):
            an = attr_name.lower()
            if an.startswith("on"):
                del tag.attrs[attr_name]
                continue

            if name == "a":
                if an not in {"href", "title", "target", "rel"}:
                    del tag.attrs[attr_name]
            elif name == "img":
                if an not in {"src", "alt"}:
                    del tag.attrs[attr_name]
            else:
                # 나머지는 속성 제거(에디터가 종종 자름)
                del tag.attrs[attr_name]

        # 링크 정리
        if name == "a":
            href = tag.get("href")
            if href and base_url:
                tag["href"] = urljoin(base_url, href)
            tag["rel"] = "noopener noreferrer"
            if "target" not in tag.attrs:
                tag["target"] = "_blank"

        # 이미지 src 확정
        if name == "img":
            url = pick_img_url(tag)
            if url:
                if base_url:
                    url = urljoin(base_url, url)
                # 네이버 에디터가 data:, blob: 등을 잘라내는 경우가 있어 http(s)만 유지
                if _is_allowed_url(url):
                    tag["src"] = url
                else:
                    tag.decompose()
                    continue
            else:
                tag.decompose()
                continue

            if not tag.get("alt"):
                tag["alt"] = ""

    # 5) 블록 단위 통일
    body = soup.body if soup.body else soup

    def _preserve_text_whitespace(text: str) -> str:
        """일반 텍스트에서도 개행/들여쓰기를 최대한 보존하기 위한 변환.

        - \r\n/\r -> \n
        - 선두 공백: &nbsp;로
        - 연속 공백(2개 이상): 첫 공백만 남기고 나머지 &nbsp;
        - 개행: <br>로 변환하기 위해 '\n'을 유지(나중에 split해서 Tag로 넣음)
        """
        text = (text or "").replace("\r\n", "\n").replace("\r", "\n")
        lines = text.split("\n")
        out_lines: list[str] = []
        for line in lines:
            if line == "":
                out_lines.append("")
                continue
            m = re.match(r"^( +)", line)
            if m:
                lead = m.group(1)
                rest = line[len(lead):]
                lead_nbsp = "&nbsp;" * len(lead)
            else:
                lead_nbsp = ""
                rest = line

            def _collapse_spaces(match: re.Match) -> str:
                n = len(match.group(0))
                return " " + ("&nbsp;" * (n - 1))

            rest = re.sub(r" {2,}", _collapse_spaces, rest)
            out_lines.append(lead_nbsp + rest)
        return "\n".join(out_lines)

    def wrap_text_nodes_with_p(root):
        for node in list(root.contents):
            # NavigableString 처리
            if getattr(node, "name", None) is None:
                txt = str(node)
                if txt.strip():
                    p = soup.new_tag("p")
                    preserved = _preserve_text_whitespace(txt.strip())
                    parts = preserved.split("\n")
                    for i, part in enumerate(parts):
                        if i > 0:
                            p.append(soup.new_tag("br"))
                        # part에는 &nbsp; 등이 들어갈 수 있어 string으로 넣지 않고 파싱해서 삽입
                        frag = BeautifulSoup(part, "lxml")
                        # lxml은 <html><body>... 구조를 만들 수 있어, 텍스트/태그만 꺼내 붙임
                        container = frag.body if frag.body else frag
                        for c in list(container.contents):
                            p.append(c)
                    node.replace_with(p)
                else:
                    node.extract()

    wrap_text_nodes_with_p(body)

    # (추가) p 내부에 순수 텍스트만 있고 \n 이 포함된 경우도 <br>로 치환
    for p in list(body.find_all("p")):
        try:
            # p 내에 자식 태그가 없고 텍스트에 개행이 있으면 분해
            if not p.find(True):
                txt = p.get_text()
                if "\n" in (txt or ""):
                    preserved = _preserve_text_whitespace(txt)
                    p.clear()
                    for i, part in enumerate(preserved.split("\n")):
                        if i > 0:
                            p.append(soup.new_tag("br"))
                        frag = BeautifulSoup(part, "lxml")
                        container = frag.body if frag.body else frag
                        for c in list(container.contents):
                            p.append(c)
        except Exception:
            continue

    # 6) 연속 <br> 또는 빈 영역을 <p><br></p>로 보정
    for p in list(body.find_all("p")):
        # p 안에 아무 것도 없거나 공백만 있으면 <br> 넣기
        if not p.get_text(strip=True) and not p.find(["br"]):
            p.clear()
            p.append(soup.new_tag("br"))

    # body 직계에 img 등이 있고 p가 없으면 img 앞뒤를 p로 구분(줄바꿈 효과)
    # -> 이미지 제거(remove_images)인 경우엔 굳이 이 로직을 태울 필요가 없음
    if not remove_images:
        new_children = []
        for child in list(body.contents):
            if getattr(child, "name", None) == "img":
                new_children.append(BeautifulSoup("<p><br></p>", "lxml").p)
                p = soup.new_tag("p")
                p.append(child.extract())
                new_children.append(p)
                new_children.append(BeautifulSoup("<p><br></p>", "lxml").p)
            else:
                new_children.append(child)

        body.clear()
        for c in new_children:
            body.append(c)

    cleaned = "".join(str(x) for x in body.contents)
    cleaned = re.sub(r"\n{3,}", "\n\n", cleaned)
    return cleaned.strip()


def _find_editable_in_frame(frame):
    """네이버 글쓰기(스마트에디터)에서 실제 본문 입력 노드를 최대한 찾아 반환합니다.

    반환: (Frame, css_selector) 또는 (None, None)

    메모:
    - 네이버 글쓰기 페이지는 같은 프레임 안에서도 contenteditable 후보가 여러 개일 수 있어
      '본문'에 가까운 셀렉터를 우선합니다.
    """
    # about:blank 같은 빈 프레임은 후보에서 제외
    try:
        if not frame.url or frame.url.startswith("about:"):
            return None, None
    except Exception:
        return None, None

    candidate_selectors = [
        # SmartEditor ONE 본문에서 자주 보이는 루트(우선순위 높음)
        "div.se2_inputarea[contenteditable='true']",
        "div.se-editable[contenteditable='true']",
        "div.se-component-content[contenteditable='true']",
        "div[role='textbox'][contenteditable='true']",
        # 마지막 폴백
        "[contenteditable='true']",
    ]

    # locator.count()가 프레임 로딩 타이밍에 따라 0이 나오는 경우가 있어 evaluate로도 확인
    for sel in candidate_selectors:
        try:
            # 1) locator 기반
            loc = frame.locator(sel)
            if loc.count() > 0:
                return frame, sel
        except Exception:
            pass

        try:
            # 2) evaluate 기반
            exists = frame.evaluate("""(sel) => document.querySelector(sel) !== null""", sel)
            if exists:
                return frame, sel
        except Exception:
            continue

    return None, None


def _find_best_editor_target_from_page(page):
    """page 전체 frames에서 본문 편집 대상(Frame+selector)을 찾습니다."""
    try:
        frames = list(page.frames)
    except Exception:
        frames = []

    for fr in frames:
        found_fr, found_sel = _find_editable_in_frame(fr)
        if found_fr:
            return found_fr, found_sel
    return None, None


def _find_best_editor_target(main_frame):
    """main_frame부터 하위 프레임까지 훑어서 본문 편집 대상(Frame+selector)을 찾습니다."""

    queue = [main_frame]
    visited = set()

    while queue:
        fr = queue.pop(0)
        if fr in visited:
            continue
        visited.add(fr)

        found_fr, found_sel = _find_editable_in_frame(fr)
        if found_fr:
            return found_fr, found_sel

        try:
            queue.extend(list(fr.child_frames))
        except Exception:
            pass

    return None, None


def set_body_text_mode(target_frame, selector: str, text: str):
    """가장 안정적인 방식: 텍스트를 줄 단위로 입력(Enter로 줄바꿈)."""

    # 줄바꿈 정규화
    lines = (text or "").replace("\r\n", "\n").replace("\r", "\n").split("\n")
    # 너무 긴 문서를 한 번에 넣지 않도록 적당히 처리

    # 클릭/포커스는 JS에서, 실제 입력은 playwright keyboard로
    target_frame.evaluate(
        """
        (selector) => {
            const nodes = Array.from(document.querySelectorAll(selector)).filter(el => el && el.isConnected);
            if (!nodes.length) throw new Error('no editor for text mode');
            const scored = nodes.map(el => {
                const r = el.getBoundingClientRect ? el.getBoundingClientRect() : { width: 0, height: 0 };
                const area = (r.width || 0) * (r.height || 0);
                return { el, area };
            }).sort((a,b) => b.area - a.area);
            const editor = scored[0].el;
            editor.focus();
            try { editor.innerHTML=''; } catch(e) {}
        }
        """,
        selector,
    )

    # 실제 키 입력
    for i, line in enumerate(lines):
        if line:
            target_frame.page.keyboard.type(line, delay=10)
        # 줄바꿈
        if i < len(lines) - 1:
            target_frame.page.keyboard.press("Enter")


# 기존 set_body를 mode 지원으로 확장

def set_body(editor_frame, html, *, base_url: str | None = None, page=None, mode: str = "auto"):
    """본문 입력.

    mode:
      - auto: paste -> insertHTML -> range -> text 폴백
      - paste: paste만 시도(실패 시 auto 폴백)
      - insertHTML: insertHTML 우선(실패 시 range -> text)
      - range: range 우선(실패 시 text)
      - text: 텍스트 키입력(줄바꿈 Enter)
    """

    # 이미지 업로드는 별도 플로우로 처리하므로 본문에서는 <img>를 제거
    html = sanitize_for_naver(html, base_url=base_url, remove_images=True)

    # 1) editor_frame(기존 로직)에서 탐색
    target_frame, target_selector = _find_best_editor_target(editor_frame)

    # 2) 실패하면 page 전체에서 탐색
    if not target_frame and page is not None:
        target_frame, target_selector = _find_best_editor_target_from_page(page)

    if not target_frame:
        raise RuntimeError(
            f"본문 편집 영역을 찾지 못했습니다. editor_frame_url={getattr(editor_frame, 'url', None)}"
        )

    print(f"[set_body] target_frame_url={target_frame.url} selector={target_selector} mode={mode}")

    try:
        target_frame.wait_for_load_state("domcontentloaded", timeout=5000)
    except Exception:
        pass

    if mode == "text":
        _soup = BeautifulSoup(html, "lxml")
        txt = "\n".join(_soup.stripped_strings)
        set_body_text_mode(target_frame, target_selector, txt)
        return

    # JS 내부에서 어떤 method를 시도할지 결정
    js_mode = mode
    if js_mode not in {"auto", "paste", "insertHTML", "range"}:
        js_mode = "auto"

    result = target_frame.evaluate(
        """
        ({ html, selector, mode }) => {
            const nodes = Array.from(document.querySelectorAll(selector)).filter(el => el && el.isConnected);
            if (!nodes.length) {
                return { ok: false, method: 'none', reason: 'no_candidates', htmlLen: 0, textLen: 0 };
            }

            // 가장 화면에 보이는 큰 영역 우선
            const scored = nodes.map(el => {
                const r = el.getBoundingClientRect ? el.getBoundingClientRect() : { width: 0, height: 0 };
                const area = Math.max(0, r.width) * Math.max(0, r.height);
                const style = window.getComputedStyle ? window.getComputedStyle(el) : null;
                const visible = style ? (style.visibility !== 'hidden' && style.display !== 'none') : true;
                return { el, area, visible };
            }).sort((a,b) => {
                const as = (a.visible ? 1e12 : 0) + a.area;
                const bs = (b.visible ? 1e12 : 0) + b.area;
                return bs - as;
            });

            const editor = scored[0].el;
            editor.scrollIntoView && editor.scrollIntoView({ block: 'center' });
            editor.focus && editor.focus();

            const beforeTextLen = (editor.innerText || '').trim().length;
            const beforeHtmlLen = (editor.innerHTML || '').length;

            const measure = () => {
                const textLen = (editor.innerText || '').trim().length;
                const htmlLen = (editor.innerHTML || '').length;
                const changed = (textLen !== beforeTextLen) || (htmlLen !== beforeHtmlLen);
                const enough = (textLen >= 20) || (htmlLen >= 50);
                return { changed, enough, textLen, htmlLen };
            };

            // 일부 에디터는 이벤트 처리 후 비동기로 DOM을 갱신하므로, 0ms 지연 후 재측정을 지원
            const measureSoon = () => new Promise(resolve => {
                setTimeout(() => resolve(measure()), 0);
            });

            const tryPaste = async () => {
                // 1) ClipboardEvent + DataTransfer
                try {
                    const dt = new DataTransfer();
                    dt.setData('text/html', html);
                    const tmp = document.createElement('div');
                    tmp.innerHTML = html;
                    const text = (tmp.innerText || tmp.textContent || '').trim();
                    dt.setData('text/plain', text);

                    try {
                        editor.dispatchEvent(new InputEvent('beforeinput', {
                            bubbles: true,
                            cancelable: true,
                            inputType: 'insertFromPaste',
                            dataTransfer: dt,
                        }));
                    } catch(e) {}

                    try {
                        const pasteEvt = new ClipboardEvent('paste', {
                            bubbles: true,
                            cancelable: true,
                            clipboardData: dt,
                        });
                        editor.dispatchEvent(pasteEvt);
                    } catch(e) {
                        // ClipboardEvent 생성이 막히면 다음 경로로
                        throw e;
                    }

                    let m = measure();
                    if (m.enough) return true;
                    m = await measureSoon();
                    return m.enough;
                } catch(e) {
                    // 2) navigator.clipboard를 사용할 수 있으면 시도 (권한/보안 정책에 따라 실패 가능)
                    try {
                        const tmp = document.createElement('div');
                        tmp.innerHTML = html;
                        const text = (tmp.innerText || tmp.textContent || '').trim();

                        if (navigator.clipboard && navigator.clipboard.write) {
                            const item = new ClipboardItem({
                                'text/plain': new Blob([text], { type: 'text/plain' }),
                                'text/html': new Blob([html], { type: 'text/html' }),
                            });
                            await navigator.clipboard.write([item]);

                            // 일부 환경에서 execCommand('paste')가 동작할 수 있음
                            try { document.execCommand && document.execCommand('paste'); } catch(e2) {}

                            let m = measure();
                            if (m.enough) return true;
                            m = await measureSoon();
                            return m.enough;
                        }
                    } catch(e3) {
                        // ignore
                    }

                    return false;
                }
            };

            const tryInsertHTML = () => {
                try {
                    try { editor.innerHTML = ''; } catch(e) {}
                    return !!(document.execCommand && document.execCommand('insertHTML', false, html));
                } catch(e) {
                    return false;
                }
            };

            const tryRange = () => {
                try {
                    const range = document.createRange();
                    range.selectNodeContents(editor);
                    range.collapse(false);
                    const sel = window.getSelection();
                    sel.removeAllRanges();
                    sel.addRange(range);
                    const tpl = document.createElement('template');
                    tpl.innerHTML = html;
                    range.insertNode(tpl.content);
                    return true;
                } catch(e) {
                    return false;
                }
            };

            // async 체인
            return (async () => {
                let ok = false;
                let method = 'none';

                const chainAuto = ['paste', 'insertHTML', 'range'];
                const chain = (mode === 'paste') ? ['paste', ...chainAuto.filter(x=>x!=='paste')]
                            : (mode === 'insertHTML') ? ['insertHTML', 'range']
                            : (mode === 'range') ? ['range']
                            : chainAuto;

                for (const m of chain) {
                    if (m === 'paste') {
                        if (await tryPaste()) { ok = true; method = 'paste'; break; }
                    } else if (m === 'insertHTML') {
                        if (tryInsertHTML()) {
                            let res = measure();
                            if (!res.enough) res = await measureSoon();
                            ok = res.enough || res.changed;
                            method = 'insertHTML';
                            if (ok) break;
                        }
                    } else if (m === 'range') {
                        if (tryRange()) {
                            let res = measure();
                            if (!res.enough) res = await measureSoon();
                            ok = res.enough || res.changed;
                            method = 'range';
                            if (ok) break;
                        }
                    }
                }

                editor.dispatchEvent(new Event('input', { bubbles: true }));
                editor.dispatchEvent(new Event('change', { bubbles: true }));

                let final = measure();
                if (!final.enough) final = await measureSoon();

                return {
                    ok,
                    method,
                    reason: ok ? 'inserted' : 'failed',
                    htmlLen: final.htmlLen,
                    textLen: final.textLen,
                    picked: { area: scored[0].area, visible: scored[0].visible },
                    before: { textLen: beforeTextLen, htmlLen: beforeHtmlLen },
                };
            })();
        }
        """,
        {"html": html, "selector": target_selector, "mode": js_mode},
    )

    if isinstance(result, dict):
        print(
            f"[set_body] ok={result.get('ok')} method={result.get('method')} htmlLen={result.get('htmlLen')} textLen={result.get('textLen')} "
            f"reason={result.get('reason')} before={result.get('before')} picked={result.get('picked')}"
        )

    # 최후 폴백: JS가 실패로 판단하면 텍스트 모드
    if not isinstance(result, dict) or not result.get('ok'):
        print("[set_body] JS 삽입 실패 -> 텍스트 모드 폴백")
        _soup = BeautifulSoup(html, "lxml")
        txt = "\n".join(_soup.stripped_strings)
        set_body_text_mode(target_frame, target_selector, txt)


def _open_image_upload_ui(page) -> bool:
    """네이버 글쓰기에서 '사진/이미지' 업로드 UI를 열어 file input이 나타나게 시도합니다."""

    button_selectors = [
        "button:has-text('사진')",
        "button:has-text('이미지')",
        "button:has-text('포토')",
        "button:has-text('첨부')",
        "button[aria-label*='사진']",
        "button[aria-label*='이미지']",
        "a:has-text('사진')",
        "a:has-text('이미지')",
        "span:has-text('사진')",
        "span:has-text('이미지')",
    ]

    for fr in list(page.frames):
        for sel in button_selectors:
            try:
                loc = fr.locator(sel)
                if loc.count() == 0:
                    continue
                loc.first.click(timeout=800)
                page.wait_for_timeout(300)
                return True
            except Exception:
                continue

    return False


def _find_file_input_for_images(page):
    """page/frames에서 이미지 업로드용 file input을 찾아 (frame, locator) 반환."""
    candidate_selectors = [
        "input[type='file'][accept*='image']",
        "input[type='file']",
    ]

    for fr in list(page.frames):
        for sel in candidate_selectors:
            try:
                loc = fr.locator(sel)
                if loc.count() > 0:
                    return fr, loc.first
            except Exception:
                continue
    return None, None


def _try_upload_via_filechooser(page, paths: list[str], *, timeout_ms: int = 15000) -> bool:
    """클릭 시 OS 파일 선택창(file chooser)이 뜨는 흐름을 Playwright로 처리.

    네이버 에디터는 어떤 경우엔 input[type=file]가 노출되지 않고,
    '사진/이미지' 버튼 클릭 시 filechooser 이벤트가 발생합니다.
    이 경우 expect_file_chooser + set_files 로 업로드를 진행합니다.

    반환: filechooser로 업로드를 시도했으면 True, 이벤트가 안 떠서 못했으면 False
    """
    try:
        # 업로드 버튼을 다시 한번 열어주며(성공/실패 상관없이) filechooser를 유도
        with page.expect_file_chooser(timeout=timeout_ms) as fc_info:
            _open_image_upload_ui(page)
        chooser = fc_info.value
        chooser.set_files(paths)
        return True
    except Exception:
        return False


def _try_upload_via_windows_dialog(paths: list[str], *, timeout_ms: int = 20000) -> bool:
    """Windows '열기' 파일 선택 대화상자가 떠 있는 경우를 pywinauto로 제어.

    전제:
    - Chromium/Playwright가 OS 파일 대화상자를 띄운 상태에서 이 함수가 호출되어야 합니다.

    주의:
    - 환경/언어(한글/영문 Windows)에 따라 컨트롤 이름이 다를 수 있어
      여러 후보를 순차 시도합니다.
    """
    try:
        from pywinauto import Application  # type: ignore
    except Exception:
        return False

    if not paths:
        return False

    # 여러 파일은 줄바꿈으로 전달(Windows 공통 동작)
    file_text = "\n".join(paths)
    first_parent = None
    try:
        first_parent = str(Path(paths[0]).parent)
    except Exception:
        first_parent = None

    deadline = time.time() + (timeout_ms / 1000)
    last_err = None
    while time.time() < deadline:
        try:
            # connect가 실패하는 경우가 있어(권한/포커스/멀티창) Desktop 탐색도 시도
            try:
                app = Application(backend="uia").connect(title_re=r"^(열기|Open)$")
                dlg = app.window(title_re=r"^(열기|Open)$")
            except Exception:
                app = Application(backend="uia")
                dlg = app.window(title_re=r"^(열기|Open)$")

            dlg.wait("visible", timeout=2)

            # 파일명 입력 박스 후보
            edit = None
            for c in [
                lambda: dlg.child_window(auto_id="1148", control_type="Edit"),  # common file name box
                lambda: dlg.child_window(title_re=r"파일 이름|File name", control_type="Edit"),
                lambda: dlg.child_window(control_type="Edit"),
            ]:
                try:
                    e = c()
                    if e.exists():
                        edit = e
                        break
                except Exception:
                    continue
            if edit is None:
                return False

            # 1) 가장 안정적인 방식: 파일명 칸에 '전체 경로'들을 줄바꿈으로 입력
            #    (폴더 탐색/클릭 없이도 다중 선택 가능)
            try:
                edit.set_edit_text("")
                edit.set_edit_text(file_text)
            except Exception:
                # 2) 실패하면: 먼저 폴더 경로를 파일명에 넣고 Enter로 이동한 뒤,
                #    파일명만(여러 개면 줄바꿈) 입력
                if first_parent:
                    try:
                        edit.set_edit_text("")
                        edit.set_edit_text(first_parent)
                        dlg.type_keys("{ENTER}")
                        time.sleep(0.4)

                        names = []
                        for p in paths:
                            try:
                                pp = Path(p)
                                names.append(pp.name)
                            except Exception:
                                continue
                        if names:
                            edit.set_edit_text("")
                            edit.set_edit_text("\n".join(names))
                    except Exception:
                        pass

            # 열기 버튼 후보
            btn = None
            for c in [
                lambda: dlg.child_window(title_re=r"열기|Open", control_type="Button"),
                lambda: dlg.child_window(auto_id="1", control_type="Button"),
            ]:
                try:
                    b = c()
                    if b.exists():
                        btn = b
                        break
                except Exception:
                    continue
            if btn is None:
                # Enter로 대체 시도
                try:
                    dlg.type_keys("{ENTER}")
                    return True
                except Exception:
                    return False

            btn.click_input()
            return True
        except Exception as e:
            last_err = e
            time.sleep(0.3)

    return False


def _wait_for_image_upload_settled(page, *, timeout_ms: int = 120000) -> dict:
    """이미지 파일 set_input_files 이후 업로드/삽입이 끝나고 팝업이 정리될 때까지 대기.

    네이버 에디터는 시점에 따라
    - 파일 선택 즉시 본문에 삽입
    - 업로드 팝업/레이어에서 '확인/완료/적용'을 눌러야 삽입
    - 업로드 진행률이 끝날 때까지 대기 필요
    가 섞여서 나타날 수 있어, 여러 신호를 느슨하게 조합합니다.

    추가: 대기 중 배열 선택 UI(se-image-type-label)가 뜨면 자동 처리합니다.
    """
    deadline = time.time() + (timeout_ms / 1000)

    # 클릭 가능한 '완료/확인' 계열 버튼 후보(팝업/레이어)
    confirm_selectors = [
        "button:has-text('완료')",
        "button:has-text('확인')",
        "button:has-text('적용')",
        "button:has-text('등록')",
        "button:has-text('넣기')",
        "button:has-text('삽입')",
        "button:has-text('닫기')",
        "text=완료",
        "text=확인",
    ]

    # 업로드 진행 중일 때 보이는 텍스트/요소 후보(있으면 사라질 때까지 기다리는 용도)
    busy_text_selectors = [
        "text=업로드",
        "text=Uploading",
        "text=전송",
        "text=진행",
    ]

    # 에디터 본문에서 업로드된 이미지를 감지하기 위한 셀렉터
    # (단순 img 태그가 아니라, 네이버 에디터의 이미지 컴포넌트로 한정)
    uploaded_img_selectors = [
        ".se-component.se-image img",
        ".se-image-resource img",
        "img[src*='postfiles']",
        "img[src*='blogfiles']",
        "img[src*='pstatic']",
        "img[data-src]",
    ]

    # 시작 시점의 img 개수를 기록(기존 이미지와 새 이미지를 구분)
    initial_img_count = 0
    try:
        for fr in list(page.frames):
            try:
                initial_img_count += fr.locator("img").count()
            except Exception:
                pass
    except Exception:
        pass

    last_click = 0.0
    layout_handled = False

    while time.time() < deadline:
        # 0) 배열 선택 UI가 대기 중에 나타났으면 처리 (안전망)
        if not layout_handled:
            try:
                roots = [page] + list(page.frames)
                for root in roots:
                    try:
                        labels = root.locator(".se-image-type-label")
                        if labels.count() >= 1 and labels.nth(0).is_visible():
                            print("[upload_settle] layout choice UI detected during settle wait → handling")
                            ch = _handle_multi_image_layout_choice(page, prefer="개별", timeout_ms=15000)
                            print(f"[upload_settle] layout_choice={ch}")
                            layout_handled = True
                            break
                    except Exception:
                        continue
            except Exception:
                pass

        # 1) 본문에 이미지가 들어갔는지(iframe 포함) 확인
        #    — 네이버 에디터 이미지 컴포넌트 셀렉터를 우선 체크
        try:
            for fr in list(page.frames):
                for sel in uploaded_img_selectors:
                    try:
                        if fr.locator(sel).count() > 0:
                            return {"ok": True, "reason": "img_tag_detected"}
                    except Exception:
                        continue
        except Exception:
            pass

        # 1-b) 구체 셀렉터로 못 잡으면, img 총 개수가 늘었는지로 판단
        try:
            current_img_count = 0
            for fr in list(page.frames):
                try:
                    current_img_count += fr.locator("img").count()
                except Exception:
                    pass
            if current_img_count > initial_img_count:
                return {"ok": True, "reason": "img_tag_detected"}
        except Exception:
            pass

        # 2) 가능한 '완료/확인' 버튼이 있으면 한 번씩 눌러보기(너무 자주 누르지 않게 throttle)
        if time.time() - last_click > 1.2:
            for sel in confirm_selectors:
                try:
                    loc = page.locator(sel).first
                    if loc.count() > 0 and loc.is_visible() and loc.is_enabled():
                        loc.click(timeout=800)
                        last_click = time.time()
                        page.wait_for_timeout(400)
                        break
                except Exception:
                    continue

        # 3) 업로드가 돈다면(텍스트가 보인다면) 잠깐 기다리기
        busy_seen = False
        for sel in busy_text_selectors:
            try:
                loc = page.locator(sel).first
                if loc.count() > 0 and loc.is_visible():
                    busy_seen = True
                    break
            except Exception:
                continue
        if busy_seen:
            time.sleep(0.5)
            continue

        # 4) 아무 신호가 없으면 짧게 폴링
        time.sleep(0.3)

    return {"ok": False, "reason": "upload_settle_timeout"}


def _handle_multi_image_layout_choice(page, *, prefer: str = "개별사진", timeout_ms: int = 15000) -> dict:
    """이미지 2장 이상 업로드 시 나타나는 '배열 방식' 선택(UI가 뜨면 클릭).

    네이버 에디터는 다중 이미지 업로드 후
    - 개별
    - 콜라보(콜라주)
    - 슬라이드/모음
    같은 선택 화면이 뜨는 경우가 있어, 자동으로 기본값(개별)을 선택하고 진행합니다.

    반환: {ok:bool, reason:str}
    """
    deadline = time.time() + (timeout_ms / 1000)

    # 텍스트 기반으로 '배열/레이아웃/콜라보' 화면 감지
    trigger_texts = [
        "배열",
        "레이아웃",
        "콜라보",
        "콜라주",
        "슬라이드",
        "개별사진",
        "개별",
    ]

    # 선택 후보(우선 prefer)
    option_selectors = [
        f"button:has-text('{prefer}')",
        f"label:has-text('{prefer}')",
        f"span:has-text('{prefer}')",
        # fallback: '개별사진' -> '개별'
        "button:has-text('개별사진')",
        "label:has-text('개별사진')",
        "span:has-text('개별사진')",
        "button:has-text('개별')",
        "label:has-text('개별')",
        "span:has-text('개별')",
    ]

    # 다음/확인/적용/완료
    confirm_selectors = [
        "button:has-text('확인')",
        "button:has-text('완료')",
        "button:has-text('적용')",
        "button:has-text('등록')",
        "button:has-text('넣기')",
        "button:has-text('삽입')",
        "button:has-text('다음')",
    ]

    def _text_seen() -> bool:
        """page와 모든 iframe에서 배열 선택 텍스트가 보이는지 확인."""
        roots = [page] + list(page.frames)
        for root in roots:
            for t in trigger_texts:
                try:
                    loc = root.get_by_text(t).first
                    if loc.count() > 0 and loc.is_visible():
                        return True
                except Exception:
                    continue
        return False

    def _label_seen_in_any_root() -> bool:
        """page와 모든 iframe에서 .se-image-type-label 요소가 보이는지 확인."""
        roots = [page] + list(page.frames)
        for root in roots:
            try:
                labels = root.locator(".se-image-type-label")
                if labels.count() >= 1:
                    if labels.nth(0).is_visible():
                        return True
            except Exception:
                continue
        return False

    # --- 배열 UI가 뜰 때까지 대기(즉시 안 뜨는 경우: 업로드 서버 처리 시간) ---
    # 최대 timeout_ms 의 절반을 대기에 사용하고, 나머지를 클릭 시도에 사용
    wait_deadline = time.time() + min(timeout_ms / 1000 * 0.6, 12.0)
    appeared = _text_seen() or _label_seen_in_any_root()
    if not appeared:
        print("[layout] waiting for layout choice UI to appear...")
        while time.time() < wait_deadline:
            if _text_seen() or _label_seen_in_any_root():
                appeared = True
                print("[layout] layout choice UI appeared")
                break
            time.sleep(0.5)

    if not appeared:
        print("[layout] layout choice UI not appeared within wait period")
        return {"ok": True, "reason": "no_layout_choice_ui"}

    # --- 배열 UI가 보이면 클릭 시도 루프 ---
    attempt = 0
    while time.time() < deadline:
        attempt += 1
        roots = [page] + list(page.frames)

        # 0) 가장 확실한 케이스: se-image-type-label 클릭 (page + 모든 frame)
        label_clicked = False
        for root in roots:
            try:
                labels = root.locator(".se-image-type-label")
                cnt = labels.count()
                if cnt < 1:
                    continue
                first = labels.nth(0)
                if not first.is_visible():
                    continue

                print(f"[layout] attempt={attempt} found {cnt} .se-image-type-label in {getattr(root, 'url', 'page')[:80]}")

                # 클릭 시도 (3단계 폴백)
                click_ok = False
                try:
                    first.click(timeout=2000)
                    click_ok = True
                except Exception:
                    try:
                        first.click(timeout=2000, force=True)
                        click_ok = True
                    except Exception:
                        try:
                            bb = first.bounding_box()
                            if bb:
                                # page 레벨 mouse 사용(frame mouse는 좌표 오프셋 문제 가능)
                                page.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2)
                                click_ok = True
                        except Exception:
                            pass

                if not click_ok:
                    # JS 강제 클릭 폴백
                    try:
                        js_ok = root.evaluate("""() => {
                            const labels = document.querySelectorAll('.se-image-type-label');
                            if (labels.length < 1) return false;
                            const el = labels[0];
                            el.scrollIntoView({block:'center'});
                            const opts = {bubbles:true, cancelable:true, composed:true};
                            el.dispatchEvent(new PointerEvent('pointerdown', opts));
                            el.dispatchEvent(new MouseEvent('mousedown', opts));
                            el.dispatchEvent(new MouseEvent('mouseup', opts));
                            el.dispatchEvent(new MouseEvent('click', opts));
                            return true;
                        }""")
                        if js_ok:
                            click_ok = True
                    except Exception:
                        pass

                if click_ok:
                    print(f"[layout] se-image-type-label clicked OK")
                    label_clicked = True
                    try:
                        page.wait_for_timeout(800)
                    except Exception:
                        time.sleep(0.8)
                    break
                else:
                    print(f"[layout] se-image-type-label click FAILED (all methods)")
            except Exception:
                continue

        # 1) 옵션 선택 (page + 모든 frame)
        option_clicked = False
        for root in roots:
            for sel in option_selectors:
                try:
                    loc = root.locator(sel).first
                    if loc.count() > 0 and loc.is_visible() and loc.is_enabled():
                        try:
                            loc.click(timeout=1200)
                        except Exception:
                            try:
                                loc.click(timeout=1200, force=True)
                            except Exception:
                                bb = loc.bounding_box()
                                if bb:
                                    page.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2)
                        try:
                            page.wait_for_timeout(400)
                        except Exception:
                            time.sleep(0.4)
                        option_clicked = True
                        print(f"[layout] option '{sel}' clicked in root={getattr(root, 'url', 'page')[:80]}")
                        break
                except Exception:
                    continue
            if option_clicked:
                break

        # label이나 option을 클릭한 뒤 UI 안정화 대기
        if label_clicked or option_clicked:
            try:
                page.wait_for_timeout(500)
            except Exception:
                time.sleep(0.5)

        # 2) 확인/적용/완료 계열 누르기
        if _robust_click_in_page_or_frames(page, confirm_selectors, timeout_ms=2000):
            print("[layout] confirm button clicked → layout_choice_confirmed")
            return {"ok": True, "reason": "layout_choice_confirmed"}

        # 3) UI가 사라졌으면 끝 (label도, 텍스트도 안 보이면)
        if not _text_seen() and not _label_seen_in_any_root():
            print("[layout] layout UI disappeared → done")
            return {"ok": True, "reason": "layout_choice_disappeared"}

        time.sleep(0.4)

    print(f"[layout] timeout after {attempt} attempts")
    return {"ok": False, "reason": "layout_choice_timeout"}


def _collect_downloaded_image_paths(out_dir: str) -> list[str]:
    """readTistory()가 저장한 images.json을 읽어 실제 존재하는 다운로드 이미지 경로를 수집."""
    d = Path(out_dir)
    img_json = d / "images.json"
    if not img_json.exists():
        return []

    try:
        data = json.loads(img_json.read_text(encoding="utf-8"))
    except Exception:
        return []

    paths: list[str] = []
    for item in data:
        if not isinstance(item, dict):
            continue
        p = item.get("path")
        if not p:
            continue
        pp = Path(p)
        if pp.exists():
            paths.append(str(pp))
    return paths


def _clear_out_dir_images(out_dir: str) -> dict:
    """이전 실행에서 내려받은 이미지/메타 파일을 삭제합니다.

    - images.json 삭제
    - out_dir 하위의 일반적인 이미지 확장자 파일 삭제

    목적: 이번 실행에서 다운로드된 이미지 목록과 파일만 업로드 되도록 정리
    """
    d = Path(out_dir)
    if not d.exists():
        return {"ok": True, "deleted": 0, "reason": "dir_not_exists"}

    deleted = 0
    # images.json
    try:
        j = d / "images.json"
        if j.exists():
            j.unlink()
            deleted += 1
    except Exception:
        pass

    exts = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"}
    for p in d.glob("**/*"):
        try:
            if p.is_file() and p.suffix.lower() in exts:
                p.unlink()
                deleted += 1
        except Exception:
            continue

    return {"ok": True, "deleted": deleted}


def _html_has_img(html: str) -> bool:
    try:
        soup = BeautifulSoup(html or "", "lxml")
        return soup.find("img") is not None
    except Exception:
        return "<img" in (html or "").lower()


def upload_images_in_batch(page, *, out_dir: str) -> dict:
    """다운로드된 이미지를 네이버 글쓰기에서 일괄 업로드합니다."""
    paths = _collect_downloaded_image_paths(out_dir)
    print(f"[upload] local images: {len(paths)}")
    if not paths:
        return {"ok": True, "reason": "no_local_images", "count": 0}

    # 0) 먼저 filechooser 이벤트로 끝낼 수 있는지 시도(일부 UI에서 input[type=file]가 안 잡힘)
    if _try_upload_via_filechooser(page, paths):
        print("[upload] used filechooser")
        # 다중 이미지일 때 배열 방식 선택 UI가 뜨면 처리
        # (업로드 서버 처리 시간에 따라 UI가 늦게 뜰 수 있어 timeout을 넉넉히 설정)
        if len(paths) >= 2:
            try:
                ch = _handle_multi_image_layout_choice(page, prefer="개별", timeout_ms=30000)
                print(f"[upload] layout_choice={ch}")
            except Exception as e:
                print(f"[upload] layout_choice_failed: {e}")
        settled = _wait_for_image_upload_settled(page, timeout_ms=180000)
        print(f"[upload] settled={settled}")
        return {"ok": True, "count": len(paths), "settled": settled, "via": "filechooser"}

    # 1) 안 되면 기존 방식: input[type=file] 찾아 set_input_files
    opened = _open_image_upload_ui(page)
    print(f"[upload] upload_ui_opened={opened}")
    page.wait_for_timeout(300)

    fr, file_input = _find_file_input_for_images(page)
    if file_input is not None:
        try:
            file_input.set_input_files(paths)
            print(f"[upload] set_input_files OK: {len(paths)} files (frame={getattr(fr,'url',None)})")

            if len(paths) >= 2:
                try:
                    ch = _handle_multi_image_layout_choice(page, prefer="개별", timeout_ms=30000)
                    print(f"[upload] layout_choice={ch}")
                except Exception as e:
                    print(f"[upload] layout_choice_failed: {e}")

            settled = _wait_for_image_upload_settled(page, timeout_ms=180000)
            print(f"[upload] settled={settled}")

            if not settled.get("ok"):
                return {"ok": True, "count": len(paths), "warn": settled, "via": "set_input_files"}

            return {"ok": True, "count": len(paths), "settled": settled, "via": "set_input_files"}
        except Exception as e:
            print(f"[upload] set_input_files_failed: {e}")

    # 2) 마지막 백업: OS 파일 선택창이 이미 떠 있는 상태면 pywinauto로 파일명 입력 후 열기
    dlg_ok = _try_upload_via_windows_dialog(paths)
    if dlg_ok:
        settled = _wait_for_image_upload_settled(page, timeout_ms=180000)
        print(f"[upload] settled={settled}")
        return {"ok": True, "count": len(paths), "settled": settled, "via": "pywinauto_dialog"}

    return {"ok": False, "reason": "file_input_not_found_and_dialog_control_failed"}


def _safe_click_any(page, selectors: list[str], *, timeout_ms: int = 1500) -> bool:
    """여러 셀렉터 중 화면에서 클릭 가능한 것이 있으면 클릭하고 True."""
    for sel in selectors:
        try:
            loc = page.locator(sel).first
            if loc.count() > 0 and loc.is_visible() and loc.is_enabled():
                loc.click(timeout=timeout_ms)
                return True
        except Exception:
            continue
    return False


def _robust_click_in_page_or_frames(page, selectors: list[str], *, timeout_ms: int = 3000) -> bool:
    """page 및 모든 frame에서 selectors 중 하나를 최대한 '어떻게든' 클릭.

    네이버 에디터는
    - iframe 내부
    - overlay가 클릭을 가로채는 타이밍
    - 버튼이 보이지만 playwright 기본 click이 실패
    같은 경우가 있어 단계적 폴백을 둡니다.
    """

    def _try_click_in_root(root) -> bool:
        for sel in selectors:
            try:
                loc = root.locator(sel).first
                if loc.count() == 0:
                    continue
                if not loc.is_visible():
                    continue

                # 1) 일반 클릭
                try:
                    loc.click(timeout=timeout_ms)
                    return True
                except Exception:
                    pass

                # 2) trial 클릭(가능 여부 테스트) 후 force 클릭
                try:
                    loc.click(trial=True, timeout=timeout_ms)
                except Exception:
                    pass
                try:
                    loc.click(force=True, timeout=timeout_ms)
                    return True
                except Exception:
                    pass

                # 3) 좌표 클릭 폴백
                try:
                    bb = loc.bounding_box()
                    if bb:
                        root.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2)
                        return True
                except Exception:
                    pass
            except Exception:
                continue
        return False

    # page 먼저
    if _try_click_in_root(page):
        return True
    # frames
    for fr in list(page.frames):
        try:
            if _try_click_in_root(fr):
                return True
        except Exception:
            continue
    return False


def _diagnose_click_intercept(page, loc) -> dict:
    """클릭이 막힐 때(투명 오버레이 등) 화면 최상단 요소가 무엇인지 진단."""
    try:
        bb = loc.bounding_box()
        if not bb:
            return {"ok": False, "reason": "no_bounding_box"}
        x = bb["x"] + bb["width"] / 2
        y = bb["y"] + bb["height"] / 2
        info = page.evaluate(
            """([x,y]) => {
                const el = document.elementFromPoint(x,y);
                if (!el) return {found:false};
                const cs = window.getComputedStyle(el);
                const path = [];
                let cur = el;
                for (let i=0; i<6 && cur; i++) {
                    const id = cur.id ? ('#'+cur.id) : '';
                    const cls = cur.className && typeof cur.className==='string' ? ('.'+cur.className.split(/\s+/).filter(Boolean).slice(0,3).join('.')) : '';
                    path.push(cur.tagName.toLowerCase()+id+cls);
                    cur = cur.parentElement;
                }
                return {
                    found:true,
                    tag: el.tagName,
                    id: el.id || null,
                    className: (typeof el.className==='string' ? el.className : null),
                    pointerEvents: cs.pointerEvents,
                    opacity: cs.opacity,
                    zIndex: cs.zIndex,
                    text: (el.innerText || '').slice(0,80),
                    path
                };
            }""",
            [x, y],
        )
        return {"ok": True, "x": x, "y": y, "top": info}
    except Exception as e:
        return {"ok": False, "reason": f"diagnose_failed: {e}"}


def _attempt_close_common_overlays(page) -> bool:
    """발행 버튼을 가리는 투명/반투명 오버레이를 닫기 시도."""
    # 1) ESC로 닫히는 레이어가 많음
    try:
        page.keyboard.press("Escape")
        page.wait_for_timeout(200)
    except Exception:
        pass

    # 2) 흔한 dim/backdrop 후보를 클릭해 닫기(너무 위험한 광역 클릭은 피하고, role/aria 기반 위주)
    overlay_selectors = [
        "[role='dialog']",
        "[aria-modal='true']",
        "div[role='presentation']",
        "div[class*='dim']",
        "div[class*='Dim']",
        "div[class*='overlay']",
        "div[class*='Overlay']",
        "div[class*='backdrop']",
        "div[class*='Backdrop']",
    ]
    closed = False
    for sel in overlay_selectors:
        try:
            loc = page.locator(sel).first
            if loc.count() > 0 and loc.is_visible():
                # dim 영역은 중앙 클릭으로 닫히는 케이스가 있어 bbox 클릭
                bb = loc.bounding_box()
                if bb:
                    page.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2)
                    page.wait_for_timeout(250)
                    closed = True
        except Exception:
            continue
    return closed


def _js_force_click(page, selector: str) -> bool:
    """Playwright click이 계속 막힐 때 JS 이벤트를 직접 발생(최후 수단)."""
    try:
        ok = page.evaluate(
            """(sel) => {
                const el = document.querySelector(sel);
                if (!el) return false;
                el.scrollIntoView({block:'center', inline:'center'});
                const opts = {bubbles:true, cancelable:true, composed:true};
                el.dispatchEvent(new PointerEvent('pointerdown', opts));
                el.dispatchEvent(new MouseEvent('mousedown', opts));
                el.dispatchEvent(new MouseEvent('mouseup', opts));
                el.dispatchEvent(new MouseEvent('click', opts));
                return true;
            }""",
            selector,
        )
        return bool(ok)
    except Exception:
        return False


def close_help_dialog_if_present(page) -> bool:
    """글쓰기 화면 우측 상단에 뜨는 '도움말/가이드' 계열 다이얼로그를 닫습니다.

    네이버 스마트에디터의 도움말은 표준 ARIA role을 사용하지 않는 경우가 많아,
    1) 에디터 전용 클래스(se-help, se-guide, coaching 등)를 JS로 직접 스캔
    2) z-index가 높은 오버레이 내부의 X/닫기 버튼을 자동 감지
    3) page + 모든 iframe에서 시도
    """
    deadline = time.time() + 10.0

    # 약간 대기 후 시작(말풍선 애니메이션 대비)
    try:
        page.wait_for_timeout(500)
    except Exception:
        time.sleep(0.5)

    # ---------- JS 기반: 에디터 프레임 내 도움말 오버레이 X 버튼 탐색 및 클릭 ----------
    _JS_FIND_AND_CLOSE_HELP = """() => {
        // 1단계: 네이버 에디터 전용 도움말/가이드/코칭 클래스 패턴으로 오버레이 탐색
        const helpPatterns = [
            'se-help', 'se-guide', 'se-tooltip', 'se-coach', 'se-popover',
            'help_popup', 'helpPopup', 'guide_popup', 'guidePopup',
            'coaching', 'onboarding', 'tooltip_layer', 'tooltipLayer',
            'help_layer', 'helpLayer', 'guide_layer', 'guideLayer',
            'help-balloon', 'helpBalloon', 'help_area', 'helpArea',
            'noti_popup', 'notiPopup', 'notice_popup', 'noticePopup',
        ];

        const rolePatterns = ['dialog', 'tooltip', 'alertdialog'];
        const textPatterns = ['도움말', '가이드', 'help', 'guide', '안내', '팁'];

        function isVisible(el) {
            if (!el) return false;
            const r = el.getBoundingClientRect();
            if (r.width < 10 || r.height < 10) return false;
            const cs = window.getComputedStyle(el);
            if (cs.display === 'none' || cs.visibility === 'hidden' || cs.opacity === '0') return false;
            return true;
        }

        function findCloseButtonInside(container) {
            // X 닫기 버튼 찾기 (여러 패턴)
            const closeSelectors = [
                'button[class*="close"]', 'button[class*="Close"]',
                'a[class*="close"]', 'a[class*="Close"]',
                'span[class*="close"]', 'span[class*="Close"]',
                'div[class*="close"]', 'div[class*="Close"]',
                'button[class*="cancel"]', 'button[class*="Cancel"]',
                '[aria-label*="닫기"]', '[aria-label*="Close"]', '[aria-label*="close"]',
                '[title*="닫기"]', '[title*="Close"]', '[title*="close"]',
                'button:last-child', // 종종 X가 마지막 자식
            ];

            for (const sel of closeSelectors) {
                try {
                    const els = container.querySelectorAll(sel);
                    for (const el of els) {
                        if (isVisible(el)) return el;
                    }
                } catch(e) {}
            }

            // SVG 아이콘이 있는 button/a 찾기
            const btnsWithSvg = container.querySelectorAll('button, a, [role="button"]');
            for (const b of btnsWithSvg) {
                if (!isVisible(b)) continue;
                if (b.querySelector('svg') || b.querySelector('img')) {
                    const r = b.getBoundingClientRect();
                    // X 닫기 버튼은 보통 작은 크기(40px 이하)
                    if (r.width <= 50 && r.height <= 50) return b;
                }
                // 텍스트가 X, ×, ✕ 인 경우
                const txt = (b.textContent || '').trim();
                if (txt === 'X' || txt === '×' || txt === '✕' || txt === '✖' || txt === '닫기') {
                    return b;
                }
            }

            // span/div 중 X 텍스트를 가진 것
            const allSpans = container.querySelectorAll('span, div, i');
            for (const s of allSpans) {
                if (!isVisible(s)) continue;
                const txt = (s.textContent || '').trim();
                if ((txt === 'X' || txt === '×' || txt === '✕' || txt === '✖') && s.getBoundingClientRect().width <= 40) {
                    return s;
                }
            }

            // 컨테이너 우측 끝에 있는 클릭 가능한 요소 찾기 (X 아이콘은 보통 오른쪽 끝에 위치)
            const containerRect = container.getBoundingClientRect();
            const rightEdge = containerRect.right;
            const allClickable = container.querySelectorAll('button, a, [role="button"], span, div');
            let rightMost = null;
            let rightMostX = -Infinity;
            for (const el of allClickable) {
                if (!isVisible(el)) continue;
                const r = el.getBoundingClientRect();
                // 크기가 적당히 작은 요소만 (닫기 버튼 크기)
                if (r.width > 60 || r.height > 60) continue;
                if (r.width < 5 || r.height < 5) continue;
                // 컨테이너 우측 20% 이내
                if (r.left > containerRect.left + containerRect.width * 0.7) {
                    if (r.right > rightMostX) {
                        rightMostX = r.right;
                        rightMost = el;
                    }
                }
            }
            if (rightMost) return rightMost;

            return null;
        }

        function clickElement(el) {
            try {
                el.scrollIntoView({block:'center', inline:'center'});
                const opts = {bubbles:true, cancelable:true, composed:true};
                el.dispatchEvent(new PointerEvent('pointerdown', opts));
                el.dispatchEvent(new MouseEvent('mousedown', opts));
                el.dispatchEvent(new MouseEvent('mouseup', opts));
                el.dispatchEvent(new MouseEvent('click', opts));
                return true;
            } catch(e) {
                return false;
            }
        }

        // --- 메인 탐색 로직 ---
        const results = [];

        // (A) 클래스 패턴으로 도움말 컨테이너 찾기
        const allElements = document.querySelectorAll('*');
        for (const el of allElements) {
            if (!isVisible(el)) continue;
            const cls = (typeof el.className === 'string' ? el.className : '').toLowerCase();
            const role = (el.getAttribute('role') || '').toLowerCase();
            const text = (el.innerText || '').slice(0, 100).toLowerCase();

            let isHelp = false;

            // 클래스 패턴 매치
            for (const pat of helpPatterns) {
                if (cls.includes(pat.toLowerCase())) { isHelp = true; break; }
            }

            // role 패턴 매치(+ 텍스트 내용이 도움말 관련)
            if (!isHelp) {
                for (const rp of rolePatterns) {
                    if (role === rp) {
                        for (const tp of textPatterns) {
                            if (text.includes(tp)) { isHelp = true; break; }
                        }
                        if (isHelp) break;
                    }
                }
            }

            if (!isHelp) continue;

            // 도움말 컨테이너 발견 → X 닫기 버튼 찾기
            const closeBtn = findCloseButtonInside(el);
            const r = el.getBoundingClientRect();
            results.push({
                found: true,
                cls: (typeof el.className === 'string' ? el.className.slice(0, 120) : ''),
                rect: {x: r.x, y: r.y, w: r.width, h: r.height},
                hasCloseBtn: !!closeBtn,
                closeBtnTag: closeBtn ? closeBtn.tagName : null,
                closeBtnCls: closeBtn ? (typeof closeBtn.className === 'string' ? closeBtn.className.slice(0, 80) : '') : null,
            });

            if (closeBtn) {
                const clicked = clickElement(closeBtn);
                return {ok: true, method: 'class_pattern', clicked: clicked, detail: results[results.length - 1]};
            }
        }

        // (B) z-index가 높은(100 이상) visible 오버레이 스캔
        const overlays = [];
        for (const el of allElements) {
            if (!isVisible(el)) continue;
            const cs = window.getComputedStyle(el);
            const z = parseInt(cs.zIndex, 10);
            if (isNaN(z) || z < 100) continue;
            const r = el.getBoundingClientRect();
            // 너무 큰 요소(전체화면)나 너무 작은 요소는 제외
            if (r.width > window.innerWidth * 0.8 && r.height > window.innerHeight * 0.8) continue;
            if (r.width < 30 || r.height < 30) continue;

            overlays.push({el, z, r});
        }
        // z-index 높은 순으로 정렬
        overlays.sort((a, b) => b.z - a.z);

        for (const ov of overlays.slice(0, 5)) {
            const closeBtn = findCloseButtonInside(ov.el);
            if (closeBtn) {
                const clicked = clickElement(closeBtn);
                return {
                    ok: true, method: 'z_index_overlay', clicked: clicked, zIndex: ov.z,
                    cls: (typeof ov.el.className === 'string' ? ov.el.className.slice(0, 80) : ''),
                };
            }
        }

        // (C) 위 방법 모두 실패 → 우측 상단 영역의 작은 버튼/클릭가능 요소를 클릭
        //     도움말 X는 보통 화면 우측 상단에 위치
        const vpW = window.innerWidth;
        const candidates = [];
        for (const el of document.querySelectorAll('button, a, [role="button"], span')) {
            if (!isVisible(el)) continue;
            const r = el.getBoundingClientRect();
            // 우측 30% 영역, 상단 25% 영역 내의 작은 요소
            if (r.left > vpW * 0.7 && r.top < window.innerHeight * 0.25) {
                if (r.width <= 50 && r.height <= 50 && r.width >= 8 && r.height >= 8) {
                    const txt = (el.textContent || '').trim();
                    const aria = el.getAttribute('aria-label') || el.getAttribute('title') || '';
                    const hasSvg = !!el.querySelector('svg');
                    const isCloselike = (
                        txt === 'X' || txt === '×' || txt === '✕' || txt === '닫기' ||
                        aria.includes('닫기') || aria.includes('close') || aria.includes('Close') ||
                        hasSvg || txt === ''
                    );
                    if (isCloselike) {
                        candidates.push({el, r, score: (hasSvg ? 10 : 0) + (txt === '' ? 5 : 0) + (r.left / vpW * 10)});
                    }
                }
            }
        }
        // 가장 우측에 있는 후보 클릭
        candidates.sort((a, b) => b.score - a.score || b.r.left - a.r.left);
        if (candidates.length > 0) {
            const clicked = clickElement(candidates[0].el);
            return {ok: true, method: 'top_right_scan', clicked: clicked, count: candidates.length};
        }

        return {ok: false, reason: 'no_help_overlay_found', scanned: results.length};
    }"""

    def _try_js_close_in_root(root) -> dict:
        """단일 root(page or frame)에서 JS 기반 도움말 닫기를 시도."""
        try:
            return root.evaluate(_JS_FIND_AND_CLOSE_HELP)
        except Exception as e:
            return {"ok": False, "reason": f"js_error: {e}"}

    # ---------- 기존 Playwright 셀렉터 기반 닫기 (보조) ----------
    def _try_playwright_close(root) -> bool:
        """Playwright 셀렉터로 닫기 버튼을 찾아 클릭."""
        close_selectors = [
            # 네이버 에디터 전용 패턴
            "[class*='se-help'] button",
            "[class*='se-guide'] button",
            "[class*='se-tooltip'] button",
            "[class*='se-coach'] button",
            "[class*='se-help'] [class*='close']",
            "[class*='se-guide'] [class*='close']",
            "[class*='help'] [class*='close']",
            "[class*='guide'] [class*='close']",
            "[class*='tooltip'] [class*='close']",
            "[class*='coaching'] [class*='close']",
            # 표준 ARIA
            "button[aria-label*='닫기']",
            "button[title*='닫기']",
            "[role='button'][aria-label*='닫기']",
            "button[aria-label*='Close']",
            "button[title*='Close']",
            # 일반
            "button:has-text('닫기')",
            "button:has(svg)",
        ]
        for sel in close_selectors:
            try:
                loc = root.locator(sel).first
                if loc.count() > 0 and loc.is_visible():
                    try:
                        loc.click(timeout=800, force=True)
                        return True
                    except Exception:
                        bb = loc.bounding_box()
                        if bb:
                            page.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2)
                            return True
            except Exception:
                continue
        return False

    # ---------- 메인 루프 ----------
    attempt = 0
    debug_dumped = False

    while time.time() < deadline:
        attempt += 1

        # (1) JS 기반 닫기 — page + 모든 frame
        roots = [page] + list(page.frames)
        for root in roots:
            result = _try_js_close_in_root(root)
            if result.get("ok"):
                print(f"[help] JS close success: {result}")
                try:
                    page.wait_for_timeout(500)
                except Exception:
                    time.sleep(0.5)
                return True

        # (2) Playwright 셀렉터 기반 닫기
        for root in roots:
            try:
                if _try_playwright_close(root):
                    print(f"[help] Playwright close success in {getattr(root, 'url', 'page')[:60]}")
                    try:
                        page.wait_for_timeout(500)
                    except Exception:
                        time.sleep(0.5)
                    return True
            except Exception:
                continue

        # (3) ESC 키
        try:
            page.keyboard.press("Escape")
            page.wait_for_timeout(300)
        except Exception:
            pass

        # ESC 후 닫혔는지 빠르게 확인
        esc_closed = True
        for root in roots:
            r = _try_js_close_in_root(root)
            if r.get("ok"):
                # 아직 닫히지 않았다는 의미(새로 찾았으니까)
                esc_closed = False
                print(f"[help] found again after ESC, JS re-close: {r}")
                try:
                    page.wait_for_timeout(300)
                except Exception:
                    time.sleep(0.3)
                break

        # 아무것도 못 찾았으면 (JS가 no_help_overlay_found 반환) → 이미 닫힌 것
        all_not_found = True
        for root in roots:
            r = _try_js_close_in_root(root)
            if r.get("ok"):
                all_not_found = False
                break
        if all_not_found:
            print(f"[help] no overlay found → considered closed (attempt={attempt})")
            return True

        # (4) 디버그 덤프 (첫 1회만)
        if not debug_dumped:
            debug_dumped = True
            try:
                # 각 frame에서 도움말 관련 요소 진단 로그
                for idx, root in enumerate(roots[:6]):
                    try:
                        diag = root.evaluate("""() => {
                            const all = document.querySelectorAll('*');
                            const hits = [];
                            const patterns = ['help','guide','tooltip','coach','popup','balloon','noti','onboard'];
                            for (const el of all) {
                                const cls = (typeof el.className === 'string' ? el.className : '').toLowerCase();
                                const r = el.getBoundingClientRect();
                                if (r.width < 10 || r.height < 10) continue;
                                const cs = window.getComputedStyle(el);
                                if (cs.display === 'none' || cs.visibility === 'hidden') continue;
                                for (const p of patterns) {
                                    if (cls.includes(p)) {
                                        hits.push({
                                            tag: el.tagName, cls: cls.slice(0,100),
                                            rect: {x:r.x|0, y:r.y|0, w:r.width|0, h:r.height|0},
                                            children: el.children.length,
                                            text: (el.innerText||'').replace(/\\s+/g,' ').slice(0,50),
                                        });
                                        break;
                                    }
                                }
                            }
                            return hits.slice(0, 10);
                        }""")
                        if diag:
                            print(f"[help][diag] root[{idx}] url={getattr(root, 'url', 'page')[:60]} hits={diag}")
                    except Exception as e:
                        print(f"[help][diag] root[{idx}] failed: {e}")
            except Exception:
                pass

            try:
                p = Path(__file__).with_name("debug_help_overlay.png")
                page.screenshot(path=str(p), full_page=True)
                print(f"[help][diag] screenshot saved: {p}")
            except Exception:
                pass

        try:
            page.wait_for_timeout(400)
        except Exception:
            time.sleep(0.4)

    print(f"[help] timeout after {attempt} attempts")
    return False


def publish_post(page, *, timeout_ms: int = 60000) -> dict:
    """네이버 블로그 에디터에서 '발행'을 2단계로 눌러 최종 게시까지 진행.

    흐름(일반적):
    1) 우측 상단 '발행'
    2) 발행 설정/확인 다이얼로그에서 '발행' 또는 '확인'
    3) 게시 완료 후 게시글 화면(또는 완료 토스트)로 전환
    """
    print("[publish] start")

    # ── 0단계: 이미지 업로드/개별사진 선택 직후의 에디터 안정화 대기 ──
    # 이미지 업로드 → 개별사진 클릭까지 걸리는 시간만큼, 도움말 닫기 전에도 에디터가 안정화되어야 함
    try:
        pre_help_delay = float(os.getenv("NAVER_PRE_HELP_DELAY", "3.0").strip() or "3.0")
    except Exception:
        pre_help_delay = 3.0
    if pre_help_delay > 0:
        print(f"[publish] pre-help stabilization wait {pre_help_delay}s")
        try:
            page.wait_for_timeout(int(pre_help_delay * 1000))
        except Exception:
            time.sleep(pre_help_delay)

    # ── 1단계: 도움말 닫기 (반복 시도 + 확인 루프) ──
    # close_help_dialog_if_present는 내부에서 JS 전면 스캔 + Playwright + ESC 등을 시도하고
    # True(닫힘/없음) 또는 False(타임아웃)를 반환.
    # True가 돌아와도 혹시 남아있을 수 있어, 한 번 더 호출해서 '찾을 게 없음'을 확인.
    help_confirmed_closed = False
    for help_attempt in range(1, 4):  # 최대 3회
        try:
            result = close_help_dialog_if_present(page)
            print(f"[publish] help close attempt={help_attempt} result={result}")
        except Exception as e:
            print(f"[publish] help close attempt={help_attempt} error={e}")
            result = False

        if result:
            # 닫기 성공 후 잠깐 대기하고 재확인
            try:
                page.wait_for_timeout(800)
            except Exception:
                time.sleep(0.8)

            # 한 번 더 호출해서 정말 닫혔는지(= 찾을 게 없는지) 확인
            try:
                result2 = close_help_dialog_if_present(page)
                print(f"[publish] help re-verify attempt={help_attempt} result={result2}")
            except Exception:
                result2 = True  # 에러면 없는 것으로 간주

            if result2:
                help_confirmed_closed = True
                print(f"[publish] help confirmed closed after {help_attempt} attempts")
                break
            else:
                print(f"[publish] help still present after attempt={help_attempt}, retrying...")
        else:
            # False = 타임아웃까지 못 닫음 → 한 번 더 시도
            print(f"[publish] help close timed out attempt={help_attempt}")

        try:
            page.wait_for_timeout(500)
        except Exception:
            time.sleep(0.5)

    if not help_confirmed_closed:
        print("[publish] WARNING: help dialog may still be open after all attempts, proceeding anyway")

    # ── 2단계: 도움말 닫힌 뒤 UI 재배치 안정화 대기 ──
    try:
        delay1 = float(os.getenv("NAVER_PUBLISH_DELAY1", "2.0").strip() or "2.0")
    except Exception:
        delay1 = 2.0
    if delay1 > 0:
        print(f"[publish] post-help stabilization wait {delay1}s")
        try:
            page.wait_for_timeout(int(delay1 * 1000))
        except Exception:
            time.sleep(delay1)

    # ── 3단계: 발행 버튼이 클릭 가능해질 때까지 대기 ──
    publish_ready_selectors = [
        ".publish_btn__m9KHH",
        ".publish_btn__m9KHH button",
        "[class*='publish_btn__']",
        "[class*='publish_btn__'] button",
        "button:has-text('발행')",
        "a:has-text('발행')",
        "[role='button'][aria-label*='발행']",
    ]

    def _any_visible_enabled_in_page_or_frames() -> bool:
        roots = [page] + list(page.frames)
        for root in roots:
            for sel in publish_ready_selectors:
                try:
                    loc = root.locator(sel).first
                    if loc.count() > 0 and loc.is_visible() and loc.is_enabled():
                        return True
                except Exception:
                    continue
        return False

    # 디버그: frame 구조 로그
    try:
        fr_urls = []
        for fr in list(page.frames):
            try:
                fr_urls.append(fr.url)
            except Exception:
                fr_urls.append("(no-url)")
        print(f"[publish] frames={len(fr_urls)}")
        for u in fr_urls[:8]:
            print(f"  - frame: {u}")
    except Exception:
        pass

    print("[publish] waiting publish button visible/enabled")
    deadline_ready = time.time() + (timeout_ms / 1000)
    while time.time() < deadline_ready:
        if _any_visible_enabled_in_page_or_frames():
            break
        time.sleep(0.3)
    print("[publish] trying first click")

    # '발행'은 다이얼로그/팝업에도 동일 텍스트가 있을 수 있어,
    # 1차 발행은 헤더/상단 영역을 최대한 우선으로 잡습니다.
    # 사용자 확인: 발행 버튼이 특정 클래스(publish_btn__m9KHH)로 감싸진 케이스가 있음
    publish_selectors = [
        # 가장 구체적인 후보(네이버 에디터 버전에 따라 해시 클래스가 바뀔 수 있어도 우선)
        ".publish_btn__m9KHH",
        ".publish_btn__m9KHH button",
        ".publish_btn__m9KHH a",
        # 클래스가 바뀌는 케이스 대응
        "[class*='publish_btn__']",
        "[class*='publish_btn__'] button",
        "[class*='publish_btn__'] a",
        # 접근성 role 기반(있으면 가장 안정적)
        "[role='button'][aria-label*='발행']",
        # 상단 헤더/툴바로 스코프 제한(오탐 방지)
        "header button:has-text('발행')",
        "header a:has-text('발행')",
        "[role='banner'] button:has-text('발행')",
        "[role='banner'] a:has-text('발행')",
        "[class*='header'] button:has-text('발행')",
        "[class*='Header'] button:has-text('발행')",
        "[class*='toolbar'] button:has-text('발행')",
        "[class*='ToolBar'] button:has-text('발행')",
        # 범용 fallback
        "button:has-text('발행')",
        "a:has-text('발행')",
        "button[aria-label*='발행']",
        "text=발행",
    ]

    # 1차 발행 버튼 대기/클릭
    # - page 뿐 아니라 iframe 안에 버튼이 있을 수 있어 _wait_for_any_selector 대신 robust click으로 바로 시도
    if not _robust_click_in_page_or_frames(page, publish_selectors, timeout_ms=3000):
        return {"ok": False, "reason": "publish_button_not_found"}

    # '보이지만 클릭이 안 됨' 케이스 대응:
    # - 오버레이가 남아 클릭을 가로채는 경우가 있어 ESC로 1회 정리
    # - 상단 고정 버튼이라 scrollIntoView가 의미 없을 수 있지만, 포커스/레이아웃 안정화 용으로 시도
    try:
        page.keyboard.press("Escape")
        page.wait_for_timeout(200)
    except Exception:
        pass

    if not _robust_click_in_page_or_frames(page, publish_selectors, timeout_ms=3000):
        # === 진단/해소: 투명 오버레이 클릭 가로채기 여부 ===
        diag = None
        try:
            publish_loc = page.locator(".publish_btn__m9KHH").first
            if publish_loc.count() == 0:
                publish_loc = page.locator("button:has-text('발행')").first
            if publish_loc.count() > 0:
                diag = _diagnose_click_intercept(page, publish_loc)
                print(f"[publish][diag] {diag}")
        except Exception:
            pass

        # 오버레이/모달 닫기 시도 후 재시도
        _attempt_close_common_overlays(page)
        try:
            page.wait_for_timeout(400)
        except Exception:
            pass

        if _robust_click_in_page_or_frames(page, publish_selectors, timeout_ms=3000):
            pass
        else:
            # JS 강제 클릭(가장 구체 selector부터)
            if _js_force_click(page, ".publish_btn__m9KHH") or _js_force_click(page, ".publish_btn__m9KHH button"):
                pass
            else:
                try:
                    page.keyboard.press("Enter")
                except Exception:
                    pass
                # 마지막 폴백: 화면에서 '발행' 텍스트 노드의 bbox를 직접 클릭
                try:
                    loc = page.get_by_text("발행", exact=True).first
                    if loc.count() > 0 and loc.is_visible():
                        bb = loc.bounding_box()
                        if bb:
                            page.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2)
                        else:
                            return {"ok": False, "reason": "publish_click_failed", "diag": diag}
                    else:
                        return {"ok": False, "reason": "publish_click_failed", "diag": diag}
                except Exception:
                    return {"ok": False, "reason": "publish_click_failed", "diag": diag}

    print("[publish] first click done; waiting dialog")

    # 2차 발행 전 잠깐 대기(발행 설정 다이얼로그 렌더링 시간)
    try:
        delay2 = float(os.getenv("NAVER_PUBLISH_DELAY2", "1.0").strip() or "1.0")
    except Exception:
        delay2 = 1.0
    if delay2 > 0:
        try:
            page.wait_for_timeout(int(delay2 * 1000))
        except Exception:
            time.sleep(delay2)

    # 2차 다이얼로그 발행(또는 확인/완료)
    # - 1차 발행 클릭 후 '발행 설정' 다이얼로그가 뜨고, 그 안의 '발행' 버튼을 눌러야 최종 게시됨
    # - 헤더의 1차 발행 버튼과 혼동하지 않도록, 다이얼로그/모달 컨텍스트 내부를 우선 검색

    # 다이얼로그 감지 셀렉터(1차 발행 클릭 후 나타나는 설정/확인 레이어)
    dialog_container_selectors = [
        "[role='dialog']",
        "[aria-modal='true']",
        "div[class*='layer']",
        "div[class*='Layer']",
        "div[class*='modal']",
        "div[class*='Modal']",
        "div[class*='popup']",
        "div[class*='Popup']",
        "div[class*='dialog']",
        "div[class*='Dialog']",
        "div[class*='publish_layer']",
        "div[class*='PublishLayer']",
        "div[class*='setting']",
    ]

    # 다이얼로그 안에서 찾을 2차 발행 버튼 셀렉터
    dialog_confirm_selectors = [
        # 가장 구체적: 사용자 확인된 2차 발행 버튼 클래스
        ".confirm_btn__WEaBq",
        ".confirm_btn__WEaBq button",
        "[class*='confirm_btn__']",
        "[class*='confirm_btn__'] button",
        "button:has-text('발행')",
        "button:has-text('확인')",
        "button:has-text('완료')",
        "button:has-text('등록')",
    ]

    # 범용 (다이얼로그 스코프 제한 없이)
    fallback_confirm_selectors = [
        ".confirm_btn__WEaBq",
        ".confirm_btn__WEaBq button",
        "[class*='confirm_btn__']",
        "[class*='confirm_btn__'] button",
        "button:has-text('발행')",
        "text=발행",
        "button:has-text('확인')",
        "button:has-text('완료')",
        "button:has-text('등록')",
    ]

    deadline = time.time() + (timeout_ms / 1000)
    clicked2 = False

    def _try_click_in_dialog(root) -> bool:
        """다이얼로그 컨테이너 내부에서 발행/확인 버튼을 스코프 한정하여 클릭 시도."""
        for dc_sel in dialog_container_selectors:
            try:
                containers = root.locator(dc_sel)
                for ci in range(min(containers.count(), 5)):
                    container = containers.nth(ci)
                    if not container.is_visible():
                        continue
                    for btn_sel in dialog_confirm_selectors:
                        try:
                            btn = container.locator(btn_sel).first
                            if btn.count() > 0 and btn.is_visible() and btn.is_enabled():
                                try:
                                    btn.click(timeout=2000)
                                    return True
                                except Exception:
                                    try:
                                        btn.click(timeout=2000, force=True)
                                        return True
                                    except Exception:
                                        bb = btn.bounding_box()
                                        if bb:
                                            root.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2)
                                            return True
                        except Exception:
                            continue
            except Exception:
                continue
        return False

    while time.time() < deadline:
        # (★) 최우선: confirm_btn__WEaBq 클래스로 2차 발행 버튼 직접 검색 (page + 모든 frame)
        direct_selectors = [
            ".confirm_btn__WEaBq",
            ".confirm_btn__WEaBq button",
            "[class*='confirm_btn__']",
            "[class*='confirm_btn__'] button",
        ]
        roots = [page] + list(page.frames)
        for root in roots:
            for sel in direct_selectors:
                try:
                    loc = root.locator(sel).first
                    if loc.count() > 0 and loc.is_visible() and loc.is_enabled():
                        try:
                            loc.click(timeout=2000)
                            clicked2 = True
                        except Exception:
                            try:
                                loc.click(timeout=2000, force=True)
                                clicked2 = True
                            except Exception:
                                bb = loc.bounding_box()
                                if bb:
                                    page.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2)
                                    clicked2 = True
                        if clicked2:
                            print(f"[publish] 2nd button found via direct selector: {sel}")
                            break
                except Exception:
                    continue
            if clicked2:
                break
        if clicked2:
            try:
                page.wait_for_timeout(600)
            except Exception:
                pass
            break

        # (A) 다이얼로그 컨텍스트 내부 검색 (page + 모든 frame)
        roots = [page] + list(page.frames)
        for root in roots:
            try:
                if _try_click_in_dialog(root):
                    clicked2 = True
                    break
            except Exception:
                continue
        if clicked2:
            try:
                page.wait_for_timeout(600)
            except Exception:
                pass
            break

        # (B) 다이얼로그를 못 찾으면 범용 fallback (1차 버튼과 같은 걸 다시 누르는 리스크가 있지만 최후 수단)
        #     단, 1차 버튼과 구분하기 위해 publish_btn 클래스가 아닌 버튼만 시도
        for root in roots:
            for sel in fallback_confirm_selectors:
                try:
                    locs = root.locator(sel)
                    for li in range(min(locs.count(), 5)):
                        loc = locs.nth(li)
                        if not loc.is_visible() or not loc.is_enabled():
                            continue
                        # 1차 발행 버튼(헤더)은 publish_btn 클래스를 가짐 → 건너뛰기
                        try:
                            cls = loc.get_attribute("class") or ""
                            parent_cls = loc.evaluate("el => el.parentElement ? (el.parentElement.className || '') : ''") or ""
                        except Exception:
                            cls = ""
                            parent_cls = ""
                        if "publish_btn" in cls or "publish_btn" in parent_cls:
                            continue  # 1차 버튼 스킵
                        try:
                            loc.click(timeout=2000)
                            clicked2 = True
                            break
                        except Exception:
                            try:
                                loc.click(timeout=2000, force=True)
                                clicked2 = True
                                break
                            except Exception:
                                bb = loc.bounding_box()
                                if bb:
                                    root.mouse.click(bb["x"] + bb["width"] / 2, bb["y"] + bb["height"] / 2)
                                    clicked2 = True
                                    break
                except Exception:
                    continue
                if clicked2:
                    break
            if clicked2:
                break
        if clicked2:
            try:
                page.wait_for_timeout(600)
            except Exception:
                pass
            break

        # (C) JS 강제 클릭: 다이얼로그 내부 발행 버튼을 JS로 직접 찾아 클릭
        for root in roots:
            try:
                js_ok = root.evaluate("""() => {
                    const opts = {bubbles:true, cancelable:true, composed:true};
                    function forceClick(el) {
                        el.scrollIntoView({block:'center'});
                        el.dispatchEvent(new PointerEvent('pointerdown', opts));
                        el.dispatchEvent(new MouseEvent('mousedown', opts));
                        el.dispatchEvent(new MouseEvent('mouseup', opts));
                        el.dispatchEvent(new MouseEvent('click', opts));
                        return true;
                    }

                    // 1) confirm_btn 클래스로 직접 찾기
                    const confirmBtn = document.querySelector('[class*="confirm_btn__"]');
                    if (confirmBtn && confirmBtn.offsetWidth > 0 && confirmBtn.offsetHeight > 0) {
                        // 자신이 button이면 바로 클릭, 아니면 내부 button 찾기
                        const btn = confirmBtn.tagName === 'BUTTON' ? confirmBtn : (confirmBtn.querySelector('button') || confirmBtn);
                        return forceClick(btn);
                    }

                    // 2) 다이얼로그/모달 컨테이너 안의 '발행' 버튼을 찾아 클릭
                    const dialogs = document.querySelectorAll('[role=dialog], [aria-modal=true], [class*=layer], [class*=Layer], [class*=modal], [class*=Modal], [class*=popup], [class*=Popup]');
                    for (const d of dialogs) {
                        if (d.offsetWidth === 0 || d.offsetHeight === 0) continue;
                        const btns = d.querySelectorAll('button');
                        for (const b of btns) {
                            const txt = (b.innerText || '').trim();
                            if (txt === '발행' || txt === '확인' || txt === '완료' || txt === '등록') {
                                if (b.offsetWidth > 0 && b.offsetHeight > 0) {
                                    return forceClick(b);
                                }
                            }
                        }
                    }
                    return false;
                }""")
                if js_ok:
                    clicked2 = True
                    break
            except Exception:
                continue
        if clicked2:
            try:
                page.wait_for_timeout(600)
            except Exception:
                pass
            break

        # 아직 다이얼로그 로딩 중이면 잠깐 대기
        time.sleep(0.3)

    print(f"[publish] second click clicked2={clicked2}")

    if not clicked2:
        # 2차 버튼이 안 나타나는 UI도 있어서, 여기서 바로 성공/실패 단정하지 않고 다음 전환 감지로 넘어감
        pass

    # 게시 완료 전환 감지: URL 변화 or '작성완료/발행완료' 텍스트 or blog.naver.com 포스트 화면 등
    done_selectors = [
        "text=발행이 완료",
        "text=발행 완료",
        "text=작성 완료",
        "text=게시",
    ]

    while time.time() < deadline:
        try:
            u = page.url or ""
            # 작성 페이지는 대개 write/Redirect=Write 류, 완료 후에는 /PostView.naver 또는 blog.naver.com/*/ 등으로 전환되는 경향
            if "PostView" in u or ("blog.naver.com" in u and "Redirect=Write" not in u and "write" not in u.lower()):
                return {"ok": True, "reason": "url_changed", "url": u}
        except Exception:
            pass

        for sel in done_selectors:
            try:
                loc = page.locator(sel).first
                if loc.count() > 0 and loc.is_visible():
                    return {"ok": True, "reason": "done_text", "url": page.url}
            except Exception:
                continue

        time.sleep(0.5)

    return {"ok": False, "reason": "publish_timeout", "url": page.url}


def _init_db(db_path: str = DB_PATH) -> None:
    Path(db_path).parent.mkdir(parents=True, exist_ok=True)
    with sqlite3.connect(db_path) as con:
        con.execute(
            """
            CREATE TABLE IF NOT EXISTS post_map (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                tistory_post_id TEXT NOT NULL,
                naver_written_at TEXT NOT NULL,
                tistory_url TEXT,
                created_at TEXT NOT NULL DEFAULT (strftime('%Y%m%d%H%M%S','now')),
                UNIQUE(tistory_post_id, naver_written_at)
            );
            """
        )
        con.execute("CREATE INDEX IF NOT EXISTS ix_post_map_written_at ON post_map(naver_written_at);")


def _get_recent_records(limit: int = 10, db_path: str = DB_PATH) -> list[dict]:
    _init_db(db_path)
    with sqlite3.connect(db_path) as con:
        con.row_factory = sqlite3.Row
        rows = con.execute(
            """
            SELECT tistory_post_id, naver_written_at, tistory_url, created_at
            FROM post_map
            ORDER BY naver_written_at DESC
            LIMIT ?;
            """,
            (limit,),
        ).fetchall()
    return [dict(r) for r in rows]


def _save_record(*, tistory_post_id: str, naver_written_at: str, tistory_url: str, db_path: str = DB_PATH) -> None:
    _init_db(db_path)
    with sqlite3.connect(db_path) as con:
        con.execute(
            """
            INSERT OR IGNORE INTO post_map (tistory_post_id, naver_written_at, tistory_url, created_at)
            VALUES (?, ?, ?, ?);
            """,
            (tistory_post_id, naver_written_at, tistory_url, datetime.now().strftime("%Y%m%d%H%M%S")),
        )


def _tistory_post_id_from_url(url: str) -> str:
    """티스토리 URL에서 포스팅 번호를 추출합니다. (예: .../4 -> '4')

    숫자가 없으면 path 전체를 식별자로 사용합니다.
    """
    try:
        from urllib.parse import urlparse
    except Exception:
        urlparse = None

    if urlparse is None:
        return (url or "").strip() or "index"

    p = urlparse(url)
    path = (p.path or "").strip("/")
    if not path:
        return "index"
    last = path.split("/")[-1]
    if last.isdigit():
        return last
    return path


def _get_last_processed_post_id(db_path: str = DB_PATH) -> int:
    """DB에 저장된 마지막 처리 티스토리 포스팅 번호(INT)를 반환합니다. 없으면 0."""
    _init_db(db_path)
    with sqlite3.connect(db_path) as con:
        row = con.execute("SELECT MAX(CAST(tistory_post_id AS INTEGER)) FROM post_map").fetchone()
    try:
        return int(row[0] or 0)
    except Exception:
        return 0


def _is_already_processed(post_id: int, db_path: str = DB_PATH) -> bool:
    """해당 post_id가 DB에 이미 저장(처리완료)되어 있으면 True."""
    _init_db(db_path)
    with sqlite3.connect(db_path) as con:
        row = con.execute(
            "SELECT 1 FROM post_map WHERE tistory_post_id = ? LIMIT 1;",
            (str(post_id),),
        ).fetchone()
    return row is not None


def _build_tistory_url_for_post_id(post_id: int) -> str:
    # 현재는 같은 blog 도메인에서 숫자 포스팅 번호 방식을 가정
    return f"https://billcorea.tistory.com/{post_id}"


def _fetch_next_valid_post(*, start_from: int, max_tries: int = 50, out_dir: str = r".\\out_tistory_tmp"):
    """start_from 다음 번호부터 티스토리 글을 순차 탐색하여 '정상 글' 1개를 반환

    정상 기준(최소): title/content_text 중 하나라도 있고, content_html이 비어있지 않음(스킨에 따라 최소 내용)
    """
    pid = start_from
    last_err = None
    for _ in range(max_tries):
        pid += 1

        # 이미 처리된 번호면 스킵
        try:
            if _is_already_processed(pid):
                print(f"[flow] skip already-processed post_id={pid}")
                continue
        except Exception as e:
            # DB 확인 실패는 치명적이진 않게 처리(그래도 진행)
            print(f"[flow] warn: processed-check failed post_id={pid} err={e}")

        url = _build_tistory_url_for_post_id(pid)
        try:
            post = readTistory(url=url, out=out_dir, no_images=False, save_raw_html=False)
            # 간단한 정상성 체크
            if post and (post.content_html and post.content_html.strip()) and (post.title and post.title.strip() and post.title != "(no title)"):
                return post

            # 비정상 글 -> 다음 번호로 계속
            last_err = f"invalid_content pid={pid} url={url}"
            print(f"[flow] skip invalid post_id={pid} url={url}")
        except Exception as e:
            last_err = f"fetch_failed pid={pid} url={url} err={e}"
            print(f"[flow] skip fetch-failed post_id={pid} url={url} err={e}")
            continue

    raise RuntimeError(f"다음 정상 포스팅을 찾지 못했습니다. start_from={start_from} last_err={last_err}")


def main():
    with sync_playwright() as p:
        # 시작 시 최근 저장 기록 출력
        recent = _get_recent_records(limit=5)
        if recent:
            print("[db] 최근 저장 기록(최신 10개):")
            for r in recent:
                print(f"  - tistory_post_id={r.get('tistory_post_id')} naver_written_at={r.get('naver_written_at')} url={r.get('tistory_url')}")
        else:
            print("[db] 저장 기록 없음")

        # 반복 처리 개수(기본 3). 환경변수 NAVER_MAX_POSTS 로 조절
        max_posts = 3

        out_dir = r".\\out_tistory_tmp"

        browser = p.chromium.launch(
            headless=False,
            args=["--disable-blink-features=AutomationControlled"]
        )
        context = browser.new_context()
        page = context.new_page()

        # 1️⃣ 네이버 로그인 페이지 이동 + 로딩 완료 자동 대기 (1회만 수행)
        resp = page.goto("https://nid.naver.com/nidlogin.login", wait_until="domcontentloaded")
        try:
            status = resp.status if resp else None
        except Exception:
            status = None
        print(f"[naver] login goto status={status} url={page.url}")

        # 자동 로그인(옵션): 환경변수로 주입
        # - NAVER_AUTO_LOGIN=1 이고, N_ACCOUNT_ID / N_ACCOUNT_PW 가 있으면 자동 입력 및 클릭
        auto_login = os.getenv("NAVER_AUTO_LOGIN", "").strip() == "1"
        n_id = os.getenv("N_ACCOUNT_ID", "").strip()
        n_pw = os.getenv("N_ACCOUNT_PW", "").strip()

        wait_for_naver_login_page_ready(page, timeout_ms=30000)
        if auto_login and n_id and n_pw:
            print("[naver] auto login: trying to fill id/pw and click login")
            perform_naver_login(page, user_id=n_id, user_pw=n_pw, timeout_ms=30000)
        else:
            print("👉 네이버 로그인 진행 중... (수동 입력/2FA 가능) 로그인 완료 감지까지 자동 대기합니다")

        ok = wait_for_naver_login_complete(page, timeout_ms=300000)
        if not ok:
            raise RuntimeError("네이버 로그인 완료를 시간 내에 감지하지 못했습니다. (캡차/2FA/보호조치 여부 확인)")

        print("[naver] login detected")

        for i in range(max_posts):
            # ✅ DB 기준 다음 포스팅 가져오기
            last_id = _get_last_processed_post_id()
            print(f"[flow] cycle={i+1}/{max_posts} last_processed_tistory_post_id={last_id}")

            # 매 사이클마다 out_dir 정리(이전 이미지 잔재 방지)
            cleared = _clear_out_dir_images(out_dir)
            print(f"[flow] cleared_out_dir_images={cleared}")

            post = _fetch_next_valid_post(start_from=last_id, max_tries=20, out_dir=out_dir)
            print(f"[flow] picked_next_post_id={_tistory_post_id_from_url(post.url)} title={post.title}")

            # 2️⃣ 섹션 홈으로 이동 -> '글쓰기' 클릭 -> 글쓰기 화면 진입(대기 포함)
            write_page = goto_blog_section_and_open_write(page, timeout_ms=45000)
            if write_page is not page:
                page = write_page

            # 글쓰기 페이지는 iframe 로딩이 더 중요해서 networkidle은 보조로만
            try:
                page.wait_for_load_state("networkidle", timeout=15000)
            except Exception:
                pass
            time.sleep(1)

            # 3️⃣ iframe 탐색
            main_frame = find_main_frame(page)
            editor_frame = find_editor_frame(main_frame)

            content = post.content_html
            content = re.sub('inventory', '', content)
            content = re.sub('반응형', '', content)
            content = re.sub('System - START', '', content)
            content = re.sub('System - END', '', content)
            content = re.sub('PostListinCategory - START', '', content)
            content = re.sub('PostListinCategory - END', '', content)

            title = post.title
            tistory_post_id = _tistory_post_id_from_url(post.url)

            content += '''
            ***이 글은 Tistory(티스토리)에 게시 되었던 글들을 네이버블로그로 이전 작업중에 발생 되는 게시글 입니다.
            ***이 글을 작성하는 {0} 시점에는 다른 세상이 되었을 수도 있습니다.  
            
            #블로그글이전 #티스토리 #네이버 #billcorea
            '''.format(datetime.now().strftime('%Y-%m-%d %H:%M'))

            # 4️⃣ 제목 + 본문 입력
            set_body(editor_frame, content, base_url=post.url, page=page, mode="auto")
            focus_title_strong(page, title)

            # 이미지 개수와 무관하게, 다음 단계(업로드/발행)를 막는 도움말/가이드 오버레이를 선제적으로 닫기
            try:
                close_help_dialog_if_present(page)
            except Exception as e:
                print(f"[help] pre-upload close failed: {e}")

            # 5️⃣ 이미지 일괄 업로드
            up = upload_images_in_batch(page, out_dir=out_dir)
            print(f"[upload] result={up}")

            # 업로드 직후 에디터가 리렌더링/포커스 이동을 하면서 상단 버튼이 잠깐 클릭 불가가 되는 경우가 있어 안정화 대기
            try:
                page.keyboard.press("Escape")
            except Exception:
                pass
            try:
                page.wait_for_timeout(3000)
            except Exception:
                time.sleep(3.0)

            # 6️⃣ 발행
            pub = publish_post(page, timeout_ms=90000)
            print(f"[publish] result={pub}")
            if not pub.get("ok"):
                raise RuntimeError(f"발행 실패: {pub}")

            # ✅ DB 저장: 티스토리 포스팅 번호 + 네이버 기록 시각(현재 시각)
            naver_written_at = datetime.now().strftime("%Y%m%d%H%M%S")
            _save_record(tistory_post_id=tistory_post_id, naver_written_at=naver_written_at, tistory_url=post.url)
            print(f"[db] saved: tistory_post_id={tistory_post_id} naver_written_at={naver_written_at}")

            # 다음 사이클로 넘어가기 전에 잠깐 안정화
            try:
                page.wait_for_timeout(1200)
            except Exception:
                pass

            print("✅ 반복 작업 완료 ... 15 초 기다리면 다음 작업 시작....")
            time.sleep(15.0)

        #input("👉 화면 확인 후 Enter 누르면 종료")

        browser.close()

if __name__ == "__main__":
    main()

 

전체 코드를 공개 합니다.   이코드는 github 의 copilot 의 노력 99%와 글쓴이의 생각 1%가 만들어낸 코드 입니다. 

 

아래 링크는 실행 영상 입니다.

https://youtube.com/shorts/rB1qHDthJm0

 

반응형

+ Recent posts