# -*- coding: utf-8 -*-
"""
V2-022 Draft Eligibility Debug

목적:
- Collect 결과는 있는데 Draft 대상이 0건인 이유를 article_no별로 확인한다.
- fetch_target_articles_for_realtor() 조건과 동일한 핵심 필터를 점검한다.
- V2 DraftBridge가 막히는 원인을 빠르게 찾기 위한 운영 진단 도구.

위치:
  D:/honghee/blog_api/tools/v2_debug_draft_eligibility.py

실행:
  cd /d D:/honghee/blog_api
  python tools/v2_debug_draft_eligibility.py --realtor-id 1 --limit 20
"""

import argparse
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from db import get_conn


INVALID_NAMES = {
    "",
    "네이버 부동산 후보 매물",
    "네이버 부동산 현재 매물",
    "네이버 부동산 매물",
    "부동산 매물",
    "현재 매물",
    "추천 매물",
}


def clean(value):
    return str(value or "").strip()


def count_rows(cur, sql, params):
    cur.execute(sql, params)
    row = cur.fetchone()
    if isinstance(row, dict):
        return int(list(row.values())[0] or 0)
    return int(row[0] or 0)


def check_article(cur, row):
    article_no = clean(row.get("article_no"))
    reasons = []

    collect_status = clean(row.get("collect_status"))
    detail_collected = int(row.get("detail_collected") or 0)
    article_name = clean(row.get("article_name"))
    price_text = clean(row.get("price_text"))

    if collect_status != "collected":
        reasons.append(f"collect_status={collect_status or 'EMPTY'}")

    if detail_collected != 1:
        reasons.append(f"detail_collected={detail_collected}")

    if article_name in INVALID_NAMES:
        reasons.append("invalid_article_name")

    if not price_text:
        reasons.append("price_text_empty")

    image_count = count_rows(
        cur,
        """
        SELECT COUNT(*)
        FROM blog_realestate_article_images
        WHERE CONVERT(article_no USING utf8mb4) COLLATE utf8mb4_unicode_ci
              =
              CONVERT(%s USING utf8mb4) COLLATE utf8mb4_unicode_ci
        """,
        (article_no,),
    )

    if image_count <= 0:
        reasons.append("image_empty")

    draft_count = count_rows(
        cur,
        """
        SELECT COUNT(*)
        FROM blog_article_drafts
        WHERE CONVERT(article_no USING utf8mb4) COLLATE utf8mb4_unicode_ci
              =
              CONVERT(%s USING utf8mb4) COLLATE utf8mb4_unicode_ci
        """,
        (article_no,),
    )

    if draft_count > 0:
        reasons.append("draft_exists")

    queue_count = 0
    try:
        queue_count = count_rows(
            cur,
            """
            SELECT COUNT(*)
            FROM blog_publish_queue
            WHERE article_no IS NOT NULL
              AND CONVERT(article_no USING utf8mb4) COLLATE utf8mb4_unicode_ci
                  =
                  CONVERT(%s USING utf8mb4) COLLATE utf8mb4_unicode_ci
              AND COALESCE(queue_status, '') IN (
                    'waiting',
                    'pending',
                    'ready',
                    'processing',
                    'published',
                    'success',
                    'done'
              )
            """,
            (article_no,),
        )
    except Exception as e:
        reasons.append(f"queue_check_error={e}")

    if queue_count > 0:
        reasons.append("publish_queue_exists")

    eligible = len(reasons) == 0

    return {
        "article_no": article_no,
        "article_name": article_name,
        "price_text": price_text,
        "collect_status": collect_status,
        "detail_collected": detail_collected,
        "image_count": image_count,
        "draft_count": draft_count,
        "queue_count": queue_count,
        "eligible": eligible,
        "reasons": reasons,
    }


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--realtor-id", type=int, required=True)
    parser.add_argument("--limit", type=int, default=20)
    args = parser.parse_args()

    conn = get_conn()

    try:
        with conn.cursor() as cur:
            cur.execute(
                """
                SELECT
                    id,
                    realtor_id,
                    article_no,
                    article_name,
                    collect_status,
                    detail_collected,
                    price_text,
                    created_at,
                    updated_at
                FROM blog_realtor_articles
                WHERE realtor_id=%s
                ORDER BY
                    COALESCE(first_posted_at, created_at) DESC,
                    id DESC
                LIMIT %s
                """,
                (int(args.realtor_id), int(args.limit)),
            )
            rows = cur.fetchall() or []

            results = [check_article(cur, dict(row)) for row in rows]

        print("=" * 100)
        print("[V2-022 DRAFT ELIGIBILITY DEBUG]")
        print("realtor_id:", args.realtor_id)
        print("checked:", len(results))
        print("-" * 100)

        eligible_count = 0
        for idx, item in enumerate(results, start=1):
            if item["eligible"]:
                eligible_count += 1
                status = "PASS"
            else:
                status = "SKIP"

            print(f"[{idx:02d}] {status} article_no={item['article_no']}")
            print(f"     name={item['article_name']}")
            print(
                "     "
                f"collect_status={item['collect_status']} "
                f"detail_collected={item['detail_collected']} "
                f"price={'Y' if item['price_text'] else 'N'} "
                f"images={item['image_count']} "
                f"drafts={item['draft_count']} "
                f"queues={item['queue_count']}"
            )

            if item["reasons"]:
                print("     reasons=" + ", ".join(item["reasons"]))
            else:
                print("     reasons=(none)")

        print("-" * 100)
        print("eligible_count:", eligible_count)
        print("skipped_count:", len(results) - eligible_count)
        print("=" * 100)

    finally:
        conn.close()


if __name__ == "__main__":
    main()
