#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
키키 QnA 봇 — 스레드 · X · 레딧 질문 수집 + 자동 답변 댓글
============================================================

- 스레드: 사주/오행 계열 키워드 검색 → 지식인처럼 자연스러운 해설 댓글
- X: 일본어 여행 키워드 검색 → 친절한 여행 팁 댓글
- 레딧: 여행 서브레딧 질문 → 영어 여행 답변 (공개 API 수집)

실행하면 http://127.0.0.1:8765 대시보드가 함께 뜹니다.
config.json 의 mode 가 "dry_run"이면 초안만 만들고, "auto"면 실제로 댓글을 답니다.

주의: 이 파일은 윈도우 PC에서 더블클릭(start_qna_bot.bat)으로 돌리는 것을 전제로 작성됐습니다.
"""

from __future__ import annotations

import argparse
import base64
import concurrent.futures
import html as html_lib
import inspect
import json
import os
import queue
import random
import re
import shutil
import sqlite3
import sys
import threading
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request
import webbrowser
from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

try:  # 한글 콘솔 깨짐 방지
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    sys.stderr.reconfigure(encoding="utf-8", errors="replace")
except Exception:
    pass

BOT_DIR = Path(__file__).resolve().parent
KST = timezone(timedelta(hours=9))
APP_NAME = "키키 QnA 봇"
VERSION = "1.1.1"

# ── Gemini ──────────────────────────────────────────────────────────────
# config.json을 손으로 고치지 않아도 항상 최신 모델로 돌게, 최신 모델 목록을 코드에 박아 둔다.
# (config에 예전 모델이 적혀 있어도 아래 목록을 먼저 시도한다)
GEMINI_LATEST_MODELS = [
    "gemini-3.8-flash",
    "gemini-3.6-flash",
    "gemini-3.5-flash-lite",
    "gemini-3.1-flash-lite",
]
GEMINI_ALIAS_MODELS = ["gemini-flash-latest", "gemini-flash-lite-latest"]
LEGACY_MODEL_RE = re.compile(r"^gemini-(1\.|2\.0)", re.I)  # 서비스 종료된 구모델
MIN_OUTPUT_TOKENS = 2048   # thinking 토큰 때문에 답변이 잘리던 문제 → 최소 2048
DEFAULT_OUTPUT_TOKENS = 2048
MAX_OUTPUT_TOKENS = 8192

# ── 스레드 화면(DOM) ─────────────────────────────────────────────────────
# Threads는 아이콘 버튼의 aria-label로만 안정적으로 찾을 수 있다(한/영/일 UI 모두 대응).
THREADS_REPLY_LABELS = ["답글", "댓글", "Reply", "Reply to", "Comment", "返信", "コメント", "回复"]
THREADS_EXPAND_LABELS = ["작성창 확장", "확장", "Expand composer", "Expand"]
THREADS_POST_BUTTONS = ["게시", "Post", "投稿", "发布"]
THREADS_ERROR_TEXTS = (
    "문제가 발생했습니다",
    "Something went wrong",
    "Sorry, something went wrong",
    "ページを表示できません",
    "다시 시도",
    "Try again",
)
THREADS_POPUP_BUTTONS = ["나중에", "닫기", "Not now", "Close", "Dismiss", "취소", "Cancel"]
# 작성 상자(Meta Lexical 리치 텍스트 에디터) 찾기 — 실제 화면 로그로 확인한 순서
# 한국어 UI는 컬럼 컨테이너가 'Column body'가 아니라 '칼럼 본문'이다.
THREADS_COMPOSER_DIRECT = (
    'div[contenteditable="true"][aria-label*="텍스트 필드가 비어 있습니다"]',
    'div[contenteditable="true"][aria-label*="Empty text field"]',
    'div[contenteditable="true"][aria-label*="テキストフィールドは空です"]',
)
THREADS_COMPOSER_COLUMN_SCOPES = (
    '[aria-label="칼럼 본문"]',
    '[aria-label="컬럼 본문"]',
    '[aria-label="Column body"]',
    '[aria-label="コラム本文"]',
)
THREADS_COMPOSER_FALLBACK = (
    'div[role="dialog"] [contenteditable="true"]',
    'main [contenteditable="true"]',
    'div[contenteditable="true"][role="textbox"]',
    '[contenteditable="true"]',
)

UA_DESKTOP = (
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
)

PLATFORM_LABEL = {"threads": "스레드", "x": "X", "reddit": "레딧"}
STATUS_LABEL = {
    "pending": "대기",
    "draft": "초안",
    "posted": "발송완료",
    "unverified": "발송(확인필요)",
    "skipped": "건너뜀",
    "failed": "실패",
}

DEFAULT_CONFIG = {
    "mode": "dry_run",
    "config_version": 2,
    "scan_interval_sec": 180,
    "max_per_hour": {"threads": 3, "x": 3, "reddit": 3},
    "max_per_day": {"threads": 20, "x": 20, "reddit": 20},
    "reply_delay_sec": [180, 420],
    "answer_limit_per_scan": 3,
    "max_item_age_hours": 36,
    "use_knowledge_pack": True,
    "knowledge_pack": "qna_knowledge_pack.json",
    "gemini_api_key": "",
    "gemini_model": "gemini-3.8-flash",
    "gemini_fallback_models": ["gemini-3.6-flash", "gemini-3.5-flash-lite", "gemini-3.1-flash-lite"],
    "gemini_max_output_tokens": 2048,
    "account_mode": "rotation",
    "pinned_account": "",
    "threads": {
        "enabled": True,
        "lang": "ko",
        "keywords": ["사주", "오행", "신년운세", "일주", "용신"],
        "max_per_scan": 12,
        "scrolls": 3,
        "search_url": "https://www.threads.net/search?q={q}&serp_type=default",
    },
    "x": {
        "enabled": True,
        "lang": "ja",
        "keywords": ["韓国旅行", "ワウパス", "T-money", "仁川空港"],
        "max_per_scan": 12,
        "scrolls": 3,
        "search_url": "https://x.com/search?q={q}&f=live",
    },
    "reddit": {
        "enabled": True,
        "lang": "en",
        "subreddits": ["koreatravel", "Seoul", "solotravel"],
        "max_per_scan": 15,
        "max_age_hours": 48,
        "api": "https://arctic-shift.photon-reddit.com/api/posts/search?subreddit={sub}&limit={limit}&sort=desc",
        "browser_fallback": True,
    },
    "accounts": [
        {
            "id": "threads_1",
            "platform": "threads",
            "label": "스레드 계정 1",
            "profile_dir": "profiles/threads_1",
            "enabled": True,
        },
        {
            "id": "x_1",
            "platform": "x",
            "label": "X 계정 1",
            "profile_dir": "profiles/x_1",
            "enabled": True,
        },
        {
            "id": "reddit_1",
            "platform": "reddit",
            "label": "레딧 계정 1",
            "profile_dir": "profiles/reddit_1",
            "enabled": True,
        },
    ],
    "browser": {"channel": "auto", "headless": True, "slow_mo": 0},
    "ui": {"host": "127.0.0.1", "port": 8765, "open": True},
}


# ---------------------------------------------------------------------------
# 공통 유틸
# ---------------------------------------------------------------------------
class LogBus:
    """콘솔 + 파일 + 대시보드용 최근 로그 버퍼."""

    def __init__(self, path: Path, maxlen: int = 500):
        self.path = path
        self.lock = threading.Lock()
        self.lines: list[dict] = []
        self.maxlen = maxlen
        self.path.parent.mkdir(parents=True, exist_ok=True)

    def add(self, msg: str, level: str = "info"):
        now = datetime.now(KST)
        entry = {
            "t": now.strftime("%H:%M:%S"),
            "level": level,
            "msg": str(msg)[:1200],
        }
        with self.lock:
            self.lines.append(entry)
            if len(self.lines) > self.maxlen:
                del self.lines[: len(self.lines) - self.maxlen]
        prefix = {"info": "·", "ok": "✓", "warn": "!", "error": "✗", "post": "▶"}.get(level, "·")
        try:
            print(f"[{entry['t']}] {prefix} {entry['msg']}", flush=True)
        except Exception:
            pass
        try:
            with open(self.path, "a", encoding="utf-8") as f:
                f.write(f"{now.isoformat(timespec='seconds')} [{level}] {msg}\n")
        except Exception:
            pass

    def snapshot(self, limit: int = 120) -> list[dict]:
        with self.lock:
            return list(self.lines[-limit:])


LOG = LogBus(BOT_DIR / "logs" / "bot.log")


def now_iso() -> str:
    return datetime.now(KST).isoformat(timespec="seconds")


def ts_to_text(ts) -> str:
    try:
        return datetime.fromtimestamp(float(ts), KST).strftime("%m-%d %H:%M")
    except Exception:
        return ""


def clean_text(s: str, limit: int = 1500) -> str:
    s = html_lib.unescape(s or "")
    s = re.sub(r"<br\s*/?>", "\n", s, flags=re.I)
    s = re.sub(r"<[^>]+>", " ", s)
    s = re.sub(r"[ \t]+", " ", s)
    s = re.sub(r"\n{3,}", "\n\n", s)
    s = s.strip()
    return s[:limit]


def load_json(path: Path, default):
    try:
        with open(path, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception:
        return default


def save_json(path: Path, data):
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_suffix(path.suffix + ".tmp")
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    os.replace(tmp, path)


def deep_merge(base: dict, override: dict) -> dict:
    out = dict(base)
    for k, v in (override or {}).items():
        if isinstance(v, dict) and isinstance(out.get(k), dict):
            out[k] = deep_merge(out[k], v)
        else:
            out[k] = v
    return out


def http_get(url: str, timeout: int = 25, headers: dict | None = None) -> tuple[int, bytes]:
    h = {"User-Agent": UA_DESKTOP, "Accept": "*/*", "Accept-Language": "en-US,en;q=0.9,ko;q=0.8,ja;q=0.7"}
    if headers:
        h.update(headers)
    req = urllib.request.Request(url, headers=h)
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return r.status, r.read()
    except urllib.error.HTTPError as e:
        try:
            body = e.read()
        except Exception:
            body = b""
        return e.code, body


def http_post_json(url: str, payload: dict, timeout: int = 60, headers: dict | None = None) -> tuple[int, dict]:
    h = {"Content-Type": "application/json", "User-Agent": UA_DESKTOP}
    if headers:
        h.update(headers)
    data = json.dumps(payload).encode("utf-8")
    req = urllib.request.Request(url, data=data, headers=h, method="POST")
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return r.status, json.loads(r.read().decode("utf-8", "replace"))
    except urllib.error.HTTPError as e:
        try:
            return e.code, json.loads(e.read().decode("utf-8", "replace"))
        except Exception:
            return e.code, {}
    except Exception as e:
        return 0, {"error": str(e)}


# ---------------------------------------------------------------------------
# 설정
# ---------------------------------------------------------------------------
class Config:
    # config.json을 예전 그대로 두고 실행해도 최신 기본값으로 돌아가게 하는 1회 보정 목록
    LEGACY_GEMINI_MODELS = {
        "gemini-2.0-flash",
        "gemini-2.0-flash-001",
        "gemini-2.0-flash-lite",
        "gemini-1.5-flash",
        "gemini-1.5-flash-latest",
    }

    def __init__(self, path: Path):
        self.path = path
        self.lock = threading.RLock()
        raw = load_json(path, {})
        if not raw:
            save_json(path, DEFAULT_CONFIG)
            raw = {}
        self.data = deep_merge(DEFAULT_CONFIG, raw)
        self._migrate(raw)
        self._normalize()

    def _migrate(self, raw: dict):
        """예전 config.json(모델 gemini-2.0-flash, 스캔 600초, 답변 10건)을 그대로 두고
        실행해도 새 기본값으로 바꿔 준다. 사용자가 직접 고친 값이 \"예전 기본값과 똑같을 때만\"
        바꾸고, 원본은 config.json.bak 으로 남긴다."""
        d = self.data
        try:
            version = int(raw.get("config_version") or 1)
        except Exception:
            version = 1
        if version >= 2:
            # 버전만 최신이어도 토큰 하한은 항상 지킨다
            try:
                d["gemini_max_output_tokens"] = max(MIN_OUTPUT_TOKENS, int(d.get("gemini_max_output_tokens") or DEFAULT_OUTPUT_TOKENS))
            except Exception:
                d["gemini_max_output_tokens"] = DEFAULT_OUTPUT_TOKENS
            return
        changed: list[str] = []
        if str(d.get("gemini_model") or "").strip().lower() in self.LEGACY_GEMINI_MODELS:
            d["gemini_model"] = DEFAULT_CONFIG["gemini_model"]
            changed.append("gemini_model")
        fb = [str(m or "").strip().lower() for m in (d.get("gemini_fallback_models") or [])]
        if not fb or all(m in self.LEGACY_GEMINI_MODELS for m in fb):
            d["gemini_fallback_models"] = list(DEFAULT_CONFIG["gemini_fallback_models"])
            changed.append("gemini_fallback_models")
        try:
            if int(d.get("answer_limit_per_scan") or 0) >= 10:
                d["answer_limit_per_scan"] = DEFAULT_CONFIG["answer_limit_per_scan"]
                changed.append("answer_limit_per_scan")
        except Exception:
            pass
        try:
            if int(d.get("scan_interval_sec") or 0) >= 600:
                d["scan_interval_sec"] = DEFAULT_CONFIG["scan_interval_sec"]
                changed.append("scan_interval_sec")
        except Exception:
            pass
        try:
            d["gemini_max_output_tokens"] = max(MIN_OUTPUT_TOKENS, int(d.get("gemini_max_output_tokens") or DEFAULT_OUTPUT_TOKENS))
        except Exception:
            d["gemini_max_output_tokens"] = DEFAULT_OUTPUT_TOKENS
        d["config_version"] = 2
        if changed and raw:
            try:
                shutil.copy2(self.path, self.path.with_name(self.path.name + ".bak"))
            except Exception:
                pass
            LOG.add(f"config.json 자동 갱신: {', '.join(changed)} (원본은 config.json.bak)", "ok")
        save_json(self.path, d)

    def _normalize(self):
        d = self.data
        if d.get("mode") not in ("dry_run", "auto"):
            d["mode"] = "dry_run"
        # 계정: id/platform/profile_dir 보정
        seen_ids = set()
        fixed = []
        for acc in d.get("accounts") or []:
            if not isinstance(acc, dict):
                continue
            platform = str(acc.get("platform", "")).lower()
            if platform not in ("threads", "x", "reddit"):
                continue
            acc_id = re.sub(r"[^a-z0-9_\-]", "", str(acc.get("id") or "")).lower()
            if not acc_id:
                acc_id = f"{platform}_1"
                n = 1
                while acc_id in seen_ids:
                    n += 1
                    acc_id = f"{platform}_{n}"
            if acc_id in seen_ids:
                continue
            seen_ids.add(acc_id)
            acc["id"] = acc_id
            acc.setdefault("label", f"{PLATFORM_LABEL[platform]} {acc_id}")
            acc.setdefault("profile_dir", f"profiles/{acc_id}")
            acc["enabled"] = bool(acc.get("enabled", True))
            fixed.append({k: acc[k] for k in ("id", "platform", "label", "profile_dir", "enabled")})
        d["accounts"] = fixed
        if d.get("account_mode") not in ("rotation", "single"):
            d["account_mode"] = "rotation"
        rng = d.get("reply_delay_sec") or [180, 420]
        if not (isinstance(rng, list) and len(rng) == 2):
            rng = [180, 420]
        d["reply_delay_sec"] = [int(rng[0]), int(rng[1])]

    def __getitem__(self, key):
        return self.data[key]

    def get(self, key, default=None):
        return self.data.get(key, default)

    def save(self):
        with self.lock:
            save_json(self.path, self.data)

    def set(self, key, value, save: bool = True):
        with self.lock:
            self.data[key] = value
            if save:
                save_json(self.path, self.data)

    def accounts(self, platform: str | None = None) -> list[dict]:
        with self.lock:
            accs = list(self.data.get("accounts") or [])
        if platform:
            accs = [a for a in accs if a["platform"] == platform]
        return accs

    def account(self, acc_id: str) -> dict | None:
        for a in self.accounts():
            if a["id"] == acc_id:
                return a
        return None

    def add_account(self, platform: str, label: str = "") -> dict:
        platform = platform.lower()
        if platform not in ("threads", "x", "reddit"):
            raise ValueError("지원하지 않는 플랫폼입니다.")
        with self.lock:
            used = {a["id"] for a in self.data["accounts"]}
            n = 1
            while f"{platform}_{n}" in used:
                n += 1
            acc = {
                "id": f"{platform}_{n}",
                "platform": platform,
                "label": label.strip() or f"{PLATFORM_LABEL[platform]} 계정 {n}",
                "profile_dir": f"profiles/{platform}_{n}",
                "enabled": True,
            }
            self.data["accounts"].append(acc)
            save_json(self.path, self.data)
            return acc

    def remove_account(self, acc_id: str) -> bool:
        with self.lock:
            before = len(self.data["accounts"])
            self.data["accounts"] = [a for a in self.data["accounts"] if a["id"] != acc_id]
            changed = len(self.data["accounts"]) != before
            if changed:
                save_json(self.path, self.data)
            return changed


# ---------------------------------------------------------------------------
# 중복 방지 / 기록 DB
# ---------------------------------------------------------------------------
class SeenDB:
    """seen.db — 한 번 본 글은 두 번 답하지 않는다(100% 중복 방지)."""

    def __init__(self, path: Path):
        path.parent.mkdir(parents=True, exist_ok=True)
        self.path = path
        self.lock = threading.RLock()
        self.conn = sqlite3.connect(str(path), check_same_thread=False)
        self.conn.row_factory = sqlite3.Row
        with self.lock:
            self.conn.executescript(
                """
                PRAGMA journal_mode=WAL;
                CREATE TABLE IF NOT EXISTS items(
                    id TEXT PRIMARY KEY,
                    platform TEXT NOT NULL,
                    sub TEXT DEFAULT '',
                    keyword TEXT DEFAULT '',
                    author TEXT DEFAULT '',
                    title TEXT DEFAULT '',
                    text TEXT DEFAULT '',
                    url TEXT DEFAULT '',
                    created_at TEXT DEFAULT '',
                    found_at TEXT DEFAULT '',
                    status TEXT DEFAULT 'pending',
                    answer TEXT DEFAULT '',
                    engine TEXT DEFAULT '',
                    account TEXT DEFAULT '',
                    posted_at TEXT DEFAULT '',
                    error TEXT DEFAULT ''
                );
                CREATE INDEX IF NOT EXISTS idx_items_status ON items(status);
                CREATE INDEX IF NOT EXISTS idx_items_platform ON items(platform);
                CREATE INDEX IF NOT EXISTS idx_items_posted ON items(posted_at);
                CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT);
                """
            )
            self.conn.commit()

    # --- meta ---
    def meta_get(self, key: str, default: str = "") -> str:
        with self.lock:
            row = self.conn.execute("SELECT value FROM meta WHERE key=?", (key,)).fetchone()
        return row["value"] if row else default

    def meta_set(self, key: str, value: str):
        with self.lock:
            self.conn.execute(
                "INSERT INTO meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
                (key, value),
            )
            self.conn.commit()

    # --- items ---
    def add_item(self, item: dict) -> bool:
        """새 글이면 True. 이미 본 글이면 False."""
        with self.lock:
            cur = self.conn.execute(
                """INSERT OR IGNORE INTO items
                   (id, platform, sub, keyword, author, title, text, url, created_at, found_at, status)
                   VALUES (?,?,?,?,?,?,?,?,?,?,?)""",
                (
                    item["id"],
                    item["platform"],
                    item.get("sub", ""),
                    item.get("keyword", ""),
                    item.get("author", ""),
                    item.get("title", "")[:400],
                    item.get("text", "")[:2000],
                    item.get("url", ""),
                    item.get("created_at", ""),
                    now_iso(),
                    item.get("status", "pending"),
                ),
            )
            self.conn.commit()
            return cur.rowcount > 0

    def set_answer(self, item_id: str, answer: str, engine: str):
        with self.lock:
            self.conn.execute(
                'UPDATE items SET answer=?, engine=?, status=CASE WHEN status="pending" THEN "pending" ELSE status END WHERE id=?',
                (answer, engine, item_id),
            )
            self.conn.commit()

    def mark(self, item_id: str, status: str, account: str = "", error: str = ""):
        with self.lock:
            self.conn.execute(
                "UPDATE items SET status=?, account=?, error=?, posted_at=? WHERE id=?",
                (
                    status,
                    account,
                    error[:600],
                    now_iso() if status in ("posted", "unverified") else "",
                    item_id,
                ),
            )
            self.conn.commit()

    def mark_posted(self, item_id: str, status: str, account: str, error: str = ""):
        with self.lock:
            self.conn.execute(
                "UPDATE items SET status=?, account=?, error=?, posted_at=? WHERE id=?",
                (status, account, error[:600], now_iso(), item_id),
            )
            self.conn.commit()

    def get(self, item_id: str) -> dict | None:
        with self.lock:
            row = self.conn.execute("SELECT * FROM items WHERE id=?", (item_id,)).fetchone()
        return dict(row) if row else None

    def exists(self, item_id: str) -> bool:
        with self.lock:
            row = self.conn.execute("SELECT 1 FROM items WHERE id=?", (item_id,)).fetchone()
        return row is not None

    def list(self, limit: int = 100, platform: str | None = None, status: str | None = None) -> list[dict]:
        q = "SELECT * FROM items"
        where, args = [], []
        if platform:
            where.append("platform=?")
            args.append(platform)
        if status:
            where.append("status=?")
            args.append(status)
        if where:
            q += " WHERE " + " AND ".join(where)
        q += " ORDER BY found_at DESC LIMIT ?"
        args.append(limit)
        with self.lock:
            rows = self.conn.execute(q, args).fetchall()
        return [dict(r) for r in rows]

    def missing_answers(self, limit: int = 10) -> list[dict]:
        with self.lock:
            rows = self.conn.execute(
                """SELECT * FROM items
                   WHERE (answer IS NULL OR answer='') AND status='pending'
                   ORDER BY found_at DESC LIMIT ?""",
                (limit,),
            ).fetchall()
        return [dict(r) for r in rows]

    def by_status(self, platform: str, status: str, limit: int = 10) -> list[dict]:
        with self.lock:
            rows = self.conn.execute(
                "SELECT * FROM items WHERE platform=? AND status=? ORDER BY found_at ASC LIMIT ?",
                (platform, status, limit),
            ).fetchall()
        return [dict(r) for r in rows]

    def count_since(self, platform: str, since_iso: str, statuses=("posted", "unverified")) -> int:
        marks = ",".join("?" for _ in statuses)
        with self.lock:
            row = self.conn.execute(
                f"SELECT COUNT(*) AS c FROM items WHERE platform=? AND status IN ({marks}) AND posted_at>=?",
                (platform, *statuses, since_iso),
            ).fetchone()
        return int(row["c"] if row else 0)

    def stats(self) -> dict:
        since_hour = (datetime.now(KST) - timedelta(hours=1)).isoformat(timespec="seconds")
        midnight = datetime.now(KST).replace(hour=0, minute=0, second=0, microsecond=0).isoformat(timespec="seconds")
        with self.lock:
            def one(sql, args=()):
                r = self.conn.execute(sql, args).fetchone()
                return int(r[0] if r else 0)

            return {
                "found_today": one("SELECT COUNT(*) FROM items WHERE found_at>=?", (midnight,)),
                "posted_today": one(
                    "SELECT COUNT(*) FROM items WHERE status IN ('posted','unverified') AND posted_at>=?", (midnight,)
                ),
                "posted_hour": one(
                    "SELECT COUNT(*) FROM items WHERE status IN ('posted','unverified') AND posted_at>=?", (since_hour,)
                ),
                "pending": one("SELECT COUNT(*) FROM items WHERE status IN ('pending','draft')"),
                "failed": one("SELECT COUNT(*) FROM items WHERE status='failed'"),
            }


# ---------------------------------------------------------------------------
# 답변 생성 엔진
# ---------------------------------------------------------------------------
SAJU_TOPICS = [
    ("ilju", ["일주", "일간", "일지"]),
    ("yongsin", ["용신", "희신", "기신"]),
    ("ohaeng", ["오행", "목화토금수", "상생", "상극"]),
    ("newyear", ["신년", "토정", "올해운", "내년", "2027", "2026"]),
    ("gunghap", ["궁합", "연애운", "결혼"]),
    ("daeun", ["대운", "세운", "운의 흐름"]),
]

# 처음 여행 계획처럼 두루 해당하는 질문에만 '일반' 답변을 쓴다
BROAD_ASK = (
    "first time", "first trip", "first visit", "tips", "advice", "itinerary",
    "recommend", "suggest", "plan", "where to stay", "things to do", "days in",
)

TRAVEL_TOPICS = [
    ("wowpass", ["ワウパス", "wowpass", "wow pass"]),
    ("tmoney", ["t-money", "tmoney", "t money", "交通カード", "교통카드"]),
    ("airport", ["仁川空港", "인천공항", "incheon", "arex", "空港鉄道", "limousine", "공항버스"]),
    ("arrival", ["k-eta", "ケータ", "arrival card", "입국", "세관", "customs", "visa"]),
    ("sim", ["esim", "sim", "유심", "wifi", "wi-fi", "ポケットwifi", "데이터"]),
    ("money", ["両替", "환전", "exchange", "atm", "cash", "현금", "card"]),
    ("rail", ["korail", "ktx", "srt", "youth pass", "rail pass", "train", "기차", "青春パス", "鉄道"]),
    ("attraction", ["palace", "tower", "lotte world", "theme park", "museum", "hanok", "attraction", "観光", "경복궁"]),
    ("family", ["stroller", "kids", "child", "baby", "toddler", "family", "아이", "子供", "ベビー"]),
    ("reserve", ["reservation", "anniversary", "birthday", "date night", "기념일", "예약", "記念日"]),
    ("food", ["食事", "グルメ", "food", "restaurant", "맛집", "vegan", "halal"]),
    ("solo", ["一人旅", "ソロ", "solo", "alone", "혼자"]),
    ("weather", ["겨울", "寒い", "winter", "december", "january", "날씨", "weather", "雪"]),
]

# --- 스레드(사주) 답변 템플릿: 링크·홍보·해시태그 없이, 지식인처럼 ---
SAJU_TEMPLATES = {
    "ilju": [
        "일주는 그 사람이 세상을 대하는 기본값이 담긴 자리라서, 같은 오행이라도 일간이 뭐냐에 따라 말투나 돈 쓰는 방식이 확 달라져요. 갑목이면 뻗어나가려는 쪽으로 힘이 쓰이고, 기토면 감싸 안는 쪽으로 쓰이거든요. 글에 써주신 고민도 그 결이랑 닿아 있는 것 같은데, 생년월일시 알려주시면 일간이랑 월지 관계까지 같이 볼게요.",
        "저는 사주 볼 때 일주부터 보는데, 세상이랑 부딪히는 방식이 거기 다 담겨 있더라구요. 같은 일간이어도 일지가 충을 받았는지 합이 걸렸는지에 따라 사람이 완전 달라 보여요. 지금 겪으시는 일도 그런 구조가 깔려 있을 가능성이 커 보이는데, 태어난 시간까지 알려주시면 더 정확하게 짚어볼 수 있어요.",
        "일주를 보면 겉으로 보이는 나랑 실제로 움직이는 나가 얼마나 다른지가 드러나요. 특히 일지에 뭐가 앉아 있냐가 사람 사귀는 속도를 결정하는 경우가 많더라구요. 말씀하신 부분도 그 속도 차이에서 오는 피로일 수 있어서, 생년월일시 주시면 그 부분만 따로 봐드릴게요.",
    ],
    "ohaeng": [
        "오행은 재료 다섯 개가 아니라 서로 밀고 당기는 관계로 봐야 해요. 목이 많다고 좋은 게 아니라 그 목을 받아줄 화가 있는지, 금이 과하게 자르고 있지는 않은지가 실제 체감을 좌우하거든요. 글에서 느껴지는 답답함도 특정 오행이 과해서 생긴 막힘일 수 있어서, 여덟 글자 알려주시면 어느 쪽이 과한지 짚어드릴게요.",
        "오행 얘기할 때 많이 놓치는 게 계절이에요. 같은 목이라도 봄의 목이랑 겨울의 목은 완전히 다르게 움직이거든요. 그래서 개수만 세면 성향이 잘 안 보이는데, 태어난 달이랑 시간까지 알려주시면 지금 고민이 어느 오행 문제인지 더 정확히 볼 수 있어요.",
        "상생상극은 좋고 나쁨이 아니라 흐름의 방향이에요. 극이 있어야 일이 굴러가고, 생이 있어야 오래 가거든요. 지금 힘드신 게 아마 극만 걸리고 생이 부족한 구조일 수 있는데, 생년월일시 주시면 그 흐름을 어떻게 풀어낼지 같이 보겠습니다.",
    ],
    "yongsin": [
        "용신은 부족한 글자를 채우는 것보다, 사주가 막혔을 때 숨통을 트여주는 역할에 가까워요. 재성이 센데 신약하면 비겁이, 신강하면 관성이 답이 되는 식이거든요. 글만 봐서는 어느 쪽인지 단정하기 어렵고 여덟 글자랑 대운을 같이 봐야 하는데, 생년월일시 알려주시면 용신이랑 지금 대운 관계까지 짚어볼게요.",
        "용신 찾는 순서는 보통 신강신약 보고, 병을 찾고, 그다음 약을 찾는 거예요. 병이 뭔지 알아야 약이 보이거든요. 그래서 사람마다 다르고 같은 사람도 대운에 따라 쓰는 글자가 달라지는데, 지금 고민도 대운에서 병이 생긴 경우일 수 있어요.",
        "용신을 좋은 오행 정도로만 이해하시는 분들이 많은데, 실제로는 이 사주가 제 기능을 하게 만드는 열쇠에 가까워요. 그래서 용신이 금이라고 무조건 금 관련 일을 하라는 뜻은 아니에요. 원국이랑 대운 같이 놓고 봐야 하는 부분이라, 생년월일시 주시면 그 열쇠가 어디 있는지 같이 찾아볼게요.",
    ],
    "newyear": [
        "신년운세는 그해에 들어오는 세운이 내 사주의 어느 자리랑 부딪히거나 합하는지를 보는 거예요. 그래서 같은 해라도 사람마다 길흉이 완전히 갈리거든요. 궁금해하신 부분도 세운이 월지나 일지에 닿는지에 따라 답이 달라져서, 생년월일시 알려주시면 내년 흐름을 월별로 짚어드릴게요.",
        "세운은 큰 파도고 월운은 그 달의 물결이에요. 큰 파도가 좋아도 배가 약하면 흔들리고 반대도 마찬가지거든요. 그래서 신년운세만 보고 결정하기보다 원국 강약을 같이 보는 게 안전한데, 태어난 연월일시 주시면 내년에 조심할 달이랑 밀어붙일 달을 나눠서 알려드릴게요.",
        "새해 운세는 뭐가 들어오는지보다 내가 그걸 받아낼 수 있는지를 먼저 봐요. 세운이 재성이라고 해도 신약하면 돈이 아니라 걱정으로 들어오는 경우가 흔하거든요. 지금 고민도 그 지점일 수 있어서, 사주 여덟 글자 알려주시면 더 구체적으로 설명드릴게요.",
    ],
    "gunghap": [
        "궁합은 두 사람 사주를 붙여놓고 서로 부족한 걸 채워주는지를 보는 작업이에요. 일지가 합을 이루면 생활 리듬이 잘 맞고, 충이면 같은 일로 자주 부딪히더라구요. 다만 충이 있다고 무조건 나쁜 건 아니고 대운에서 풀리는 시점이 있어서, 두 분 생년월일시 알려주시면 그 부분까지 같이 볼게요.",
        "연애운은 배우자 자리인 일지랑 재성·관성 상태를 같이 봐요. 상대가 어떤 결을 가진 사람인지, 인연이 언제 들어오는지는 대운이랑 세운에서 드러나는 경우가 많거든요. 글에 써주신 고민도 그 시기랑 맞물려 있을 수 있어서, 생년월일시 주시면 시기 중심으로 짚어드릴게요.",
        "궁합에서 제일 많이 오해되는 게 같은 오행이면 좋다는 생각이에요. 오히려 서로 다른 오행이 필요한 걸 채워줄 때 오래 가더라구요. 두 분 사주에서 뭐가 비어 있고 뭐가 넘치는지가 핵심이라, 생년월일시 알려주시면 그 지점부터 풀어볼게요.",
    ],
    "daeun": [
        "대운은 10년 단위로 바뀌는 큰 흐름이고 세운은 그 안의 1년짜리 변수예요. 지금 힘드시면 대운이 바뀌는 시점인지부터 확인해보는 게 좋아요. 대운이 교체될 때 환경이 통째로 흔들리는 경우가 많아서 그 시기를 어떻게 쓰느냐가 오래 가거든요. 생년월일시 알려주시면 지금 대운이랑 다음 대운 결을 비교해드릴게요.",
        "운은 좋고 나쁨보다 때의 문제인 것 같아요. 같은 일도 대운이 받쳐줄 때 하면 수월하고 아닐 때 하면 두 배로 힘이 들거든요. 지금 고민도 시기를 잘못 잡은 걸 수 있어서, 태어난 연월일시 주시면 지금이 밀어붙일 때인지 정비할 때인지 봐드릴게요.",
        "대운 볼 때는 뭐가 들어오는지랑 내 원국이 그걸 감당하는지를 같이 봐요. 감당 못 하는 대운은 기회처럼 와도 부담으로 남는 경우가 많더라구요. 지금 고민도 그런 구조일 수 있어서, 사주랑 대운 같이 놓고 보고 싶으시면 생년월일시 알려주세요.",
    ],
    "general": [
        "사주는 정답을 맞히는 게 아니라 타고난 결을 어떻게 쓰느냐를 같이 보는 쪽에 가까워요. 그래서 같은 고민이라도 원국 강약이랑 지금 대운에 따라 조언이 달라지거든요. 글만으로는 단정하기 어렵지만 방향은 잡아드릴 수 있으니, 생년월일시 알려주시면 그 부분부터 볼게요.",
        "명리에서 중요한 건 뭐가 부족한가보다 뭐가 과한가예요. 과한 건 결국 병이 되고, 병이 있으면 같은 실수를 반복하게 되더라구요. 쓰신 글 보면 그 과함이 어디서 오는지가 핵심으로 보이는데, 태어난 연월일과 시간 주시면 더 정확히 설명드릴게요.",
        "사주 상담할 때 저는 성향보다 리듬을 먼저 봐요. 언제 힘이 들어오고 언제 빠지는지 알면 같은 노력으로도 결과가 달라지거든요. 지금 겪으시는 일도 그 리듬을 놓쳐서 생긴 피로일 수 있어서, 생년월일시 알려주시면 지금이 어떤 구간인지 같이 보겠습니다.",
    ],
}

# --- X(일본어 여행) 템플릿 ---
TRAVEL_JP_TEMPLATES = {
    "wowpass": [
        "ワウパスは空港の機械ですぐ作れますよ〜。両替もT-moneyも1枚で済むので、最初にこれだけ押さえとけば移動はラクかも。ちなみに残高の払い戻しは手数料かかるので、少額から入れるのがおすすめです。",
        "ワウパス、駅の機械より空港の方が空いてて作りやすいですよ。パスポートが必要なので荷物から出すの忘れずに〜。チャージはコンビニでもできるので、足りなくなったらその場で足せばOKです。",
        "ワウパス作るなら、両替は全部空港でせずに必要分だけの方がいいかも。カードの方がレート安定しますよ〜。T-moneyとしても使えるので地下鉄もバスもタクシーもほぼ対応してます。",
    ],
    "tmoney": [
        "T-moneyはコンビニで買えるので、空港で並ばなくて大丈夫ですよ〜。地下鉄もバスもタクシーもほぼこれ1枚でいけます。チャージはレジでできるので、足りなくなったらその場で足せばOK。",
        "T-money1枚で地下鉄・バス・コンビニまで済むので、最初に5000〜10000ウォンくらい入れとくと安心ですよ。空港の自販機は混むことあるので、市内のコンビニで作る方が早いかも。",
        "T-moneyはカード自体2500ウォンくらいで、チャージ式ですよ〜。改札タッチするだけで通れて、バスも乗り換え割引効くので数日滞在ならかなりお得かも。",
    ],
    "airport": [
        "仁川空港から市内ならAREXがわかりやすいですよ〜。ソウル駅まで43分くらいで、予約なしで乗れます。荷物多いなら空港バスの方がラクかもですけど、渋滞すると読めないので時間は余裕もって！",
        "仁川空港、第1と第2ターミナルがけっこう離れてるので、航空会社のターミナル先に確認しとくと安心ですよ。AREXは第2ターミナル始発なので、そっちの方が座りやすいかも。",
        "明洞方面ならAREXでソウル駅まで出て地下鉄乗り換えが早くて安いですよ〜。深夜着ならタクシー割増になるので、空港バスの最終便も見とくと安心かも。",
    ],
    "arrival": [
        "アライバルカードは機内で配られるので、ペンだけ手荷物に入れとくと安心ですよ。K-ETAがいるかは国籍で変わるので、出発前に公式サイトで確認しとくのが確実かも。",
        "入国審査、時間帯によってけっこう混むので乗り継ぎあるなら余裕もってください〜。アライバルカードは機内でもらえますけど、書き漏らすとやり直しになるのでホテルの住所メモっとくとスムーズです。",
        "税関申告は家族で1枚でOKですよ。食品持ち込むなら申告が必要なものあるので、肉製品とか果物は避けた方が無難かも。",
    ],
    "sim": [
        "eSIMを日本で設定しとくのが一番ラクですよ〜。着いたらそのまま地下鉄乗れます。空港のSIMカウンターは便が重なると混むので、時間ないなら避けた方がいいかも。",
        "eSIMは端末が対応してれば一番手軽ですよ。データ専用だと電話番号使えないので、予約で電話いるなら注意かも。ポケットWi-Fiは複数人なら安いですけど充電の手間あります。",
        "空港のSIMカウンター、着陸便が重なると並びますよ〜。時間節約したいなら日本でeSIM買っとくのがおすすめ。",
    ],
    "money": [
        "韓国はカード社会なので、現金は思ったより使いませんよ。ただ市場とか小さなお店は現金のみも多いので、3〜5万ウォンくらい持っとくと安心かも。両替は空港より市内の方がレートいいこと多いです。",
        "両替は一度に全部せず必要分だけの方が安全ですよ〜。カードはほぼどこでも使えますけど、海外手数料はカード会社で違うので確認しとくと安心かも。",
        "ATMは日本語表示に切り替えられる機械が多いですよ。海外発行カードが使えないATMもあるので、コンビニか銀行店内のATMがおすすめです。",
    ],
    "rail": [
        "Korailパスは長距離を2回以上乗るならお得ですよ〜。ソウル〜釜山とかソウル〜江陵とか。ただしパスだけでは席が確保されないので、KTXは別で座席予約が必要かも。短距離だけなら普通に切符買った方が安いです。",
        "KTXは速いですけど、ITXとか高速バスの方が同じ区間で半額くらいのことも多いですよ。週末は数日前にKorailアプリで予約しとくのが安心かも。",
        "25歳以下とか学生なら青春パス的な割引を確認してみるといいですよ〜。乗車中に身分証チェックあるので、パスポート持ってた方が安心かも。",
    ],
    "attraction": [
        "宮殿は開場直後が一番ラクですよ〜。景福宮は11時にはかなり混むので、交代式の時間に合わせて行くと得かも。近くで韓服レンタルすると入場無料になるので、結果的に安く済みます。",
        "Nソウルタワーは日の入り1時間前くらいに上がると、昼も夜景も両方見られておすすめですよ。週末はケーブルカーの列が長いので、南山シャトルバスの方が早いかも。",
        "ロッテワールドは1日がかりなので、平日+オンラインチケットがラクですよ。マジックパスは乗り物ガッツリ乗るなら元取れますけど、そうじゃなければ普通のチケットで十分かも。",
    ],
    "family": [
        "ベビーカーで地下鉄は大丈夫ですよ〜。駅にはエレベーターありますけど、出口によってはホームから遠いことも。釜山は坂と階段がきついので、そこだけタクシーがラクかも。",
        "だいたいのお店に子ども椅子ありますし、店員さんも親切なことが多いですよ。ロッテとか新世界みたいな大きいモールなら、トイレも授乳室も安心かも。",
        "子連れなら地下鉄の直通ルート沿いに泊まって、1日は予定を空けとくのがおすすめですよ。子どもは思ったより早く疲れるので。",
    ],
    "reserve": [
        "記念日なら予約した方が確実ですよ〜。キャッチテーブルってアプリで韓国のお店も予約できます。静かな店なら平日の早めの時間が狙い目かも。",
        "人気店は週末だと埋まりやすいので、3〜7日前には予約しとくのが安心ですよ。キャッチテーブルは英語表示もあるので使いやすいかも。",
        "予約なしで入るなら開店直後がラクですよ〜。記念日なら窓際とか静かな席を予約時にリクエストしとくと良いかも。",
    ],
    "food": [
        "韓国の食堂は一人でも入りやすいですよ〜。人気店は12時台が混むので、11時台か14時以降がラクかも。辛いの苦手なら「안 맵게 해주세요」って言えば調整してくれます。",
        "屋台は現金のみのとこもあるので小銭あると便利ですよ。衛生的に心配なら人が多く回ってる屋台を選ぶのが一番の目安かも。",
        "ベジタリアンとかハラルのお店、ソウルは増えてますけど地方はまだ少ないですよ〜。事前に調べとくか、駅近の大きめのお店選ぶと安心かも。",
    ],
    "solo": [
        "ソウルは一人旅しやすいですよ〜。食堂もカフェも一人客多いし、地下鉄も遅くまで動いてます。ただ週末の夜は繁華街混むので、ホテルは駅近がラクかもです。",
        "一人旅なら朝ゆっくり、昼にメイン、夜はカフェか屋台くらいのペースが疲れにくいですよ。コインロッカーが駅にたくさんあるので移動日も身軽に動けます〜。",
        "一人だとご飯の量が問題になりがちですけど、韓国は小皿多いので1品でも満足できますよ。キンパとかクッパは一人でも入りやすいのでおすすめです。",
    ],
    "weather": [
        "冬のソウルは想像以上に寒いですよ〜。ダウンとマフラーは必須で、室内は暖房きついので脱ぎ着できる服がラクかも。路面凍る日あるので滑りにくい靴で！",
        "12月〜1月は日が落ちると一気に冷えるので、観光は午前から夕方までに詰めるのがおすすめですよ。カイロと保湿クリームあるとだいぶ違います〜。",
        "3月下旬〜4月と10月ならどちらもいいですよ〜。春は黄砂と風が多め、秋は空気が澄んで涼しいかも。当日の朝にPM2.5の予報を見とくと安心です。",
    ],
    "general": [
        "韓国旅行は交通と支払いさえ押さえとけば大丈夫ですよ〜。T-money1枚あれば地下鉄もバスもコンビニもほぼ済みます。行き先決まってたら、もう少し具体的に組めますよ。",
        "初めての韓国ならソウルは地下鉄中心が一番効率いいですよ。移動時間読めるので1日3〜4か所くらいが無理なく回れるかも。気になるエリア教えてくれれば順番組みますね。",
        "韓国はキャッシュレス進んでますけど、市場とか小さなお店は現金必要なことありますよ。カードと現金両方持って、小額紙幣多めにしとくと安心かもです。",
    ],
}

# --- 레딧(영어 여행) 템플릿 ---
TRAVEL_EN_TEMPLATES = {
    "tmoney": [
        "Honestly, just grab a T-money card at any convenience store — it covers subway, buses, and most taxis. Load like 10-20k KRW to start and top up at the counter when it runs low. Pro tip: one card per person, since you tap on and off.",
        "Yeah, T-money is the move: buy it at a CU or GS25 for a couple thousand won, load cash, tap on/off. Subway fare is actually a bit cheaper than a single ticket. It works at some convenience stores too, which is handy when you're drowning in coins.",
        "You can use a contactless credit card on the Seoul subway now, but T-money still wins for buses and taxis. For a few days, load ~20k KRW and refill as needed — cash refunds on the leftover balance are annoying.",
    ],
    "airport": [
        "The AREX non-stop to Seoul Station is about 43 min and you don't need a reservation. Yeah, it's the easiest option unless your hotel is deep in Gangnam. Airport buses are comfy but sit in traffic, so leave buffer if you're on a schedule.",
        "Check which terminal you land at — T1 and T2 are far apart. AREX starts at T2 so you're more likely to get a seat there. For late arrivals, check the last train time; taxis after midnight add a surcharge.",
        "AREX plus subway is usually the best value. Grab a T-money card at the airport convenience store before you board. If you've got heavy luggage, the limousine bus drops you closer to hotels in Myeongdong and Gangnam.",
    ],
    "arrival": [
        "You'll get the arrival card on the plane, so keep a pen handy and note your hotel address. Whether you need K-ETA depends on your passport — check the official site before you fly, rules change. Immigration can eat 30-60 min at peak times, so don't book a tight connection.",
        "Fill the arrival card carefully; mistakes mean redoing it at the counter. One customs form per family is fine. Meat and fresh fruit generally aren't allowed, so skip those.",
        "If you're transiting, leave at least 2 hours — immigration and bags get slow at Incheon during holidays. Free wifi at the airport, so you can sort your eSIM while you wait.",
    ],
    "sim": [
        "An eSIM is way easier if your phone supports it — set it up before you fly and you're online the moment you land. Data-only is fine unless you need a local number. Pocket wifi only really wins if you're splitting it with 2-3 people.",
        "Airport SIM counters get slammed when a few flights land together. Yeah, if your phone does eSIM, buy it in advance; otherwise the counters are open early and late, just bring your passport.",
        "Korean wifi is everywhere but you still want data for maps. eSIM is the least hassle; physical SIM is fine if your phone is locked. Check your plan allows hotspot if you're travelling with someone.",
    ],
    "money": [
        "Cards work almost everywhere here, including taxis and markets. Still keep 30-50k KRW in small notes for street food and tiny shops. Pro tip: exchange in the city, not at the airport — rates are usually better.",
        "Don't exchange everything at once. Yeah, cards are accepted almost everywhere, but some small restaurants and stalls are cash-only. Convenience store ATMs take foreign cards and have an English menu.",
        "Tipping isn't a thing here. If a card terminal asks for a PIN, just say 'signature' and they'll print a slip. Keep a little cash for buses and markets and you're set.",
    ],
    "rail": [
        "The Korail pass pays off if you're doing two or more long trips (Seoul-Busan, Seoul-Gangneung). Yeah, buy it before you arrive, then reserve KTX seats separately — the pass itself doesn't hold a seat. For one or two short hops, single tickets are cheaper.",
        "KTX is the fast option, but ITX and intercity buses are often half the price for a similar route. Pro tip: book on the Korail app a few days ahead for weekend travel, popular trains sell out.",
        "If you're under 25 or a student, check the youth pass — it can be a lot cheaper than the standard rail pass. Bring ID either way, they check it on board.",
    ],
    "attraction": [
        "Palaces are best right at opening — Gyeongbokgung is packed by 11, and the guard-changing ceremony is worth timing your visit around. Yeah, renting a hanbok nearby gets you free palace entry, so it often works out cheaper.",
        "For N Seoul Tower, go up about an hour before sunset so you get daylight and the night view in one trip. Pro tip: the cable car queue is long on weekends, the Namsan shuttle bus is quicker.",
        "Lotte World is a full day; buy tickets online for a small discount and go on a weekday. Honestly, the magic pass is only worth it if you're planning to do the big rides.",
    ],
    "family": [
        "Strollers are fine on the subway — every station has an elevator, though some exits are far from the platform. In Busan the hills and stairs are the real problem, so take taxis for the steep bits.",
        "Most restaurants have high chairs and staff are usually happy to help with kids. Yeah, big malls like Lotte or Shinsegae are the easiest bet for bathrooms and nursing rooms.",
        "For a family trip, stay near a subway line with a direct route to the sights and leave one day unplanned. Kids tire out faster than the itinerary expects.",
    ],
    "reserve": [
        "For a special dinner, book ahead — popular Seoul places fill up weeks out. CatchTable covers a lot of restaurants and has an English mode. Yeah, an early weekday slot is usually quieter and easier to get.",
        "Honestly, call or book through CatchTable rather than walking in. A lot of places hold tables for 30 minutes, so don't be late. Pro tip: ask for a window or a quieter corner when you book, they usually try to accommodate.",
        "Weekend dinners need a reservation, weekdays are more forgiving. Yeah, book 3-7 days ahead for anything popular in Gangnam or Itaewon.",
    ],
    "food": [
        "Portions are big here, so one main plus a shared side is usually plenty. Yeah, lunch rush is 12-1, so go at 11:30 or after 1:30 if you don't want to queue. If you can't do spice, 'an maepge haejuseyo' works every time.",
        "Street food is mostly cash, so keep small bills. Pick stalls with fast turnover — best freshness signal. Seoul has plenty of vegan and halal spots now, smaller cities are harder.",
        "Honestly, bibimbap, gimbap and gukbap are safe bets anywhere. Water is free at most places, just ask for 'mul'. Tipping isn't expected.",
    ],
    "solo": [
        "Seoul is honestly great solo — single diners are normal and the subway runs late. Stay near a station instead of right in a nightlife district if you want quiet nights. Pro tip: coin lockers at major stations make moving day way easier.",
        "Don't overpack your days. Yeah, two or three areas a day is realistic here. Coin lockers at big stations let you drop bags on travel days.",
        "It's safe overall, normal city rules at night. Kakao T is the easiest taxi app and you can pay by card in-app, which avoids language issues with drivers.",
    ],
    "weather": [
        "Winters here are colder than most people expect. Bring a real down jacket and shoes with grip — sidewalks ice up. Indoors is heavily heated, so layers beat one big coat.",
        "December-January gets dark around 5pm, so plan outdoor stuff for the morning. Hand warmers and moisturizer make a real difference. If snow is forecast, build extra time into transit.",
        "Late March to April and October are both good — spring is dustier and windier, autumn is clearer and cooler. Yeah, check the fine-dust forecast the morning you head out; masks are sold at any convenience store.",
    ],
    "wowpass": [
        "WOWPASS is handy if you want exchange + transit in one card, and you can issue it at the airport machines with your passport. That said, plain T-money plus your normal bank card is usually cheaper. Check the refund fee before you load a big amount.",
        "WOWPASS works for subway, bus and lots of stores, but T-money alone is enough if you're mostly paying by card. Load small first and see how it goes.",
        "You need your passport to issue WOWPASS. Yeah, it's convenient, but for a few days a regular T-money card does the same job for less hassle.",
    ],
    "general": [
        "Honestly, the two things that make Korea easy are a T-money card and data. Sort those at the airport and the rest falls into place. Happy to help with a rough day-by-day if you share your dates and where you're staying.",
        "Seoul is compact enough that you don't need to plan transport in detail. Yeah, just stay near a subway line and group sights by neighbourhood — expect 20-40 min between districts.",
        "Happy to help with specifics. Dates, where you're staying and what you want to see would let me give you a tighter plan.",
    ],
}

def detect_topic(text: str, table, title: str = "", min_score: int = 1) -> str:
    """제목에 나온 단어를 3배로 세어 주제를 고른다. 점수가 낮으면 general."""
    low = (text or "").lower()
    ttl = (title or "").lower()
    best, best_score = "general", 0
    for name, keys in table:
        score = 0
        for k in keys:
            kk = k.lower()
            if kk in ttl:
                score += 3
            elif kk in low:
                score += 1
        if score > best_score:
            best, best_score = name, score
    return best if best_score >= min_score else "general"


class KnowledgePack:
    """3호기 제작 100세트 지식 DB(qna_knowledge_pack.json).

    각 세트는 질문 패턴·매치 단어·완성된 답변을 갖고 있어서, API 키 없이도
    원어민/스친님 말투의 답변을 그대로 쓸 수 있다.
    """

    def __init__(self, path: Path):
        raw = load_json(path, {})
        self.meta = raw.get("meta") or {}
        self.sets = [x for x in (raw.get("sets") or []) if x.get("answer")]
        self.by_lang: dict[str, list[dict]] = {}
        for x in self.sets:
            self.by_lang.setdefault(str(x.get("lang", "en")), []).append(x)

    def __len__(self):
        return len(self.sets)

    # 어디에나 나오는 단어는 매칭 근거로 쓰지 않는다
    GENERIC = {
        "seoul", "korea", "korean", "trip", "travel", "traveler", "day", "days", "bus",
        "train", "food", "hotel", "tour", "visit", "guide", "city", "tourist", "itinerary",
        "first", "time", "best", "good", "help", "tips", "ask", "question", "korea travel",
        "서울", "한국", "여행", "ソウル", "韓国", "旅行",
    }

    @classmethod
    def _term_score(cls, t: str) -> int:
        t = t.strip().lower()
        if len(t) < 2 or t in cls.GENERIC:
            return 0
        dense = any(ord(ch) > 0x2E80 for ch in t)  # 한자·가나·한글은 글자당 정보량이 크다
        return len(t) * (2 if dense else 1) + 2

    def match(self, item: dict, lang: str, used: set | None = None) -> dict | None:
        title = str(item.get("title", "")).lower()
        body = str(item.get("text", "")).lower()
        hay = title + " " + body
        if not hay.strip():
            return None
        scored = []
        for st in self.by_lang.get(lang, []):
            if used and st.get("id") in used:
                continue
            ts = bs = 0
            for term in list(st.get("match_terms") or []) + list(st.get("keywords") or []):
                t = str(term).lower().strip()
                if not t:
                    continue
                sc = self._term_score(t)
                if not sc:
                    continue
                if t in title:
                    ts += sc
                elif t in body:
                    bs += sc
            if ts or bs:
                scored.append((st, ts, ts * 2 + bs))
        if not scored:
            return None
        # 제목에 걸린 세트가 있으면 그것만 후보로 본다(본문 한 단어로 엉뚱한 답을 고르지 않게)
        titled = [c for c in scored if c[1] >= 6]
        pool = titled or [c for c in scored if c[2] >= 12]
        if not pool:
            return None
        return max(pool, key=lambda c: c[2])[0]


class AnswerEngine:
    """Gemini 키가 있으면 AI 생성, 없으면 100세트 지식 DB → 내장 템플릿 순으로 답한다."""

    def __init__(self, cfg: Config):
        self.cfg = cfg
        self._recent: dict[str, list[str]] = {}
        self._used_pack: set[str] = set()
        self.pack = None
        if cfg.get("use_knowledge_pack", True):
            try:
                self.pack = KnowledgePack(BOT_DIR / str(cfg.get("knowledge_pack") or "qna_knowledge_pack.json"))
                if not len(self.pack):
                    self.pack = None
                else:
                    LOG.add(f"지식 DB {len(self.pack)}세트 로드 ({cfg.get('knowledge_pack')})", "ok")
            except Exception as e:
                LOG.add(f"지식 DB 로드 실패({e}) — 내장 템플릿으로 답합니다", "warn")
                self.pack = None

    # ---- 공개 API ----
    def generate(self, item: dict) -> tuple[str, str]:
        text = (item.get("title", "") + "\n" + item.get("text", "")).strip()
        platform = item["platform"]
        lang = self._lang_for(platform, text)
        key = (self.cfg.get("gemini_api_key") or "").strip()
        if key:
            try:
                answer = self._gemini(item, text, lang)
                if answer:
                    return self._clean_answer(answer, platform), "gemini"
            except Exception as e:
                LOG.add(f"Gemini 생성 실패 → 템플릿으로 대체: {e}", "warn")
        # API 키가 없으면 3호기 지식 DB(100세트)를 먼저 쓴다
        if self.pack:
            hit = self.pack.match(item, lang, self._used_pack)
            if hit:
                self._used_pack.add(str(hit.get("id")))
                LOG.add(f"지식 DB 매칭: {hit.get('id')} · {hit.get('topic', '')}", "info")
                return self._fit(hit["answer"], platform), "knowledge_pack"

        # 지식 DB에도 없고 템플릿만 쓸 때: 주제를 확실히 모르는 레딧 질문은 억지 답변보다 건너뛴다
        if platform == "reddit" and not key:
            topic = detect_topic(text + " " + item.get("keyword", ""), TRAVEL_TOPICS, item.get("title", ""), min_score=2)
            hay = (item.get("title", "") + " " + text).lower()
            if topic == "general" and not any(k in hay for k in BROAD_ASK):
                return "", "skip:주제를 확실히 알 수 없어 자동 답변을 보류했습니다(직접 확인 권장)"
        return self._template(item, text, lang), "template"

    # ---- 언어/템플릿 ----
    def _lang_for(self, platform: str, text: str) -> str:
        if platform == "threads":
            return "ko"
        if platform == "reddit":
            return "en"
        # X: 일본어 글이면 일본어, 아니면 영어
        if re.search(r"[\u3040-\u30ff\u4e00-\u9fff]", text or ""):
            return "ja"
        return "en"

    def _template(self, item: dict, text: str, lang: str) -> str:
        platform = item["platform"]
        rnd = random.Random(item["id"])
        if platform == "threads":
            topic = detect_topic(text, SAJU_TOPICS, item.get("title", ""), min_score=1)
            pool = SAJU_TEMPLATES.get(topic) or SAJU_TEMPLATES["general"]
            key = f"threads:{topic}"
            out = rnd.choice(self._varied(f"threads:{topic}", pool))
            recent = self._recent.setdefault(key, [])
            recent.append(out)
            del recent[:-2]
            # 실제 스레드 유저처럼: 절반 정도는 '스친님'으로 말 걸기
            if rnd.random() < 0.5 and not out.startswith("스친님"):
                out = "스친님, " + out[0].lower() + out[1:] if out[:1].isalpha() and out[0].isupper() else "스친님, " + out
            return out
        topic = detect_topic(text + " " + item.get("keyword", ""), TRAVEL_TOPICS, item.get("title", ""), min_score=2)
        table = TRAVEL_JP_TEMPLATES if lang == "ja" else TRAVEL_EN_TEMPLATES
        pool = table.get(topic) or table["general"]
        if topic == "attraction":
            low = (text + " " + item.get("title", "")).lower()
            if any(k in low for k in ("tower", "namsan", "タワー", "南山")):
                return pool[1]
            if any(k in low for k in ("lotte world", "everland", "theme park", "ロッテワールド", "遊園地")):
                return pool[2]
            return pool[0]
        return rnd.choice(self._varied(f"{platform}:{lang}:{topic}", pool))

    def _varied(self, key: str, pool: list[str]) -> list[str]:
        """같은 템플릿이 연달아 나오지 않게 최근 2개를 피한다."""
        recent = self._recent.setdefault(key, [])
        cand = [t for t in pool if t not in recent]
        return cand or pool

    # ---- Gemini ----
    def _prompt(self, item: dict, text: str, lang: str) -> str:
        platform = item["platform"]
        if platform == "threads":
            rule = (
                "너는 사주를 오래 봐온 사람이고, 지금은 스레드에서 지인이랑 얘기하듯 댓글을 단다.\n"
                "말투: 담백한 구어체 2~3문장. '~해요 / ~더라구요 / 이럴 땐 ~쪽을 먼저 봐야 해요' 같은 결. "
                "'~입니다 / ~하시기 바랍니다' 금지, 번호 매기기·이모지·링크·홍보·해시태그 금지. "
                "가능하면 '스친님'으로 한 번 불러 주고, 상대를 평가하지 말고 명리 개념(일주·오행·용신·대운)을 근거로 설명한다. "
                "마지막에 생년월일시를 알려주면 더 정확히 볼 수 있다고 가볍게 말한다."
            )
        elif lang == "ja":
            rule = (
                "あなたは韓国旅行に詳しい日本語話者で、Xで友だちに返信する感じで書きます。\n"
                "条件: 実際の日本語Xユーザーの口語(「〜ですよ」「〜かも」「ちなみに〜の方がラクかも」「〜めっちゃ助かりますよね」)。"
                "翻訳調・敬語の羅列(「〜でございます」「〜いただけますと幸いです」)は禁止。2〜3文、60〜140字。"
                "宣伝・リンク・ハッシュタグ・絵文字の多用は禁止。使える具体情報(交通・支払い・両替・空港・SIM)を1つ入れる。"
            )
        else:
            rule = (
                "You're a Redditor who knows Korea well, replying like a local in a travel thread.\n"
                "Tone: casual native Reddit English — 'Honestly, ...', 'Yeah, ... is way easier', 'Pro tip: ...'. "
                "2-4 sentences, 40-90 words. No textbook phrasing, no links, no promotion, no hashtags, no emojis. "
                "Include one concrete practical detail (transport, payments, airport, food, weather). "
                "Don't invent personal experience; general but accurate advice is fine. End lightly, not salesy."
            )
        return (
            f"{rule}\n\n"
            f"[플랫폼] {PLATFORM_LABEL.get(platform, platform)}\n"
            f"[검색 키워드] {item.get('keyword','')}\n"
            f"[작성자] {item.get('author','')}\n"
            f"[원문]\n{text[:1200]}\n\n"
            "위 원문의 맥락에 딱 맞는 댓글 본문만 출력해. 따옴표나 설명 없이 본문만."
        )

    def _gemini(self, item: dict, text: str, lang: str) -> str | None:
        key = (self.cfg.get("gemini_api_key") or "").strip()
        if not key:
            return None
        prompt = self._prompt(item, text, lang)
        models = self._model_list()
        budget = self._output_tokens()
        tried: list[str] = []
        errors: list[str] = []
        for model in models:
            tried.append(model)
            for _ in range(2):  # MAX_TOKENS로 잘리면 같은 모델을 더 긴 예산으로 한 번 더
                url = (
                    "https://generativelanguage.googleapis.com/v1beta/models/"
                    f"{urllib.parse.quote(model)}:generateContent?key={urllib.parse.quote(key)}"
                )
                payload = {
                    "contents": [{"role": "user", "parts": [{"text": prompt}]}],
                    "generationConfig": {
                        "temperature": 0.85,
                        "topP": 0.95,
                        "maxOutputTokens": max(MIN_OUTPUT_TOKENS, budget),
                    },
                    "safetySettings": [
                        {"category": c, "threshold": "BLOCK_ONLY_HIGH"}
                        for c in (
                            "HARM_CATEGORY_HARASSMENT",
                            "HARM_CATEGORY_HATE_SPEECH",
                            "HARM_CATEGORY_SEXUALLY_EXPLICIT",
                            "HARM_CATEGORY_DANGEROUS_CONTENT",
                        )
                    ],
                }
                status, data = http_post_json(url, payload, timeout=60)
                if status == 200:
                    cand = {}
                    try:
                        cand = (data.get("candidates") or [{}])[0] or {}
                        parts = cand["content"]["parts"]
                        out = "".join(p.get("text", "") for p in parts).strip()
                    except Exception:
                        out = ""
                    if out and cand.get("finishReason") == "MAX_TOKENS" and budget < MAX_OUTPUT_TOKENS:
                        budget = min(budget * 2, MAX_OUTPUT_TOKENS)
                        LOG.add(f"Gemini {model}: 답변이 잘려(maxOutputTokens={budget // 2}) → {budget} 토큰으로 재시도", "warn")
                        continue
                    if out:
                        if tried[1:]:
                            LOG.add(f"Gemini 모델 대체 사용: {model}", "info")
                        return out
                    errors.append(f"{model}: 빈 응답")
                    break
                if status in (400, 403, 404):
                    # 모델명이 없거나 키 권한 문제 → 다음 모델로 넘어간다
                    errors.append(f"{model}: HTTP {status}")
                    break
                if status in (429, 500, 502, 503, 504):
                    # 무료 한도/서버 혼잡 → 1.5초 쉬고 다음 모델로 넘어간다
                    errors.append(f"{model}: HTTP {status}")
                    LOG.add(f"Gemini {model} HTTP {status} — 1.5초 후 다음 모델로 재시도", "warn")
                    time.sleep(1.5)
                    break
                errors.append(f"{model}: HTTP {status}")
                break
        if errors:
            raise RuntimeError("Gemini 실패(" + "; ".join(errors[:4]) + ")")
        return None

    def _model_list(self) -> list[str]:
        """시도할 모델 순서 — 최신 모델 먼저, 그다음 config에 적힌 모델(중복 제거)."""
        cfg_models: list[str] = []
        for m in [self.cfg.get("gemini_model")] + list(self.cfg.get("gemini_fallback_models") or []):
            m = str(m or "").strip()
            if m and m not in cfg_models:
                cfg_models.append(m)
        ordered: list[str] = []
        for m in GEMINI_LATEST_MODELS + cfg_models + GEMINI_ALIAS_MODELS:
            if m not in ordered and not LEGACY_MODEL_RE.match(m):
                ordered.append(m)
        if not ordered:  # 정말 아무것도 없을 때만 구모델이라도 시도
            ordered = cfg_models[:]
        return ordered

    def _output_tokens(self) -> int:
        try:
            want = int(self.cfg.get("gemini_max_output_tokens") or DEFAULT_OUTPUT_TOKENS)
        except Exception:
            want = DEFAULT_OUTPUT_TOKENS
        return max(MIN_OUTPUT_TOKENS, min(want, MAX_OUTPUT_TOKENS))

    def _fit(self, text: str, platform: str) -> str:
        """플랫폼 글자 수에 맞춰 다듬는다(지식 DB 답변용)."""
        t = re.sub(r"\n{3,}", "\n\n", str(text or "").strip())
        t = re.sub(r"http\S+", "", t).strip()
        t = re.sub(r"#\S+", "", t).strip()
        limit = {"threads": 500, "x": 280, "reddit": 1200}.get(platform, 600)
        if len(t) > limit:
            cut = t[:limit]
            for sep in ("\n", "。", ". ", "다. ", "요. "):
                idx = cut.rfind(sep)
                if idx > limit * 0.6:
                    cut = cut[: idx + len(sep)].rstrip()
                    break
            t = cut
        return t

    def _clean_answer(self, text: str, platform: str) -> str:
        t = text.strip().strip('"').strip("“”")
        t = re.sub(r"^(댓글|답변|Reply)\s*[:：]\s*", "", t)
        t = re.sub(r"http\S+", "", t).strip()
        t = re.sub(r"#\S+", "", t).strip()
        if platform == "threads":
            t = t[:400]
        elif platform == "x":
            t = t[:280]
        else:
            t = t[:900]
        return re.sub(r"[ \t]{2,}", " ", t).strip()

# ---------------------------------------------------------------------------
# 브라우저 (계정별 프로필 · 기본 headless)
# ---------------------------------------------------------------------------
LOGIN_URL = {
    "threads": "https://www.threads.net/login",
    "x": "https://x.com/i/flow/login",
    "reddit": "https://www.reddit.com/login/",
}
HOME_URL = {
    "threads": "https://www.threads.net/",
    "x": "https://x.com/home",
    "reddit": "https://www.reddit.com/",
}
COOKIE_HINT = {
    "threads": ("sessionid",),
    "x": ("auth_token",),
    "reddit": ("reddit_session", "token_v2"),
}


class BrowserPool:
    """계정마다 독립된 Chrome 프로필(profiles/<id>)로 브라우저를 띄운다.

    기본은 headless(창이 안 뜸, PC 화면 점유 0). 대시보드에서 '로그인 창 열기'를
    눌렀을 때만 headless=False로 그 계정의 창을 띄운다.
    """

    def __init__(self, cfg: Config):
        self.cfg = cfg
        self._pw = None
        self._items: dict[str, dict] = {}  # acc_id -> {"ctx":..., "headless":bool}
        self.lock = threading.RLock()
        self.available = True
        try:
            import playwright  # noqa: F401
        except Exception:
            self.available = False

    # -- 내부 --
    def _start(self):
        from playwright.sync_api import sync_playwright

        if self._pw is None:
            self._pw = sync_playwright().start()

    def _channels(self) -> list:
        ch = (self.cfg.get("browser", {}) or {}).get("channel", "auto")
        if ch and ch != "auto":
            return [ch]
        return ["chrome", "msedge", None]

    def _profile_dir(self, acc: dict) -> Path:
        p = Path(acc.get("profile_dir") or f"profiles/{acc['id']}")
        if not p.is_absolute():
            p = BOT_DIR / p
        p.mkdir(parents=True, exist_ok=True)
        return p

    def _launch(self, acc: dict, headless: bool):
        self._start()
        slow = int((self.cfg.get("browser", {}) or {}).get("slow_mo", 0) or 0)
        last_err = None
        for channel in self._channels():
            try:
                kw = dict(
                    user_data_dir=str(self._profile_dir(acc)),
                    headless=headless,
                    slow_mo=slow,
                    args=[
                        "--disable-blink-features=AutomationControlled",
                        "--no-first-run",
                        "--no-default-browser-check",
                        "--disable-notifications",
                        "--lang=ko-KR",
                    ],
                    ignore_default_args=["--enable-automation"],
                    locale="ko-KR",
                    timezone_id="Asia/Seoul",
                )
                if headless:
                    # 헤드리스 티가 나지 않게 일반 브라우저와 같은 UA/화면 크기를 쓴다
                    kw["user_agent"] = UA_DESKTOP
                    kw["viewport"] = {"width": 1366, "height": 900}
                else:
                    kw["no_viewport"] = True
                if channel:
                    kw["channel"] = channel
                ctx = self._pw.chromium.launch_persistent_context(**kw)
                LOG.add(f"{acc['id']} 브라우저 열림 ({channel or 'bundled chromium'}, headless={headless})")
                return ctx, channel or "chromium"
            except Exception as e:
                last_err = e
                continue
        raise RuntimeError(f"브라우저를 열 수 없습니다: {last_err}")

    def context(self, acc: dict, headless: bool | None = None):
        want = bool(self.cfg.get("browser", {}).get("headless", True)) if headless is None else headless
        with self.lock:
            cur = self._items.get(acc["id"])
            if cur and cur["headless"] == want:
                try:
                    if not cur["ctx"].pages and cur["ctx"].browser is None:
                        raise RuntimeError("closed")
                    return cur["ctx"]
                except Exception:
                    self._items.pop(acc["id"], None)
            if cur:
                try:
                    cur["ctx"].close()
                except Exception:
                    pass
                self._items.pop(acc["id"], None)
            ctx, _ = self._launch(acc, headless=want)
            self._items[acc["id"]] = {"ctx": ctx, "headless": want}
            return ctx

    def page(self, acc: dict, headless: bool | None = None):
        ctx = self.context(acc, headless=headless)
        pages = [p for p in ctx.pages if not p.is_closed()]
        page = pages[0] if pages else ctx.new_page()
        try:
            page.set_default_timeout(20000)
            page.set_default_navigation_timeout(45000)
        except Exception:
            pass
        return page

    def open_login(self, acc: dict) -> dict:
        with self.lock:
            ctx = self.context(acc, headless=False)  # 로그인만 창을 띄운다
            page = ctx.pages[0] if ctx.pages else ctx.new_page()
            url = LOGIN_URL.get(acc["platform"], "about:blank")
            try:
                page.goto(url, wait_until="domcontentloaded")
            except Exception as e:
                LOG.add(f"{acc['id']} 로그인 페이지 이동 실패: {e}", "warn")
            try:
                page.bring_to_front()
            except Exception:
                pass
            for other in list(ctx.pages):
                if other is not page:
                    try:
                        other.close()
                    except Exception:
                        pass
            LOG.add(f"{acc['id']} 로그인 창을 열었습니다. 창에서 직접 로그인해 주세요.", "ok")
            return {"ok": True, "message": f"{acc['label']} 로그인 창을 열었습니다. 브라우저에서 로그인하세요."}

    def cookies(self, acc: dict) -> list[dict]:
        try:
            ctx = self.context(acc)
            return ctx.cookies()
        except Exception:
            return []

    def check_login(self, acc: dict) -> tuple[bool | None, str]:
        """쿠키로 로그인 여부를 추정한다. 판단이 안 되면 None."""
        if not self.available:
            return None, "playwright 미설치"
        try:
            cookies = self.cookies(acc)
        except Exception as e:
            return None, f"쿠키 확인 실패: {e}"
        names = {c.get("name") for c in cookies}
        hints = COOKIE_HINT.get(acc["platform"], ())
        if any(h in names for h in hints):
            return True, "로그인 쿠키 확인"
        if names:
            return False, "로그인 쿠키 없음"
        return False, "프로필이 비어 있음(로그인 필요)"

    def close(self, acc_id: str | None = None):
        with self.lock:
            targets = [acc_id] if acc_id else list(self._items)
            for k in targets:
                cur = self._items.pop(k, None)
                if cur:
                    try:
                        cur["ctx"].close()
                    except Exception:
                        pass

    def shutdown(self):
        self.close()
        if self._pw is not None:
            try:
                self._pw.stop()
            except Exception:
                pass
            self._pw = None


# ---------------------------------------------------------------------------
# 수집기
# ---------------------------------------------------------------------------
THREADS_JS = r"""
() => {
  const out = [];
  const seen = new Set();
  document.querySelectorAll('a[href*="/post/"]').forEach(a => {
    const href = a.getAttribute('href') || '';
    const m = href.match(/^\/@([^\/]+)\/post\/([A-Za-z0-9_\-]+)/);
    if (!m) return;
    const key = m[2];
    if (seen.has(key)) return;
    seen.add(key);
    let el = a, text = '';
    for (let i = 0; i < 9 && el; i++) {
      el = el.parentElement;
      if (el && el.innerText && el.innerText.trim().length > 50) { text = el.innerText; break; }
    }
    out.push({ url: 'https://www.threads.net/@' + m[1] + '/post/' + m[2], author: m[1], text: text });
  });
  return out;
}
"""

X_JS = r"""
() => {
  const out = [];
  const seen = new Set();
  document.querySelectorAll('article[data-testid="tweet"]').forEach(a => {
    let url = '';
    a.querySelectorAll('a[href*="/status/"]').forEach(x => {
      const href = x.getAttribute('href') || '';
      const m = href.match(/^\/([A-Za-z0-9_]+)\/status\/(\d+)/);
      if (m && !url) url = 'https://x.com' + m[0];
    });
    if (!url || seen.has(url)) return;
    seen.add(url);
    const t = a.querySelector('[data-testid="tweetText"]');
    const tm = a.querySelector('time');
    out.push({
      url: url,
      author: url.split('/')[3],
      text: t ? t.innerText : '',
      time: tm ? (tm.getAttribute('datetime') || '') : ''
    });
  });
  return out;
}
"""

REDDIT_OLD_JS = r"""
() => {
  const out = [];
  document.querySelectorAll('div.thing.link').forEach(d => {
    const a = d.querySelector('a.title');
    const c = d.querySelector('a.comments');
    const t = d.querySelector('time');
    const au = d.querySelector('a.author');
    if (!a || !c) return;
    out.push({
      url: 'https://www.reddit.com' + (c.getAttribute('href') || ''),
      title: a.innerText || '',
      author: au ? au.innerText : '',
      time: t ? t.getAttribute('datetime') : ''
    });
  });
  return out;
}
"""

QUESTION_START = (
    "how", "what", "where", "when", "why", "which", "who", "can ", "is ", "are ", "do ", "does ",
    "should", "any ", "anyone", "need", "help", "recommend", "advice", "tips", "best ", "worth",
)
NON_QUESTION_FLAIR = ("trip report", "photo", "video", "news", "mod post", "megathread", "weekly")
# 여행 답변 봇이 끼어들면 안 되는 주제(의료·부동산·구직 등)
OFF_TOPIC_PATTERNS = (
    r"\b(clinic|hospital|doctor|dentist|dermatolog|surgery|prescription|medication|mole removal)\b",
    r"\b(apartment|lease|jeonse|real estate|landlord|deposit|job|employment|salary|resume)\b",
)
# r/koreatravel·r/Seoul 외 서브레딧은 '한국' 언급이 있어야 수집
KOREA_HINTS = ("korea", "korean", "seoul", "busan", "jeju", "incheon", "dmz", "hongdae", "myeongdong")


def looks_like_question(title: str) -> bool:
    t = (title or "").strip().lower()
    if not t:
        return False
    if "?" in t or "？" in t:
        return True
    return any(t.startswith(w) for w in QUESTION_START) or any(
        w in t for w in ("recommend", "advice", "help me", "should i", "any tips", "worth it", "suggest")
    )


class Collectors:
    def __init__(self, cfg: Config, pool: BrowserPool, db: SeenDB):
        self.cfg = cfg
        self.pool = pool
        self.db = db

    # ---- 스레드 ----
    def threads(self, acc: dict) -> list[dict]:
        conf = self.cfg["threads"]
        page = self.pool.page(acc)
        out: list[dict] = []
        for kw in conf.get("keywords", []):
            url = conf["search_url"].format(q=urllib.parse.quote(kw))
            try:
                page.goto(url, wait_until="domcontentloaded")
                page.wait_for_timeout(3500)
                for _ in range(int(conf.get("scrolls", 2))):
                    page.mouse.wheel(0, 2200)
                    page.wait_for_timeout(random.randint(1200, 2200))
                rows = page.evaluate(THREADS_JS) or []
            except Exception as e:
                LOG.add(f"스레드 '{kw}' 검색 실패: {str(e)[:160]}", "warn")
                continue
            for row in rows:
                text = clean_text(row.get("text", ""), 1200)
                if len(text) < 20:
                    continue
                if kw.lower() not in text.lower():
                    continue
                out.append(
                    {
                        "id": "threads_" + row["url"].rsplit("/", 1)[-1],
                        "platform": "threads",
                        "keyword": kw,
                        "author": row.get("author", ""),
                        "title": "",
                        "text": text,
                        "url": row["url"],
                        "created_at": "",
                    }
                )
            page.wait_for_timeout(random.randint(2500, 5000))
        return self._dedupe(out)[: int(conf.get("max_per_scan", 12))]

    # ---- X ----
    def x(self, acc: dict) -> list[dict]:
        conf = self.cfg["x"]
        page = self.pool.page(acc)
        out: list[dict] = []
        max_age = int(self.cfg.get("max_item_age_hours", 36))
        cutoff = datetime.now(timezone.utc) - timedelta(hours=max_age)
        for kw in conf.get("keywords", []):
            url = conf["search_url"].format(q=urllib.parse.quote(kw))
            try:
                page.goto(url, wait_until="domcontentloaded")
                page.wait_for_timeout(4000)
                for _ in range(int(conf.get("scrolls", 3))):
                    page.mouse.wheel(0, 2400)
                    page.wait_for_timeout(random.randint(1300, 2400))
                rows = page.evaluate(X_JS) or []
            except Exception as e:
                LOG.add(f"X '{kw}' 검색 실패: {str(e)[:160]}", "warn")
                continue
            for row in rows:
                text = clean_text(row.get("text", ""), 800)
                if len(text) < 8 or text.startswith("RT @"):
                    continue
                if kw.lower() not in text.lower() and kw.lower() not in (row.get("url") or ""):
                    continue
                created = ""
                t = row.get("time") or ""
                if t:
                    try:
                        dt = datetime.fromisoformat(t.replace("Z", "+00:00"))
                        if dt < cutoff:
                            continue
                        created = dt.astimezone(KST).isoformat(timespec="seconds")
                    except Exception:
                        created = t
                out.append(
                    {
                        "id": "x_" + row["url"].rsplit("/", 1)[-1],
                        "platform": "x",
                        "keyword": kw,
                        "author": row.get("author", ""),
                        "title": "",
                        "text": text,
                        "url": row["url"],
                        "created_at": created,
                    }
                )
            page.wait_for_timeout(random.randint(2500, 5000))
        return self._dedupe(out)[: int(conf.get("max_per_scan", 12))]

    # ---- 레딧 ----
    def reddit(self, acc: dict | None = None) -> list[dict]:
        conf = self.cfg["reddit"]
        out: list[dict] = []
        for sub in conf.get("subreddits", []):
            posts = self._reddit_api(sub)
            if posts is None and conf.get("browser_fallback", True) and acc:
                posts = self._reddit_browser(sub, acc)
            if not posts:
                continue
            for p in posts:
                out.extend(self._reddit_items(p, sub))
        return self._dedupe(out)[: int(conf.get("max_per_scan", 15))]

    def _reddit_api(self, sub: str) -> list[dict] | None:
        """arctic-shift 공개 API — 인증 불필요, 레딧 .rss 종료 이후 1순위."""
        conf = self.cfg["reddit"]
        url = conf["api"].format(sub=sub, limit=25)
        for attempt in range(3):
            status, body = http_get(url, timeout=30)
            if status == 200:
                try:
                    data = json.loads(body.decode("utf-8", "replace"))
                    posts = data.get("data") or []
                    return posts if isinstance(posts, list) else []
                except Exception as e:
                    LOG.add(f"레딧 API 응답 파싱 실패({sub}): {e}", "warn")
                    return None
            if status in (422, 429):
                wait = 5 * (attempt + 1)
                LOG.add(f"레딧 API 일시 오류({sub}, HTTP {status}) — {wait}초 후 재시도", "warn")
                time.sleep(wait)
                continue
            LOG.add(f"레딧 API 실패({sub}): HTTP {status}", "warn")
            return None
        return None

    def _reddit_items(self, p: dict, sub: str) -> list[dict]:
        conf = self.cfg["reddit"]
        title = clean_text(p.get("title", ""), 300)
        if not title:
            return []
        created = p.get("created_utc") or p.get("created") or 0
        try:
            age_h = (time.time() - float(created)) / 3600 if created else 0
        except Exception:
            age_h = 0
        if created and age_h > float(conf.get("max_age_hours", 48)):
            return []
        flair = (p.get("link_flair_text") or "").lower()
        if any(f in flair for f in NON_QUESTION_FLAIR):
            return []
        if p.get("over_18") or p.get("stickied"):
            return []
        if not looks_like_question(title):
            return []
        hay = (title + " " + (p.get("selftext") or "")).lower()
        if any(re.search(pat, hay) for pat in OFF_TOPIC_PATTERNS):
            return []
        if sub.lower() not in ("koreatravel", "seoul") and not any(h in hay for h in KOREA_HINTS):
            return []
        try:
            if int(p.get("num_comments") or 0) > 40:
                return []
        except Exception:
            pass
        pid = p.get("id") or ""
        permalink = p.get("permalink") or ""
        url = "https://www.reddit.com" + permalink if permalink.startswith("/") else (p.get("url") or "")
        if not pid or not url:
            return []
        body = clean_text(p.get("selftext", ""), 1200)
        return [
            {
                "id": "reddit_" + pid,
                "platform": "reddit",
                "sub": sub,
                "keyword": sub,
                "author": p.get("author", ""),
                "title": title,
                "text": body if body and body != "[removed]" else "",
                "url": url,
                "created_at": ts_to_text(created),
            }
        ]

    def _reddit_browser(self, sub: str, acc: dict) -> list[dict] | None:
        """2순위: 로그인된 브라우저로 old.reddit 새 글 목록을 직접 연다."""
        try:
            page = self.pool.page(acc)
            page.goto(f"https://old.reddit.com/r/{sub}/new/", wait_until="domcontentloaded")
            page.wait_for_timeout(3000)
            rows = page.evaluate(REDDIT_OLD_JS) or []
        except Exception as e:
            LOG.add(f"레딧 브라우저 수집 실패({sub}): {str(e)[:140]}", "warn")
            return None
        posts = []
        for r in rows:
            m = re.search(r"/comments/([a-z0-9]+)/", r.get("url", ""))
            posts.append(
                {
                    "id": (m.group(1) if m else r.get("url", "")),
                    "title": r.get("title", ""),
                    "author": r.get("author", ""),
                    "permalink": urllib.parse.urlparse(r.get("url", "")).path,
                    "created_utc": 0,
                    "num_comments": 0,
                    "link_flair_text": "",
                    "selftext": "",
                }
            )
        return posts

    def _dedupe(self, items: list[dict]) -> list[dict]:
        seen, out = set(), []
        for it in items:
            if it["id"] in seen or self.db.exists(it["id"]):
                continue
            seen.add(it["id"])
            out.append(it)
        return out


# ---------------------------------------------------------------------------
# 댓글 작성
# ---------------------------------------------------------------------------
class Poster:
    def __init__(self, cfg: Config, pool: BrowserPool):
        self.cfg = cfg
        self.pool = pool

    def post(self, item: dict, acc: dict) -> tuple[str, str]:
        fn = {"threads": self._threads, "x": self._x, "reddit": self._reddit}[item["platform"]]
        return fn(item, acc)

    # -- 공용 헬퍼 --
    def _click_any(self, page, selectors, timeout_each: int = 2500) -> bool:
        for sel in selectors:
            try:
                loc = page.locator(sel).first
                loc.wait_for(state="visible", timeout=timeout_each)
                loc.click(timeout=timeout_each)
                return True
            except Exception:
                continue
        return False

    def _type_into(self, page, selectors, text: str) -> bool:
        for sel in selectors:
            try:
                loc = page.locator(sel).last
                loc.wait_for(state="visible", timeout=2500)
                loc.click(timeout=2500)
                page.wait_for_timeout(300)
                try:
                    page.keyboard.press("Control+a")
                    page.keyboard.press("Delete")
                except Exception:
                    pass
                page.keyboard.insert_text(text)  # 한글/일본어 입력 안전
                page.wait_for_timeout(500)
                return True
            except Exception:
                continue
        return False

    def _click_text_button(self, page, names: list[str]) -> bool:
        for name in names:
            for role in ("button", "link"):
                try:
                    loc = page.get_by_role(role, name=re.compile(rf"^{re.escape(name)}$")).first
                    if loc.count() and loc.is_visible():
                        loc.click(timeout=2500)
                        return True
                except Exception:
                    continue
            try:
                loc = page.locator(f"div[role='button']:has-text('{name}')").last
                if loc.count() and loc.is_visible():
                    loc.click(timeout=2500)
                    return True
            except Exception:
                continue
        return False

    # -- 스레드 --
    def _threads_post_url(self, url: str) -> str:
        """threads.net 주소를 threads.com으로 맞춘다(리다이렉트 지연 방지)."""
        u = (url or "").strip()
        for host in ("https://www.threads.net", "https://threads.net", "https://www.threads.com", "https://threads.com"):
            if u.startswith(host):
                u = "https://www.threads.com" + u[len(host):]
                break
        if u.startswith("www.threads.com"):
            u = "https://" + u
        if u.startswith("/"):
            u = "https://www.threads.com" + u
        return u

    def _threads_page_state(self, page) -> str:
        """지금 화면이 무엇인지: ok / login / error / empty"""
        try:
            if page.locator('input[name="username"]').count():
                return "login"
        except Exception:
            pass
        if re.search(r"/(login|auth_platform)", page.url or ""):
            return "login"
        try:
            body = page.locator("body").inner_text(timeout=4000) or ""
        except Exception:
            body = ""
        if any(t in body for t in THREADS_ERROR_TEXTS) and "답글" not in body and "Reply" not in body:
            return "error"
        if not body.strip():
            return "empty"
        if self._find_threads_composer(page):
            return "ok"
        # 글이 보이는 데 답글칸이 없고 로그인 링크가 있으면 → 로그인이 풀린 화면
        try:
            if page.locator('a[href="/login"]').count():
                return "login"
        except Exception:
            pass
        return "ok"

    def _find_threads_composer(self, page):
        """글 페이지에 이미 떠 있는 답글 입력창을 찾는다.

        Threads는 글을 열면 글 아래에 답글 입력창(인라인 작성 상자)을 바로 보여준다.
        그래서 답글 아이콘을 누를 필요 없이 그 상자에 바로 입력하면 된다.

        주의 1: 한국어 UI의 컬럼 컨테이너는 'Column body'가 아니라 '칼럼 본문'이다.
        주의 2: 빈 입력창은 aria-label에 '텍스트 필드가 비어 있습니다'가 들어 있어 가장 확실하지만,
                글을 넣으면 그 이름이 바뀐다 → 입력을 시작한 뒤에는 이 함수를 다시 부르지 말고
                찾아 둔 element를 그대로 쓴다.
        """
        def first_visible(selectors, limit=4):
            for sel in selectors:
                try:
                    loc = page.locator(sel)
                    n = loc.count()
                except Exception:
                    continue
                for i in range(min(n, limit)):
                    try:
                        el = loc.nth(i)
                        if not el.is_visible():
                            continue
                        # Locator는 쓸 때마다 다시 찾기 때문에, 글을 넣어 aria-label이 바뀌면
                        # 다음 순간부터 찾지 못한다 → 지금 이 DOM 노드에 고정(ElementHandle)해서 돌려준다.
                        return el.element_handle() or el
                    except Exception:
                        continue
            return None

        # 0순위: 빈 작성 상자 그 자체(aria-label로 바로)
        el = first_visible(THREADS_COMPOSER_DIRECT, 3)
        if el:
            return el
        # 1순위: 칼럼 본문(한/영/일) 안의 편집 영역 — 위에서부터 첫 번째 보이는 것
        el = first_visible([f'{scope} [contenteditable="true"]' for scope in THREADS_COMPOSER_COLUMN_SCOPES], 4)
        if el:
            return el
        # 2순위: 대화상자 → 본문 → textbox 순
        return first_visible(THREADS_COMPOSER_FALLBACK, 3)

    def _dismiss_threads_popups(self, page) -> None:
        """로그인 유도/알림 안내 팝업이 클릭을 가로채지 않게 닫는다."""
        for name in THREADS_POPUP_BUTTONS:
            try:
                loc = page.get_by_role("button", name=re.compile(rf"^{re.escape(name)}$"))
                if loc.count() and loc.first.is_visible():
                    loc.first.click(timeout=1500)
                    page.wait_for_timeout(300)
                    return
            except Exception:
                continue

    def _dom_click_labeled(self, page, labels: list[str]) -> str:
        """svg[aria-label]의 '클릭되는 조상'(div[role=button])을 DOM 클릭한다.
        아이콘을 Playwright로 직접 클릭하면 React 핸들러가 안 돌아서 아무 일도 안 일어난다."""
        try:
            return page.evaluate(
                """(labels) => {
                    const root = document.querySelector('[aria-label="Column body"]') || document.body;
                    const hits = [...root.querySelectorAll('svg[aria-label], [role="button"][aria-label]')];
                    for (const el of hits) {
                        const label = el.getAttribute('aria-label') || '';
                        if (!labels.some(l => label === l || label.startsWith(l))) continue;
                        const r = el.getBoundingClientRect();
                        if (r.width === 0 && r.height === 0) continue;
                        let n = el;
                        while (n && !(n.getAttribute && (n.getAttribute('role') === 'button' || n.tagName === 'BUTTON' || n.tagName === 'A'))) {
                            n = n.parentElement;
                        }
                        (n || el).click();
                        return label;
                    }
                    return '';
                }""",
                labels,
            ) or ""
        except Exception:
            return ""

    def _open_threads_composer(self, page) -> bool:
        """인라인 입력창이 없을 때: 답글 아이콘 → '답글 남기기' 문구 순으로 눌러 작성창을 연다."""
        if self._dom_click_labeled(page, THREADS_REPLY_LABELS):
            return True
        for sel in (
            'div[role="button"]:has-text("에게 답글")',
            'div[role="button"]:has-text("답글 남기기")',
            'div[role="button"]:has-text("답글 달기")',
            'div[role="button"]:has-text("Reply to @")',
            'div[role="button"]:has-text("Add a reply")',
            'span:has-text("답글 남기기")',
            'span:has-text("에게 답글")',
        ):
            try:
                loc = page.locator(sel).first
                if loc.count() and loc.is_visible():
                    loc.click(timeout=2500)
                    return True
            except Exception:
                continue
        return False

    def _click_threads_post_button(self, page) -> bool:
        for name in THREADS_POST_BUTTONS:
            try:
                loc = page.get_by_role("button", name=re.compile(rf"^{re.escape(name)}$"))
                n = loc.count()
                for i in range(n - 1, -1, -1):
                    b = loc.nth(i)
                    if b.is_visible() and b.is_enabled():
                        b.click(timeout=3000)
                        return True
            except Exception:
                continue
        return False

    def _threads_fail_report(self, page, item: dict, note: str) -> None:
        """실패 원인을 바로 알 수 있게 스크린샷·HTML·aria-label 목록을 logs/에 남긴다."""
        out = BOT_DIR / "logs"
        out.mkdir(parents=True, exist_ok=True)
        ts = datetime.now(KST).strftime("%Y%m%d_%H%M%S")
        try:
            page.screenshot(path=str(out / f"threads_fail_{ts}.png"))
        except Exception:
            pass
        try:
            (out / f"threads_fail_{ts}.html").write_text(page.content(), encoding="utf-8")
        except Exception:
            pass
        labels: list[str] = []
        try:
            labels = page.evaluate(
                """() => {
                    const seen = new Set(); const out = [];
                    document.querySelectorAll('[aria-label]').forEach(e => {
                        const r = e.getBoundingClientRect();
                        if (r.width === 0 && r.height === 0) return;
                        const v = e.tagName.toLowerCase() + ':' + e.getAttribute('aria-label');
                        if (!seen.has(v)) { seen.add(v); out.push(v); }
                    });
                    return out.slice(0, 60);
                }"""
            ) or []
        except Exception:
            pass
        LOG.add(f"스레드 실패 기록: logs/threads_fail_{ts}.png · .html ({note})", "warn")
        LOG.add(f"  지금 화면: {page.url} · 보이는 aria-label {len(labels)}개 → " + " / ".join(labels[:20]), "info")

    def _threads(self, item: dict, acc: dict) -> tuple[str, str]:
        page = self.pool.page(acc)
        url = self._threads_post_url(item["url"])
        composer = None
        note = ""
        for attempt in range(1, 4):
            try:
                page.goto(url, wait_until="domcontentloaded", timeout=45000)
            except Exception as e:
                note = f"페이지 열기 실패: {str(e)[:120]}"
                page.wait_for_timeout(2000)
                continue
            # threads.net → threads.com 리다이렉트 + 첫 렌더까지 충분히 기다린다
            page.wait_for_timeout(5000 if attempt == 1 else 4000)
            try:
                page.wait_for_load_state("networkidle", timeout=8000)
            except Exception:
                pass
            state = self._threads_page_state(page)
            if state == "login":
                raise RuntimeError("스레드 로그인이 필요합니다(대시보드 → 계정 관리 → 로그인 창 열기)")
            if state in ("error", "empty"):
                note = "스레드가 오류 화면을 보여줌" if state == "error" else "화면이 비어 있음"
                LOG.add(f"스레드 글 열기 재시도 {attempt}/3 — {note}", "warn")
                page.wait_for_timeout(1500 * attempt)
                continue
            self._dismiss_threads_popups(page)
            composer = self._find_threads_composer(page)
            if composer:
                break
            if self._open_threads_composer(page):
                page.wait_for_timeout(1500)
                composer = self._find_threads_composer(page)
                if composer:
                    break
            note = f"답글 입력창을 찾지 못했습니다(화면 상태: {state})"
            page.wait_for_timeout(1500 * attempt)
        if composer is None:
            self._threads_fail_report(page, item, note or "답글 입력창 없음")
            raise RuntimeError(f"답글 입력창을 열지 못했습니다 — {note or '화면에 입력창이 없음'}")

        # 입력 — Lexical 에디터라 insert_text만으로는 안 들어갈 때가 있다.
        # (aria-label이 '텍스트 필드가 비어 있습니다' → 입력 후 바뀌므로 찾아 둔 element를 그대로 쓴다)
        ok, how = self._threads_fill_composer(page, composer, item["answer"])
        if not ok:
            self._threads_fail_report(page, item, "답글 입력창에 글이 들어가지 않았습니다")
            raise RuntimeError("답글 입력창에 글이 들어가지 않았습니다(입력창 구조 변경 가능)")
        LOG.add(f"스레드 답글 입력 완료({how})", "info")

        # 게시: 인라인 작성 상자는 Ctrl+Enter, 대화상자형 작성창은 '게시/Post' 버튼
        try:
            page.keyboard.press("Control+Enter")
        except Exception:
            pass
        page.wait_for_timeout(2500)
        sent = self._threads_editor_cleared(page, item["answer"], composer)
        if not sent and self._click_threads_post_button(page):
            page.wait_for_timeout(3000)
            sent = self._threads_editor_cleared(page, item["answer"], composer)
        if sent:
            return "posted", ""
        self._threads_fail_report(page, item, "게시 후에도 입력창에 글이 남아 있음")
        return "unverified", "게시 후에도 입력창에 글이 남아 있음(확인 필요)"

    # -- 스레드 입력 상자(Lexical) 다루기 --
    def _threads_editor_text(self, page=None, composer=None) -> str:
        """입력창에 지금 들어 있는 글. composer를 주면 그 element를 그대로 읽는다."""
        if composer is not None:
            try:
                return (composer.inner_text() or "").strip()
            except Exception:
                pass
        if page is None:
            return ""
        try:
            box = self._find_threads_composer(page)
            return box.inner_text().strip() if box else ""
        except Exception:
            return ""

    def _threads_editor_cleared(self, page, answer: str, composer=None) -> bool:
        """입력창이 비었거나(게시됨) 내 글이 더 이상 입력창에 없으면 True."""
        probe = self._threads_probe(answer)
        if composer is not None:
            try:
                left = (composer.inner_text() or "").strip()
            except Exception:
                left = None  # 게시되면 상자가 사라지거나 새로 그려진다
            if left is not None:
                return (not left) or (bool(probe) and probe not in left)
        left = self._threads_editor_text(page)
        return (not left) or (bool(probe) and probe not in left)

    def _threads_probe(self, text: str) -> str:
        """입력 확인에 쓸 첫 줄 앞부분(줄바꿈·공백 정규화 영향 없이)."""
        for line in (text or "").splitlines():
            line = line.strip()
            if line:
                return line[:14]
        return ""

    def _threads_clear_composer(self, page, composer) -> None:
        try:
            composer.click(force=True, timeout=3000)
            page.keyboard.press("Control+a")
            page.keyboard.press("Delete")
            page.wait_for_timeout(200)
        except Exception:
            pass

    def _threads_composer_paste(self, page, composer, text: str) -> str:
        """Lexical이 가장 확실하게 받는 'paste' 이벤트를 던진다.

        Meta Lexical 에디터는 beforeinput/키 입력을 내부 상태와 동기화하지 못하는 경우가 있어,
        붙여넣기(paste) 이벤트를 직접 던지는 쪽이 실제로 가장 잘 들어간다.
        주의: Lexical의 붙여넣기 처리기는 비동기라서, 던진 직후에는 아직 안 들어가 있을 수 있다
              → 결과 판정은 잠시 기다린 뒤 _threads_editor_text(composer=...)로 한다.
        """
        try:
            page.evaluate(
                """([el, text]) => {
                    try { el.focus(); } catch (e) {}
                    try {
                        const dt = new DataTransfer();
                        dt.setData('text/plain', text);
                        el.dispatchEvent(new ClipboardEvent('paste', {
                            clipboardData: dt, bubbles: true, cancelable: true
                        }));
                    } catch (e) {}
                    return true;
                }""",
                [composer, text],
            )
            return text
        except Exception:
            return ""

    def _threads_composer_exec(self, page, composer, text: str) -> str:
        """paste가 안 먹을 때의 폴백: execCommand('insertText')로 직접 삽입."""
        try:
            got = page.evaluate(
                """([el, text]) => {
                    try { el.focus(); } catch (e) {}
                    try { document.execCommand('insertText', false, text); } catch (e) {}
                    return (el.innerText || '').trim();
                }""",
                [composer, text],
            ) or ""
            return str(got).strip()
        except Exception:
            return ""

    def _threads_fill_composer(self, page, composer, text: str) -> tuple[bool, str]:
        """답글 입력창에 글을 넣는다 → (성공?, 어느 방법이었는지).

        1차 insert_text(한/영/일 안전) → 2차 paste 이벤트 → 3차 keyboard.type(사람처럼).
        확인은 매번 '찾아 둔 composer'의 inner_text로만 한다(다시 찾으면 다른 상자를 집는다).
        """
        probe = self._threads_probe(text)

        def entered() -> bool:
            got = self._threads_editor_text(composer=composer)
            return bool(got.strip()) and (not probe or probe in got)

        try:
            composer.scroll_into_view_if_needed(timeout=3000)
        except Exception:
            pass
        try:
            composer.click(force=True, timeout=4000)
        except Exception:
            try:
                composer.click(timeout=3000)
            except Exception:
                pass
        try:
            composer.focus()
        except Exception:
            pass
        # Lexical은 내부 <p>에 캐럿이 있어야 키 입력을 받는다
        try:
            inner_p = composer.query_selector("p")
            if inner_p and inner_p.is_visible():
                inner_p.click(timeout=1500)
        except Exception:
            pass
        page.wait_for_timeout(300)
        try:
            page.keyboard.press("Control+a")
            page.keyboard.press("Delete")
        except Exception:
            pass

        # 1차: insert_text
        try:
            page.keyboard.insert_text(text)
        except Exception:
            pass
        page.wait_for_timeout(700)
        if entered():
            return True, "insert_text"

        # 2차: paste 이벤트 (Lexical은 비동기로 처리하므로 잠시 기다려 확인)
        self._threads_clear_composer(page, composer)
        if self._threads_composer_paste(page, composer, text):
            page.wait_for_timeout(900)
            if entered():
                return True, "paste"
            # 2-1차: execCommand('insertText')
            self._threads_composer_exec(page, composer, text)
            page.wait_for_timeout(500)
            if entered():
                return True, "execCommand"

        # 3차: 사람처럼 한 글자씩
        self._threads_clear_composer(page, composer)
        try:
            page.keyboard.type(text, delay=15)
        except Exception:
            pass
        page.wait_for_timeout(900)
        if entered():
            return True, "type"
        return False, ""

    # -- X --
    def _x(self, item: dict, acc: dict) -> tuple[str, str]:
        page = self.pool.page(acc)
        page.goto(item["url"], wait_until="domcontentloaded")
        page.wait_for_timeout(3500)
        if page.locator('[data-testid="loginButton"]').count():
            raise RuntimeError("X 로그인이 필요합니다(대시보드에서 로그인 창을 열어 주세요)")
        if not self._click_any(page, ['[data-testid="reply"]']):
            raise RuntimeError("답글 아이콘을 찾지 못했습니다")
        page.wait_for_timeout(1500)
        ok = self._type_into(page, ['div[data-testid^="tweetTextarea_"]', 'div[role="textbox"]'], item["answer"])
        if not ok:
            raise RuntimeError("답글 입력창을 찾지 못했습니다")
        page.wait_for_timeout(700)
        if not self._click_any(page, ['[data-testid="tweetButtonInline"]', '[data-testid="tweetButton"]']):
            try:
                page.keyboard.press("Control+Enter")
            except Exception:
                raise RuntimeError("게시 버튼을 찾지 못했습니다")
        page.wait_for_timeout(4000)
        try:
            still = page.locator('div[data-testid^="tweetTextarea_"]').count()
        except Exception:
            still = 0
        if still:
            return "unverified", "게시 후 입력창이 남아 있음(확인 필요)"
        return "posted", ""

    # -- 레딧 --
    def _reddit(self, item: dict, acc: dict) -> tuple[str, str]:
        page = self.pool.page(acc)
        # old.reddit이 구조가 단순해 성공률이 높다
        url = item["url"].replace("https://www.reddit.com", "https://old.reddit.com")
        page.goto(url, wait_until="domcontentloaded")
        page.wait_for_timeout(3000)
        if page.locator('input[name="user"]').count() and page.locator('form#login-form').count():
            raise RuntimeError("레딧 로그인이 필요합니다(대시보드에서 로그인 창을 열어 주세요)")
        ok = self._type_into(page, ['textarea[name="text"]', 'div[contenteditable="true"]'], item["answer"])
        if not ok:
            raise RuntimeError("댓글 입력창을 찾지 못했습니다")
        page.wait_for_timeout(600)
        clicked = self._click_any(page, ['button.save', 'button[name="submit"]', 'button:has-text("save")'])
        if not clicked:
            clicked = self._click_text_button(page, ["Comment", "댓글"])
        if not clicked:
            raise RuntimeError("등록 버튼을 찾지 못했습니다")
        page.wait_for_timeout(4000)
        try:
            shown = page.get_by_text(item["answer"][:40], exact=False).count()
        except Exception:
            shown = 0
        if shown:
            return "posted", ""
        return "unverified", "등록 후 댓글이 화면에서 확인되지 않음"


# ---------------------------------------------------------------------------
# 봇 본체
# ---------------------------------------------------------------------------
class Bot:
    def __init__(self, cfg: Config, db: SeenDB | None = None, no_browser: bool = False, mode_override: str | None = None):
        self.cfg = cfg
        self.db = db or SeenDB(BOT_DIR / "seen.db")
        self.pool = BrowserPool(cfg)
        self.collectors = Collectors(cfg, self.pool, self.db)
        self.poster = Poster(cfg, self.pool)
        self.engine = AnswerEngine(cfg)
        self.no_browser = no_browser
        self.mode_override = mode_override
        self.cmds: queue.Queue = queue.Queue()
        self.stop = threading.Event()
        self.scan_requested = threading.Event()
        self.scanning = False
        self.last_scan = ""
        self.next_scan_at = 0.0
        self.login_state: dict[str, dict] = {}
        self._rr_start = 0
        self.started_at = datetime.now(KST).strftime("%Y-%m-%d %H:%M")

    # -- 상태 --
    @property
    def mode(self) -> str:
        return self.mode_override or self.cfg.get("mode", "dry_run")

    def set_mode(self, mode: str):
        self.mode_override = None
        self.cfg.set("mode", mode)
        LOG.add(f"모드 변경: {'자동 댓글 ON (실제 게시)' if mode == 'auto' else '자동 댓글 OFF (초안만)'}", "ok")

    def accounts_state(self) -> list[dict]:
        out = []
        for a in self.cfg.accounts():
            st = self.login_state.get(a["id"], {})
            out.append(
                {
                    **a,
                    "logged_in": st.get("ok"),
                    "login_note": st.get("note", "확인 전"),
                    "checked_at": st.get("at", ""),
                    "pinned": self.cfg.get("pinned_account") == a["id"],
                }
            )
        return out

    def state(self) -> dict:
        return {
            "app": APP_NAME,
            "version": VERSION,
            "time": now_iso(),
            "started_at": self.started_at,
            "mode": self.mode,
            "auto": self.mode == "auto",
            "scanning": self.scanning,
            "last_scan": self.last_scan,
            "next_scan_in": max(0, int(self.next_scan_at - time.time())) if self.next_scan_at else 0,
            "scan_interval_sec": int(self.cfg.get("scan_interval_sec", 180)),
            "gemini": {
                "configured": bool((self.cfg.get("gemini_api_key") or "").strip()),
                "model": self.cfg.get("gemini_model"),
            },
            "accounts": self.accounts_state(),
            "account_mode": self.cfg.get("account_mode", "rotation"),
            "stats": self.db.stats(),
            "caps": self.cfg.get("max_per_hour"),
            "items": self.db.list(limit=120),
            "log": LOG.snapshot(60),
            "platforms": {
                p: {
                    "enabled": bool(self.cfg.get(p, {}).get("enabled", True)),
                    "label": PLATFORM_LABEL[p],
                    "keywords": self.cfg.get(p, {}).get("keywords") or self.cfg.get(p, {}).get("subreddits") or [],
                }
                for p in ("threads", "x", "reddit")
            },
        }

    # -- 명령 큐(Playwright는 워커 스레드에서만 만진다) --
    def submit(self, name: str, **kw) -> concurrent.futures.Future:
        fut: concurrent.futures.Future = concurrent.futures.Future()
        self.cmds.put((name, kw, fut))
        return fut

    def _handle_cmd(self, cmd):
        name, kw, fut = cmd
        try:
            if name == "login":
                acc = self.cfg.account(kw["acc_id"])
                if not acc:
                    raise RuntimeError("계정을 찾을 수 없습니다")
                fut.set_result(self.pool.open_login(acc))
            elif name == "check":
                acc = self.cfg.account(kw["acc_id"])
                if not acc:
                    raise RuntimeError("계정을 찾을 수 없습니다")
                ok, note = self.pool.check_login(acc)
                self.login_state[acc["id"]] = {"ok": ok, "note": note, "at": now_iso()}
                LOG.add(f"{acc['id']} 로그인 상태: {note}", "ok" if ok else "warn")
                fut.set_result({"ok": ok, "note": note})
            else:
                raise RuntimeError(f"알 수 없는 명령: {name}")
        except Exception as e:
            LOG.add(f"명령 실패({name}): {e}", "error")
            if not fut.done():
                fut.set_exception(e)

    def _drain_commands(self):
        while True:
            try:
                cmd = self.cmds.get_nowait()
            except queue.Empty:
                return
            self._handle_cmd(cmd)

    def _sleep(self, seconds: float):
        """대시보드 명령에 반응할 수 있는 대기."""
        end = time.time() + max(0, seconds)
        while time.time() < end and not self.stop.is_set():
            self._drain_commands()
            time.sleep(min(1.0, max(0.05, end - time.time())))

    # -- 계정 선택 --
    def pick_account(self, platform: str, advance: bool = True) -> dict | None:
        accs = [a for a in self.cfg.accounts(platform) if a.get("enabled", True)]
        if not accs:
            return None
        if self.cfg.get("account_mode") == "single":
            pinned = self.cfg.get("pinned_account")
            for a in accs:
                if a["id"] == pinned:
                    return a
            return None
        idx = int(self.db.meta_get(f"rot_{platform}", "0") or 0) % len(accs)
        acc = accs[idx]
        if advance:
            self.db.meta_set(f"rot_{platform}", str((idx + 1) % len(accs)))
        return acc

    def _login_ok(self, acc: dict) -> bool | None:
        st = self.login_state.get(acc["id"])
        if st and st.get("at"):
            try:
                age = (datetime.now(KST) - datetime.fromisoformat(st["at"])).total_seconds()
                if age < 600:
                    return st.get("ok")
            except Exception:
                pass
        ok, note = self.pool.check_login(acc)
        self.login_state[acc["id"]] = {"ok": ok, "note": note, "at": now_iso()}
        return ok

    # -- 수집 + 답변 생성 --
    PLATFORM_ORDER = ("threads", "x", "reddit")

    def _rr_order(self, items: list[dict]) -> list[dict]:
        """플랫폼을 라운드 로빈(돌아가면서) 순서로 섞는다. 스캔마다 시작 플랫폼을 한 칸씩 옮긴다."""
        buckets: dict[str, list[dict]] = {}
        for it in items:
            buckets.setdefault(it.get("platform") or "", []).append(it)
        order = [p for p in self.PLATFORM_ORDER if p in buckets]
        order += [p for p in buckets if p not in self.PLATFORM_ORDER]
        if not order:
            return []
        out: list[dict] = []
        start = int(getattr(self, "_rr_start", 0)) % len(order)
        queues = [list(buckets[p]) for p in order]
        i = 0
        while any(queues):
            idx = (start + i) % len(order)
            if queues[idx]:
                out.append(queues[idx].pop(0))
            i += 1
            if i > 10000:
                break
        return out

    def scan_once(self) -> dict:
        if self.scanning:
            return {"ok": False, "message": "이미 스캔 중입니다"}
        self.scanning = True
        summary = {"found": 0, "new": 0, "answered": 0, "posted": 0}
        try:
            LOG.add("스캔 시작", "info")
            new_items: list[dict] = []
            for platform in ("threads", "x", "reddit"):
                conf = self.cfg.get(platform, {}) or {}
                if not conf.get("enabled", True):
                    continue
                if platform in ("threads", "x") and self.no_browser:
                    LOG.add(f"{PLATFORM_LABEL[platform]}: 브라우저 수집 건너뜀(--no-browser)", "warn")
                    continue
                try:
                    if platform == "threads":
                        acc = self.pick_account("threads", advance=False)
                        if not acc:
                            LOG.add("스레드: 활성 계정이 없습니다", "warn")
                            continue
                        if not self.pool.available:
                            LOG.add("스레드: playwright가 설치되지 않았습니다", "warn")
                            continue
                        found = self.collectors.threads(acc)
                    elif platform == "x":
                        acc = self.pick_account("x", advance=False)
                        if not acc:
                            LOG.add("X: 활성 계정이 없습니다", "warn")
                            continue
                        if not self.pool.available:
                            LOG.add("X: playwright가 설치되지 않았습니다", "warn")
                            continue
                        found = self.collectors.x(acc)
                    else:
                        acc = self.pick_account("reddit", advance=False)
                        found = self.collectors.reddit(acc)
                except Exception as e:
                    LOG.add(f"{PLATFORM_LABEL[platform]} 수집 오류: {str(e)[:200]}", "error")
                    LOG.add(traceback.format_exc(limit=3), "error")
                    continue

                summary["found"] += len(found)
                fresh = [it for it in found if self.db.add_item(it)]
                summary["new"] += len(fresh)
                LOG.add(
                    f"{PLATFORM_LABEL[platform]}: {len(found)}건 확인, 새 글 {len(fresh)}건",
                    "ok" if fresh else "info",
                )
                new_items.extend(fresh)
                self._drain_commands()

            # 답변 생성 (새 글 + 이전 스캔에서 답변을 못 받은 대기 글)
            # 한 플랫폼(예: 스레드 12건)만 몰려서 X·레딧이 계속 밀리지 않도록 플랫폼을 번갈아 꺼낸다.
            limit = max(1, int(self.cfg.get("answer_limit_per_scan", 3)))
            backlog = self.db.missing_answers(limit=max(limit * 4, 12))
            queue_items = self._rr_order(list(new_items) + backlog)
            picked, ids = [], set()
            for it in queue_items:
                if it["id"] in ids:
                    continue
                ids.add(it["id"])
                picked.append(it)
                if len(picked) >= limit:
                    break
            self._rr_start += 1
            for it in picked:
                try:
                    answer, engine = self.engine.generate(it)
                    if not answer:
                        reason = engine.split(":", 1)[-1] if engine.startswith("skip:") else "답변 보류"
                        self.db.mark(it["id"], "skipped", error=reason)
                        LOG.add(f"[{PLATFORM_LABEL[it['platform']]}] 건너뜀 — {reason}", "warn")
                        continue
                    status = "draft" if self.mode == "dry_run" else "pending"
                    self.db.set_answer(it["id"], answer, engine)
                    if status == "draft":
                        self.db.mark(it["id"], "draft")
                    summary["answered"] += 1
                    LOG.add(f"[{PLATFORM_LABEL[it['platform']]}] {it['author']} 글에 답변 준비 ({engine})", "ok")
                    LOG.add(f"   → {answer[:160]}{'…' if len(answer) > 160 else ''}")
                except Exception as e:
                    self.db.mark(it["id"], "failed", error=f"답변 생성 실패: {e}")
                    LOG.add(f"답변 생성 실패: {e}", "error")

            if self.mode == "auto":
                summary["posted"] = self._post_pending()
            else:
                LOG.add("자동 댓글 OFF — 초안만 저장했습니다. 대시보드에서 ON 하면 실제로 답니다.", "info")

            self.last_scan = now_iso()
            self.next_scan_at = time.time() + int(self.cfg.get("scan_interval_sec", 180))
            LOG.add(
                f"스캔 완료 — 새 글 {summary['new']}건, 답변 {summary['answered']}건, 게시 {summary['posted']}건",
                "ok",
            )
            return {"ok": True, **summary}
        except Exception as e:
            LOG.add(f"스캔 오류: {e}", "error")
            LOG.add(traceback.format_exc(limit=4), "error")
            return {"ok": False, "message": str(e), **summary}
        finally:
            self.scanning = False

    # -- 실제 게시 --
    def _post_pending(self) -> int:
        posted = 0
        hour_ago = (datetime.now(KST) - timedelta(hours=1)).isoformat(timespec="seconds")
        midnight = datetime.now(KST).replace(hour=0, minute=0, second=0, microsecond=0).isoformat(timespec="seconds")
        for platform in ("threads", "x", "reddit"):
            conf = self.cfg.get(platform, {}) or {}
            if not conf.get("enabled", True):
                continue
            cap_hour = int((self.cfg.get("max_per_hour") or {}).get(platform, 3))
            cap_day = int((self.cfg.get("max_per_day") or {}).get(platform, 20))
            pending = self.db.by_status(platform, "pending", limit=5)
            if not pending:
                continue
            done_hour = self.db.count_since(platform, hour_ago)
            done_day = self.db.count_since(platform, midnight)
            if self.no_browser:
                LOG.add(f"{PLATFORM_LABEL[platform]}: --no-browser 실행이라 게시를 건너뜁니다", "warn")
                continue
            first = True
            for item in pending:
                if done_hour >= cap_hour:
                    LOG.add(f"{PLATFORM_LABEL[platform]}: 시간당 한도({cap_hour}) 도달 — 다음 스캔에서", "warn")
                    break
                if done_day >= cap_day:
                    LOG.add(f"{PLATFORM_LABEL[platform]}: 하루 한도({cap_day}) 도달", "warn")
                    break
                acc = self.pick_account(platform)
                if not acc:
                    self.db.mark(item["id"], "skipped", error="활성 계정 없음")
                    LOG.add(f"{PLATFORM_LABEL[platform]}: 활성 계정이 없어 건너뜀", "warn")
                    break
                ok = self._login_ok(acc)
                if ok is False:
                    self.db.mark(item["id"], "skipped", error=f"{acc['id']} 로그인 필요")
                    LOG.add(f"{acc['id']} 로그인이 안 되어 있어 건너뜀(대시보드에서 로그인 창 열기)", "warn")
                    break
                delay = random.randint(20, 60) if first else random.randint(*self.cfg.get("reply_delay_sec", [180, 420]))
                LOG.add(f"{delay}초 대기 후 {acc['id']}로 댓글 게시 예정", "info")
                self._sleep(delay)
                if self.stop.is_set():
                    return posted
                try:
                    status, note = self.poster.post(item, acc)
                    self.db.mark_posted(item["id"], status, acc["id"], note)
                    LOG.add(
                        f"[{PLATFORM_LABEL[platform]}] 게시 {'완료' if status == 'posted' else '(확인 필요)'} — {item['url']}",
                        "post",
                    )
                    posted += 1
                    done_hour += 1
                    done_day += 1
                except Exception as e:
                    self.db.mark_posted(item["id"], "failed", acc["id"], str(e))
                    LOG.add(f"[{PLATFORM_LABEL[platform]}] 게시 실패: {str(e)[:200]}", "error")
                first = False
                self._drain_commands()
        return posted

    # -- 루프 --
    def run_forever(self):
        LOG.add(f"{APP_NAME} v{VERSION} 시작 — 모드: {self.mode}", "ok")
        self.next_scan_at = time.time() + 3
        while not self.stop.is_set():
            try:
                try:
                    cmd = self.cmds.get(timeout=1.0)
                    self._handle_cmd(cmd)
                except queue.Empty:
                    pass
                if self.scan_requested.is_set() or time.time() >= self.next_scan_at:
                    self.scan_requested.clear()
                    self.scan_once()
                    if not self.next_scan_at:
                        self.next_scan_at = time.time() + int(self.cfg.get("scan_interval_sec", 180))
            except KeyboardInterrupt:
                break
            except Exception as e:
                LOG.add(f"루프 오류: {e}", "error")
                LOG.add(traceback.format_exc(limit=4), "error")
                time.sleep(5)
        LOG.add("봇을 종료합니다", "info")
        self.pool.shutdown()

# ---------------------------------------------------------------------------
# 로컬 대시보드 (127.0.0.1:8765)
# ---------------------------------------------------------------------------
class DashboardHandler(BaseHTTPRequestHandler):
    server_version = "KikiQnADashboard/1.0"

    def log_message(self, fmt, *args):  # 콘솔 조용히
        return

    # -- helpers --
    @property
    def bot(self) -> "Bot":
        return self.server.bot  # type: ignore[attr-defined]

    def _send(self, code: int, body: bytes, ctype: str = "application/json; charset=utf-8"):
        self.send_response(code)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Cache-Control", "no-store")
        self.end_headers()
        try:
            self.wfile.write(body)
        except Exception:
            pass

    def _json(self, obj, code: int = 200):
        self._send(code, json.dumps(obj, ensure_ascii=False).encode("utf-8"))

    def _host_ok(self) -> bool:
        host = (self.headers.get("Host") or "").split(":")[0].strip().lower()
        return host in ("127.0.0.1", "localhost", "")

    def _body(self) -> dict:
        try:
            n = int(self.headers.get("Content-Length") or 0)
            raw = self.rfile.read(n) if n else b"{}"
            data = json.loads(raw.decode("utf-8") or "{}")
            return data if isinstance(data, dict) else {}
        except Exception:
            return {}

    # -- GET --
    def do_GET(self):
        if not self._host_ok():
            return self._json({"ok": False, "error": "forbidden"}, 403)
        path = urllib.parse.urlparse(self.path).path
        if path in ("/", "/index.html", "/dashboard.html"):
            html_file = BOT_DIR / "dashboard.html"
            if html_file.exists():
                return self._send(200, html_file.read_bytes(), "text/html; charset=utf-8")
            return self._send(200, b"<h1>dashboard.html missing</h1>", "text/html; charset=utf-8")
        if path == "/api/state":
            return self._json(self.bot.state())
        if path == "/api/log":
            return self._json({"log": LOG.snapshot(200)})
        if path == "/favicon.ico":
            return self._send(200, b"", "image/x-icon")
        return self._json({"ok": False, "error": "not found"}, 404)

    # -- POST --
    def do_POST(self):
        if not self._host_ok():
            return self._json({"ok": False, "error": "forbidden"}, 403)
        path = urllib.parse.urlparse(self.path).path
        data = self._body()
        bot = self.bot
        try:
            if path == "/api/auto":
                on = bool(data.get("on"))
                bot.set_mode("auto" if on else "dry_run")
                if on:
                    LOG.add("자동 댓글 ON — 다음 스캔부터 실제로 댓글을 답니다.", "ok")
                return self._json({"ok": True, "mode": bot.mode})

            if path == "/api/scan":
                bot.scan_requested.set()
                LOG.add("대시보드에서 '지금 1회 스캔' 요청", "info")
                return self._json({"ok": True, "message": "스캔을 시작합니다"})

            if path == "/api/config":
                if "gemini_api_key" in data:
                    key = str(data.get("gemini_api_key") or "").strip()
                    bot.cfg.set("gemini_api_key", key)
                    LOG.add("Gemini API 키 " + ("저장됨" if key else "삭제됨"), "ok")
                if data.get("gemini_model"):
                    bot.cfg.set("gemini_model", str(data["gemini_model"]).strip())
                return self._json({"ok": True, "gemini": {"configured": bool((bot.cfg.get("gemini_api_key") or "").strip())}})

            if path == "/api/accounts/add":
                acc = bot.cfg.add_account(str(data.get("platform", "")), str(data.get("label", "")))
                LOG.add(f"계정 추가: {acc['label']} ({acc['id']}) — 프로필 폴더 {acc['profile_dir']}", "ok")
                return self._json({"ok": True, "account": acc, "accounts": bot.accounts_state()})

            if path == "/api/accounts/remove":
                acc_id = str(data.get("id", ""))
                acc = bot.cfg.account(acc_id)
                ok = bot.cfg.remove_account(acc_id)
                if ok:
                    bot.login_state.pop(acc_id, None)
                    LOG.add(f"계정 삭제: {acc_id} (프로필 폴더는 남겨 둡니다)", "warn")
                return self._json({"ok": ok, "accounts": bot.accounts_state()})

            if path == "/api/accounts/toggle":
                acc = bot.cfg.account(str(data.get("id", "")))
                if not acc:
                    return self._json({"ok": False, "error": "계정 없음"}, 404)
                enabled = bool(data.get("enabled"))
                with bot.cfg.lock:
                    for a in bot.cfg.data["accounts"]:
                        if a["id"] == acc["id"]:
                            a["enabled"] = enabled
                    bot.cfg.save()
                LOG.add(f"{acc['label']} {'활성' if enabled else '비활성'}", "info")
                return self._json({"ok": True, "accounts": bot.accounts_state()})

            if path == "/api/accounts/pin":
                acc_id = str(data.get("id", ""))
                if acc_id:
                    with bot.cfg.lock:
                        bot.cfg.data["account_mode"] = "single"
                        bot.cfg.data["pinned_account"] = acc_id
                        bot.cfg.save()
                    LOG.add(f"'{acc_id}' 계정으로 고정", "info")
                else:
                    with bot.cfg.lock:
                        bot.cfg.data["account_mode"] = "rotation"
                        bot.cfg.data["pinned_account"] = ""
                        bot.cfg.save()
                    LOG.add("계정 로테이션으로 전환", "info")
                return self._json({"ok": True, "account_mode": bot.cfg.get("account_mode"), "accounts": bot.accounts_state()})

            if path == "/api/accounts/login":
                acc = bot.cfg.account(str(data.get("id", "")))
                if not acc:
                    return self._json({"ok": False, "error": "계정 없음"}, 404)
                bot.submit("login", acc_id=acc["id"])
                return self._json({"ok": True, "message": f"{acc['label']} 로그인 창을 엽니다(잠시만요)"})

            if path == "/api/accounts/check":
                acc = bot.cfg.account(str(data.get("id", "")))
                if not acc:
                    return self._json({"ok": False, "error": "계정 없음"}, 404)
                bot.submit("check", acc_id=acc["id"])
                return self._json({"ok": True, "message": "로그인 상태 확인 중"})

            return self._json({"ok": False, "error": "not found"}, 404)
        except Exception as e:
            LOG.add(f"대시보드 요청 오류({path}): {e}", "error")
            return self._json({"ok": False, "error": str(e)}, 500)


class DashboardServer(ThreadingHTTPServer):
    daemon_threads = True
    allow_reuse_address = True

    def __init__(self, addr, bot: "Bot"):
        self.bot = bot
        super().__init__(addr, DashboardHandler)


def start_dashboard(bot: "Bot", host: str = "127.0.0.1", port: int = 8765) -> DashboardServer:
    srv = DashboardServer((host, port), bot)
    t = threading.Thread(target=srv.serve_forever, name="dashboard", daemon=True)
    t.start()
    LOG.add(f"대시보드 열림 → http://{host}:{port}", "ok")
    return srv


# ---------------------------------------------------------------------------
# 자체 점검 (오프라인에서도 안전하게 돌 수 있는 검사)
# ---------------------------------------------------------------------------
def run_selftest() -> int:
    import tempfile

    passed, failed = [], []

    def check(name, cond, detail=""):
        (passed if cond else failed).append(f"{name}{(' — ' + detail) if detail else ''}")
        print(("PASS " if cond else "FAIL ") + name + (f" — {detail}" if detail else ""))

    tmp = Path(tempfile.mkdtemp(prefix="qna_selftest_"))
    try:
        # 1) 설정
        cfg = Config(tmp / "config.json")
        check("설정 기본값 로드", cfg["mode"] == "dry_run" and len(cfg["accounts"]) == 3)
        check("기본 headless=True(백그라운드)", cfg["browser"]["headless"] is True)
        check("기본 모델이 최신(gemini-3.8-flash)", cfg["gemini_model"] == "gemini-3.8-flash", str(cfg["gemini_model"]))
        check("기본 스캔 180초·답변 3건", cfg["scan_interval_sec"] == 180 and cfg["answer_limit_per_scan"] == 3,
              f"{cfg['scan_interval_sec']}s / {cfg['answer_limit_per_scan']}건")
        # 예전 config.json을 그대로 두고 실행해도 최신화되는지
        legacy = tmp / "legacy" / "config.json"
        legacy.parent.mkdir(parents=True, exist_ok=True)
        save_json(legacy, {
            "mode": "dry_run", "scan_interval_sec": 600, "answer_limit_per_scan": 10,
            "gemini_model": "gemini-2.0-flash",
            "gemini_fallback_models": ["gemini-2.0-flash", "gemini-2.0-flash-001", "gemini-1.5-flash"],
        })
        lcfg = Config(legacy)
        check("예전 config.json 자동 갱신",
              lcfg["gemini_model"] == "gemini-3.8-flash" and lcfg["scan_interval_sec"] == 180
              and lcfg["answer_limit_per_scan"] == 3 and lcfg["config_version"] == 2,
              f"{lcfg['gemini_model']} / {lcfg['scan_interval_sec']}s / {lcfg['answer_limit_per_scan']}건")
        check("원본 config.json.bak 백업", legacy.with_name("config.json.bak").exists())
        check("스레드 키워드", cfg["threads"]["keywords"] == ["사주", "오행", "신년운세", "일주", "용신"])
        check("X 키워드", cfg["x"]["keywords"] == ["韓国旅行", "ワウパス", "T-money", "仁川空港"])
        check("레딧 서브레딧", cfg["reddit"]["subreddits"] == ["koreatravel", "Seoul", "solotravel"])

        # 2) 계정 추가/로테이션
        acc2 = cfg.add_account("x", "X 계정 2")
        check("계정 추가(x_2)", acc2["id"] == "x_2" and acc2["profile_dir"] == "profiles/x_2")
        db = SeenDB(tmp / "seen.db")
        bot = Bot(cfg, db=db, no_browser=True)
        picks = []
        for _ in range(4):
            a = bot.pick_account("x")
            picks.append(a["id"] if a else None)
        check("X 계정 로테이션", picks[:2] == ["x_1", "x_2"] and picks[:4] == ["x_1", "x_2", "x_1", "x_2"], str(picks))

        # 3) 중복 방지
        item = {
            "id": "reddit_test1",
            "platform": "reddit",
            "sub": "koreatravel",
            "keyword": "koreatravel",
            "author": "u_test",
            "title": "How do I get from Incheon to Myeongdong?",
            "text": "",
            "url": "https://www.reddit.com/r/koreatravel/comments/test1/x/",
            "created_at": "",
        }
        check("새 글 저장", db.add_item(item) is True)
        check("중복 글 차단", db.add_item(item) is False)
        db.set_answer(item["id"], "AREX is easiest.", "template")
        db.mark_posted(item["id"], "posted", "reddit_1")
        since = (datetime.now(KST) - timedelta(hours=1)).isoformat(timespec="seconds")
        check("시간당 게시 수 집계", db.count_since("reddit", since) == 1)
        check("상태 저장", db.get(item["id"])["status"] == "posted")

        # 4) 레딧 API 응답 파싱/필터
        col = Collectors(cfg, bot.pool, db)
        now = time.time()
        fake = [
            {"id": "a1", "title": "Any tips for a first trip to Seoul?", "selftext": "3 days in April",
             "author": "u1", "created_utc": now - 3600, "permalink": "/r/koreatravel/comments/a1/x/",
             "num_comments": 3, "link_flair_text": "Question"},
            {"id": "a2", "title": "My trip report: 10 days in Korea", "selftext": "",
             "author": "u2", "created_utc": now - 3600, "permalink": "/r/koreatravel/comments/a2/x/",
             "num_comments": 3, "link_flair_text": "Trip Report"},
            {"id": "a3", "title": "Old question from a week ago?", "selftext": "",
             "author": "u3", "created_utc": now - 7 * 24 * 3600, "permalink": "/r/koreatravel/comments/a3/x/",
             "num_comments": 1, "link_flair_text": "Question"},
            {"id": "a4", "title": "So crowded these days", "selftext": "",
             "author": "u4", "created_utc": now - 3600, "permalink": "/r/koreatravel/comments/a4/x/",
             "num_comments": 1, "link_flair_text": ""},
        ]
        parsed = []
        for p in fake:
            parsed.extend(col._reddit_items(p, "koreatravel"))
        check("레딧 질문만 추림", [x["id"] for x in parsed] == ["reddit_a1"], str([x["id"] for x in parsed]))
        check("레딧 URL 구성", parsed and parsed[0]["url"].startswith("https://www.reddit.com/r/koreatravel/comments/a1"))

        # 5) 답변 엔진(지식 DB → 템플릿)
        eng = AnswerEngine(cfg)
        # 4-1) 지식 DB(100세트) 로드·매칭
        if eng.pack:
            check("지식 DB 100세트 로드", len(eng.pack) == 100, f"{len(eng.pack)}세트")
            ko_hit = eng.pack.match({"title": "", "text": "제 갑자일주 특징이 궁금해요"}, "ko")
            ja_hit = eng.pack.match({"title": "", "text": "T-moneyはどこで買えますか"}, "ja")
            en_hit = eng.pack.match({"title": "Best way from Incheon Airport to Seoul?", "text": ""}, "en")
            check("지식 DB 매칭(한/일/영)", bool(ko_hit and ja_hit and en_hit),
                  f"{ko_hit and ko_hit['id']} / {ja_hit and ja_hit['id']} / {en_hit and en_hit['id']}")
            got, engine_name = eng.generate({"id": "threads_kp1", "platform": "threads", "title": "",
                                             "keyword": "일주", "text": "갑자일주 연애 스타일 알려주세요"})
            check("API 키 없이 지식 DB가 답변", engine_name == "knowledge_pack" and len(got) > 80, engine_name)
            check("지식 DB 답변은 링크 없음", "http" not in got)
        else:
            check("지식 DB 100세트 로드", False, "qna_knowledge_pack.json 없음")

        ko = eng.generate({"id": "threads_x1", "platform": "threads", "title": "", "keyword": "일주",
                           "text": "제 일주가 뭔지 궁금해서요. 요즘 일이 너무 안 풀려요."})
        ja = eng.generate({"id": "x_x1", "platform": "x", "title": "", "keyword": "T-money",
                           "text": "T-moneyってどこで買えますか？"})
        en = eng.generate({"id": "reddit_x1", "platform": "reddit", "title": "How to get to Seoul from Incheon?",
                           "keyword": "koreatravel", "text": ""})
        check("스레드 답변 생성", ko[1] in ("template", "knowledge_pack") and 40 < len(ko[0]) < 600, ko[1])
        check("Gemini 키 없으면 지식DB/템플릿", ja[1] in ("template", "knowledge_pack") and en[1] in ("template", "knowledge_pack"))
        check("스레드 구어체(보고서 톤 없음)", "하시기 바랍니다" not in ko[0] and "1." not in ko[0])
        check("이모지 없음", not re.search(r"[\U0001F300-\U0001FAFF\u2600-\u27BF]", ko[0] + ja[0] + en[0]))
        check("스레드 말투(스친님/구어체)", ko[0].startswith("스친님") or re.search(r"(요|다)[.!]?$", ko[0]) is not None)
        check("일본어 X 템플릿", re.search(r"[ぁ-ん]", ja[0]) is not None and len(ja[0]) < 400)
        check("레딧 영어 템플릿", re.search(r"Honestly|Yeah|Pro tip|T-money|AREX", en[0]) is not None)

        # 5-2) 모델 로테이션·토큰 하한
        check("최신 모델 우선 시도", eng._model_list()[:3] == ["gemini-3.8-flash", "gemini-3.6-flash", "gemini-3.5-flash-lite"],
              str(eng._model_list()[:4]))
        old_cfg = Config(tmp / "oldmodel.json")
        old_cfg.data["config_version"] = 2
        old_cfg.set("gemini_model", "gemini-2.0-flash")
        old_cfg.set("gemini_fallback_models", ["gemini-2.0-flash", "gemini-1.5-flash"])
        old_eng = AnswerEngine(old_cfg)
        check("config가 구모델이어도 최신 모델 먼저", old_eng._model_list()[0] == "gemini-3.8-flash"
              and "gemini-2.0-flash" not in old_eng._model_list(), str(old_eng._model_list()))
        old_cfg.set("gemini_max_output_tokens", 512)
        check("maxOutputTokens 최소 2048 보장", old_eng._output_tokens() >= 2048, str(old_eng._output_tokens()))

        # 5-3) 503이면 1.5초 후 다음 모델로 넘어가는지 (네트워크 없이 모의)
        calls: list[tuple[str, int]] = []
        real_post = globals()["http_post_json"]

        def fake_post(url, payload, timeout=60, headers=None):
            model = urllib.parse.unquote(url.split("/models/")[1].split(":")[0])
            calls.append((model, int(payload["generationConfig"]["maxOutputTokens"])))
            if len(calls) == 1:
                return 503, {}
            return 200, {"candidates": [{"content": {"parts": [{"text": "모의 답변입니다."}]}, "finishReason": "STOP"}]}

        globals()["http_post_json"] = fake_post
        try:
            mcfg = Config(tmp / "mock.json")
            mcfg.set("gemini_api_key", "test-key")
            meng = AnswerEngine(mcfg)
            got = meng._gemini(
                {"platform": "threads", "title": "", "text": "사주 질문이요", "keyword": "사주", "author": "tester"},
                "사주 질문이요", "ko",
            )
            check("503 → 다음 모델로 자동 재시도", got == "모의 답변입니다." and len(calls) >= 2, str(calls[:2]))
            check("실제 요청 토큰 2048 이상", all(t >= 2048 for _, t in calls), str(calls[:2]))
        finally:
            globals()["http_post_json"] = real_post

        # 5-4) 플랫폼 라운드 로빈 (스레드에 몰리지 않게)
        rr = bot._rr_order([
            {"id": "t1", "platform": "threads"}, {"id": "t2", "platform": "threads"},
            {"id": "t3", "platform": "threads"}, {"id": "x1", "platform": "x"},
            {"id": "r1", "platform": "reddit"},
        ])
        check("플랫폼 라운드 로빈", [i["platform"] for i in rr[:3]] == ["threads", "x", "reddit"],
              str([i["id"] for i in rr]))

        # 5-5) 스레드 화면 처리 헬퍼
        po = Poster(cfg, bot.pool)
        check("스레드 주소 threads.com 정규화",
              po._threads_post_url("https://www.threads.net/@a/post/Bc") == "https://www.threads.com/@a/post/Bc")
        check("스레드 답글 아이콘 이름(한/영)", len(THREADS_REPLY_LABELS) >= 4
              and all(k in THREADS_REPLY_LABELS for k in ("답글", "Reply", "댓글")))
        check("스레드 답글 처리 함수", all(hasattr(po, n) for n in (
            "_find_threads_composer", "_open_threads_composer", "_threads_editor_text",
            "_threads_editor_cleared", "_threads_page_state", "_threads_fail_report",
            "_threads_fill_composer", "_threads_composer_paste", "_threads_composer_exec")))
        # v1.1.1: 한국어 스레드는 컬럼 이름이 '칼럼 본문', 입력창은 aria-label '텍스트 필드가 비어 있습니다'
        check("스레드 입력창 선택자(한국어 aria-label)",
              any("텍스트 필드가 비어 있습니다" in s for s in THREADS_COMPOSER_DIRECT)
              and any('aria-label="칼럼 본문"' in s for s in THREADS_COMPOSER_COLUMN_SCOPES))
        check("스레드 입력창 선택자(영문 UI)",
              any("Empty text field" in s for s in THREADS_COMPOSER_DIRECT)
              and any('aria-label="Column body"' in s for s in THREADS_COMPOSER_COLUMN_SCOPES))
        src_fill = (inspect.getsource(po._threads_fill_composer)
                    + inspect.getsource(po._threads_composer_paste)
                    + inspect.getsource(po._threads_composer_exec))
        check("스레드 입력 3단계(insert_text → paste → type)",
              all(k in src_fill for k in ("insert_text", "ClipboardEvent('paste'", "execCommand('insertText'",
                                          "keyboard.type")))
        check("입력 확인은 잡아 둔 입력창으로(다시 찾지 않음)",
              "_threads_editor_text(composer=composer)" in inspect.getsource(po._threads_fill_composer))

        # 6) 대시보드 서버
        srv = start_dashboard(bot, "127.0.0.1", 0)
        port = srv.server_address[1]
        import urllib.request as u2

        def api(path, payload=None):
            url = f"http://127.0.0.1:{port}{path}"
            data = json.dumps(payload).encode() if payload is not None else None
            req = u2.Request(url, data=data, headers={"Content-Type": "application/json"}, method="POST" if data else "GET")
            with u2.urlopen(req, timeout=10) as r:
                return r.status, json.loads(r.read().decode())

        st, html_page = None, ""
        with u2.urlopen(f"http://127.0.0.1:{port}/", timeout=10) as r:
            st = r.status
            html_page = r.read().decode("utf-8")
        check("대시보드 페이지", st == 200 and "자동 댓글" in html_page and "계정 관리" in html_page)
        code, state = api("/api/state")
        check("상태 API", code == 200 and state["app"] == APP_NAME and len(state["items"]) >= 1)
        code, r = api("/api/auto", {"on": True})
        check("자동 토글 API", code == 200 and r["mode"] == "auto" and bot.mode == "auto")
        code, r = api("/api/auto", {"on": False})
        check("자동 OFF API", code == 200 and r["mode"] == "dry_run")
        code, r = api("/api/accounts/add", {"platform": "threads", "label": "스레드 계정 2"})
        check("계정 추가 API", code == 200 and r["account"]["id"] == "threads_2")
        code, r = api("/api/accounts/toggle", {"id": "threads_2", "enabled": False})
        check("계정 활성 토글 API", code == 200 and any(a["id"] == "threads_2" and not a["enabled"] for a in r["accounts"]))
        code, r = api("/api/accounts/pin", {"id": "x_2"})
        check("계정 고정 API", code == 200 and r["account_mode"] == "single")
        code, r = api("/api/accounts/pin", {"id": ""})
        check("로테이션 복귀 API", code == 200 and r["account_mode"] == "rotation")
        code, r = api("/api/config", {"gemini_api_key": ""})
        check("Gemini 키 저장 API", code == 200 and r["gemini"]["configured"] is False)
        srv.shutdown()

        # 7) 대시보드 HTML 정합성 (JS가 찾는 id가 실제로 있는지)
        html_path = BOT_DIR / "dashboard.html"
        if html_path.exists():
            doc = html_path.read_text(encoding="utf-8")
            js = doc.split("<script>")[-1].split("</script>")[0]
            used = set(re.findall(r'\$\("#([A-Za-z0-9_]+)"\)', js)) | set(re.findall(r'\$\("#([A-Za-z0-9_]+)"\)', doc))
            defined = set(re.findall(r'id="([A-Za-z0-9_]+)"', doc))
            missing = sorted(used - defined)
            check("대시보드 화면 요소", not missing, "누락: " + ", ".join(missing) if missing else "")
            check("대시보드 필수 문구", all(k in doc for k in ("자동 댓글", "계정 관리", "지금 1회 스캔")))
        else:
            check("대시보드 화면 파일", False, "dashboard.html 없음")

        # 8) 레딧 실 API 응답 형식(네트워크 없으면 건너뜀)
        try:
            status, body = 0, b""
            for attempt in range(2):
                status, body = http_get(cfg["reddit"]["api"].format(sub="koreatravel", limit=3), timeout=25)
                if status == 200:
                    break
                time.sleep(4)
            if status == 200:
                ok = isinstance(json.loads(body.decode())["data"], list)
                check("레딧 공개 API 응답", ok, f"HTTP {status}")
            else:
                print(f"SKIP 레딧 공개 API 응답 — 서버 일시 오류 HTTP {status} (PC에서는 재시도됩니다)")
        except Exception as e:
            print(f"SKIP 레딧 공개 API 응답 — 네트워크 오류: {str(e)[:100]}")
    finally:
        try:
            shutil.rmtree(tmp, ignore_errors=True)
        except Exception:
            pass

    print(f"\n결과: {len(passed)}개 통과, {len(failed)}개 실패")
    if failed:
        for f in failed:
            print("  실패:", f)
        return 1
    return 0


def probe_threads(cfg: Config, url: str, show: bool = False) -> int:
    """스레드 글 페이지를 실제로 열어 '답글을 달 수 있는 화면인지'만 확인한다(게시 안 함).

    사용법: python qna_bot.py --probe-threads "https://www.threads.com/@아이디/post/코드" --show-browser
    """
    pool = BrowserPool(cfg)
    acc = next((a for a in cfg.accounts("threads") if a.get("enabled")), None)
    if not acc:
        print("활성화된 스레드 계정이 없습니다. 대시보드 → 계정 관리에서 켜 주세요.")
        return 2
    poster = Poster(cfg, pool)
    try:
        page = pool.page(acc, headless=not show)
        page.goto(poster._threads_post_url(url), wait_until="domcontentloaded", timeout=45000)
        page.wait_for_timeout(6000)
        state = poster._threads_page_state(page)
        print(f"최종 주소 : {page.url}")
        print(f"화면 상태 : {state} (ok=정상, login=로그인 필요, error=스레드 오류 화면, empty=빈 화면)")
        composer = poster._find_threads_composer(page)
        print(f"답글 입력창: {'있음 ✓ 바로 입력 가능' if composer else '없음'}")
        if composer is None and poster._open_threads_composer(page):
            page.wait_for_timeout(2000)
            composer = poster._find_threads_composer(page)
            print(f"답글 아이콘 클릭 후: {'있음 ✓' if composer else '없음 ✗'}")
        labels = page.evaluate(
            """() => {
                const seen = new Set(); const out = [];
                document.querySelectorAll('svg[aria-label]').forEach(e => {
                    const r = e.getBoundingClientRect();
                    if (r.width === 0 && r.height === 0) return;
                    const v = e.getAttribute('aria-label');
                    if (!seen.has(v)) { seen.add(v); out.push(v); }
                });
                return out.slice(0, 40);
            }"""
        ) or []
        print("아이콘 이름(aria-label):", " / ".join(labels))
        shot = BOT_DIR / "logs" / "threads_probe.png"
        shot.parent.mkdir(parents=True, exist_ok=True)
        page.screenshot(path=str(shot))
        print(f"화면 캐처: {shot}")
        return 0 if composer else 1
    finally:
        try:
            pool.shutdown()
        except Exception:
            pass


# ---------------------------------------------------------------------------
# 실행 진입점
# ---------------------------------------------------------------------------
def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=f"{APP_NAME} — 스레드·X·레딧 질문 수집 및 자동 답변")
    ap.add_argument("--config", default=str(BOT_DIR / "config.json"), help="설정 파일 경로")
    ap.add_argument("--once", action="store_true", help="한 번만 스캔하고 종료")
    ap.add_argument("--dry-run", action="store_true", help="이번 실행은 초안만(설정은 그대로)")
    ap.add_argument("--auto", action="store_true", help="이번 실행은 실제 게시")
    ap.add_argument("--no-browser", action="store_true", help="브라우저(스레드·X) 없이 레딧만")
    ap.add_argument("--no-ui", action="store_true", help="대시보드 없이 실행")
    ap.add_argument("--port", type=int, default=None, help="대시보드 포트(기본 8765)")
    ap.add_argument("--open-browser", action="store_true", help="시작 시 대시보드를 기본 브라우저로 열기")
    ap.add_argument("--headless", dest="headless", action="store_true", default=None, help="브라우저 창 숨김(기본)")
    ap.add_argument("--show-browser", dest="headless", action="store_false", help="브라우저 창 표시")
    ap.add_argument("--selftest", action="store_true", help="설치/설정/대시보드 자체 점검")
    ap.add_argument("--probe-threads", metavar="URL", default=None,
                    help="스레드 글 페이지를 열어 답글 입력창이 보이는지 진단만 하고 종료(게시 안 함)")
    args = ap.parse_args(argv)

    if args.selftest:
        return run_selftest()

    cfg = Config(Path(args.config))
    if args.probe_threads:
        return probe_threads(cfg, args.probe_threads, show=bool(args.show_browser))
    if args.headless is not None:
        cfg.data.setdefault("browser", {})["headless"] = bool(args.headless)
    port = args.port or int(cfg.get("ui", {}).get("port", 8765))
    mode_override = "dry_run" if args.dry_run else ("auto" if args.auto else None)
    bot = Bot(cfg, no_browser=args.no_browser, mode_override=mode_override)

    print("=" * 62)
    print(f"  {APP_NAME} v{VERSION}")
    print(f"  모드: {'자동 댓글 ON (실제 게시)' if bot.mode == 'auto' else '초안만 (dry_run)'}"
          f"   헤드리스: {cfg['browser']['headless']}")
    print("=" * 62)

    if args.once:
        res = bot.scan_once()
        print("\n결과:", json.dumps(res, ensure_ascii=False))
        bot.pool.shutdown()
        return 0 if res.get("ok") else 1

    srv = None
    if not args.no_ui:
        try:
            srv = start_dashboard(bot, cfg["ui"]["host"], port)
            url = f"http://{cfg['ui']['host']}:{port}"
            print(f"\n  대시보드: {url}\n")
            if args.open_browser or cfg["ui"].get("open", True):
                try:
                    webbrowser.open(url)
                except Exception:
                    pass
        except OSError as e:
            LOG.add(f"대시보드 포트 {port} 사용 실패: {e} — 봇은 계속 실행합니다", "warn")

    try:
        bot.run_forever()
    except KeyboardInterrupt:
        bot.stop.set()
    finally:
        if srv:
            try:
                srv.shutdown()
            except Exception:
                pass
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
