# -*- coding: utf-8 -*-
"""
STEP111-06 Draft Type Debugger

운영 코드는 수정하지 않고 특정 매물/초안의 매물유형 판별 흐름을 확인한다.

사용:
  cd /d D:\honghee\blog_api
  python tools\debug_draft_property_type_flow.py --realtor-id 5 --article-nos 2633005438,2632364259
"""

import argparse
import json
import re
import sys
from pathlib import Path
from html import unescape

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

from db import get_conn

from jobs.generate_blog_drafts import (
    detect_property_type_for_header,
    detect_law_target_type,
    enrich_detail_from_raw_json_for_property_type,
)


def clean_text_local(value):
    value = "" if value is None else str(value)
    value = unescape(value)
    value = re.sub(r"<[^>]+>", " ", value)
    value = re.sub(r"\s+", " ", value)
    return value.strip()


def get_raw_type_info(raw_json):
    try:
        raw = json.loads(raw_json or "{}")
    except Exception:
        raw = {}

    article_detail = raw.get("articleDetail") or {}
    article_addition = raw.get("articleAddition") or {}

    return {
        "articleDetail.realestateTypeName": article_detail.get("realestateTypeName"),
        "articleAddition.articleRealEstateTypeName": article_addition.get("articleRealEstateTypeName"),
        "articleAddition.realEstateTypeName": article_addition.get("realEstateTypeName"),
        "articleDetail.articleTypeCode": article_detail.get("articleTypeCode"),
        "articleAddition.articleRealEstateTypeCode": article_addition.get("articleRealEstateTypeCode"),
        "articleAddition.realEstateTypeCode": article_addition.get("realEstateTypeCode"),
        "articleDetail.tradeBuildingTypeCode": article_detail.get("tradeBuildingTypeCode"),
        "articleDetail.realestateTypeCode": article_detail.get("realestateTypeCode"),
    }


def fetch_article(conn, realtor_id, article_no):
    with conn.cursor() as cur:
        cur.execute(
            """
            SELECT *
            FROM blog_realtor_articles
            WHERE realtor_id=%s AND article_no=%s
            LIMIT 1
            """,
            (int(realtor_id), str(article_no)),
        )
        return cur.fetchone()


def fetch_latest_drafts(conn, realtor_id, article_no, limit=5):
    with conn.cursor() as cur:
        cur.execute(
            """
            SELECT
                id,
                realtor_id,
                article_no,
                draft_title,
                status,
                draft_status,
                created_at,
                updated_at,
                LEFT(COALESCE(clipboard_html, draft_html, ''), 2000) AS html_head,
                CHAR_LENGTH(COALESCE(clipboard_html, draft_html, '')) AS html_len
            FROM blog_article_drafts
            WHERE realtor_id=%s AND article_no=%s
            ORDER BY id DESC
            LIMIT %s
            """,
            (int(realtor_id), str(article_no), int(limit)),
        )
        return cur.fetchall()


def extract_first_h2(html):
    m = re.search(r"<h2[^>]*>(.*?)</h2>", html or "", flags=re.I | re.S)
    if not m:
        return ""
    return clean_text_local(m.group(1))


def detect_html_flags(html):
    text = clean_text_local(html)
    return {
        "first_h2": extract_first_h2(html),
        "has_togi_overview": "토지 개요" in text,
        "has_togi_core": "토지 핵심 정보" in text,
        "has_togi_check": "토지 확인 포인트" in text,
        "has_land_use": "활용 가능성" in text,
        "has_invest_point": "투자 검토 포인트" in text,
        "has_building_disclosure": "중개대상물 명시사항 - 건축물" in text,
        "has_land_disclosure": "중개대상물 명시사항 - 토지" in text,
        "has_apt_header": "header_APT_" in (html or ""),
    }


def print_report(realtor_id, article_no, article, enriched, drafts):
    print("=" * 100)
    print("[STEP111-06 DRAFT PROPERTY TYPE FLOW DEBUG]")
    print("realtor_id:", realtor_id)
    print("article_no:", article_no)
    print("-" * 100)

    if not article:
        print("[ARTICLE NOT FOUND]")
        return

    print("[DB ARTICLE]")
    print("id:", article.get("id"))
    print("article_name:", article.get("article_name"))
    print("building_name:", article.get("building_name"))
    print("real_estate_type:", article.get("real_estate_type"))
    print("detail_collected:", article.get("detail_collected"))
    print("has_raw_json:", bool(article.get("raw_json")))
    print("-" * 100)

    print("[RAW JSON TYPE]")
    for k, v in get_raw_type_info(article.get("raw_json")).items():
        print(f"{k}: {v}")
    print("-" * 100)

    print("[ENRICHED DETAIL]")
    for k in [
        "real_estate_type",
        "real_estate_type_name",
        "_raw_article_real_estate_type_name",
        "_raw_realestate_type_name",
        "_raw_article_type_code",
        "_raw_realestate_type_code",
    ]:
        print(f"{k}: {enriched.get(k)}")
    print("-" * 100)

    try:
        header_type = detect_property_type_for_header(enriched)
    except Exception as e:
        header_type = f"ERROR: {e}"

    try:
        law_type = detect_law_target_type(enriched)
    except Exception as e:
        law_type = f"ERROR: {e}"

    print("[DETECTORS]")
    print("detect_property_type_for_header(enriched):", header_type)
    print("detect_law_target_type(enriched):", law_type)
    print("-" * 100)

    print("[LATEST DRAFTS]")
    if not drafts:
        print("(none)")

    for d in drafts:
        html = d.get("html_head") or ""
        flags = detect_html_flags(html)
        print("-" * 60)
        print("draft_id:", d.get("id"))
        print("title:", d.get("draft_title"))
        print("status:", d.get("status"), "draft_status:", d.get("draft_status"))
        print("created_at:", d.get("created_at"), "updated_at:", d.get("updated_at"))
        print("html_len:", d.get("html_len"))
        print("flags:", json.dumps(flags, ensure_ascii=False))
        print("html_head_sample:")
        print(html[:800].replace("\n", "\\n"))
    print("=" * 100)


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

    if args.article_nos:
        article_nos = [x.strip() for x in args.article_nos.split(",") if x.strip()]
    elif args.article_no:
        article_nos = [args.article_no.strip()]
    else:
        raise RuntimeError("--article-no 또는 --article-nos 필요")

    conn = get_conn()
    try:
        for article_no in article_nos:
            article = fetch_article(conn, args.realtor_id, article_no)
            enriched = enrich_detail_from_raw_json_for_property_type(article or {})
            drafts = fetch_latest_drafts(conn, args.realtor_id, article_no)
            print_report(args.realtor_id, article_no, article, enriched, drafts)
    finally:
        conn.close()


if __name__ == "__main__":
    main()
