# -*- coding: utf-8 -*-
"""
운영 초안 생성 복구 패치 2차
- 소재지 주소 우선순위 보강
- 단지/complex 주소, 도로명 주소, 지번 주소를 article exposureAddress보다 우선 사용

사용:
  cd /d D:\honghee\blog_api
  python tools\patch_operating_complex_address.py
"""

from pathlib import Path
from datetime import datetime

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

if not TARGET.exists():
    raise FileNotFoundError(TARGET)

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

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

helper = """
def extract_complex_display_address(raw, article_detail=None):
    \"""
    운영 복구 정책:
    - 매물 소재지는 article exposureAddress보다 단지/complex 주소를 우선 사용한다.
    - 네이버 단지 정보에서 도로명/지번 주소가 있으면 함께 표기한다.
    \"""
    article_detail = article_detail or {}
    raw = raw or {}

    if isinstance(raw, str):
        raw = parse_json_safely(raw)

    if not isinstance(raw, dict):
        raw = {}

    road_keys = {
        "roadAddress", "roadAddressName", "road_address", "road_address_name",
        "roadNameAddress", "roadAddr", "road_addr", "newAddress",
        "new_address", "rnAddr", "roadBaseAddress",
    }

    jibun_keys = {
        "jibunAddress", "jibunAddressName", "jibun_address", "jibun_address_name",
        "address", "addressName", "oldAddress", "old_address", "lotAddress",
        "lot_address", "dongAddress", "bunjiAddress",
    }

    general_keys = {
        "complexAddress", "complex_address", "fullAddress", "full_address",
        "address", "addressName", "exposureAddress", "detailAddress",
    }

    complex_hint_keys = {
        "complex", "hscp", "overview", "complexInfo", "complexDetail",
        "complexOverview", "complexArticle", "danji", "단지"
    }

    road = ""
    jibun = ""
    general = ""

    def clean_addr(v):
        v = clean_text(v)
        if not v:
            return ""
        if "http://" in v or "https://" in v or "<" in v or ">" in v:
            return ""
        if len(v) < 4:
            return ""
        if v in ["아파트", "오피스텔", "주상복합"]:
            return ""
        return v

    def visit(obj, in_complex=False):
        nonlocal road, jibun, general

        if isinstance(obj, dict):
            local_complex = in_complex or any(str(k) in complex_hint_keys for k in obj.keys())

            for k, v in obj.items():
                key = str(k)

                if isinstance(v, (dict, list)):
                    visit(v, local_complex or any(h.lower() in key.lower() for h in complex_hint_keys))
                    continue

                if not local_complex:
                    continue

                value = clean_addr(v)
                if not value:
                    continue

                if not road and key in road_keys:
                    road = value
                elif not jibun and key in jibun_keys:
                    jibun = value
                elif not general and key in general_keys:
                    general = value

        elif isinstance(obj, list):
            for item in obj:
                visit(item, in_complex)

    preferred_roots = [
        raw.get("complex"),
        raw.get("complexInfo"),
        raw.get("complexDetail"),
        raw.get("complexOverview"),
        raw.get("complexOverviewResponse"),
        raw.get("complexArticle"),
        raw.get("complexAddress"),
        raw.get("hscp"),
        raw.get("hscpInfo"),
        raw.get("overview"),
        raw.get("articleComplex"),
    ]

    for root_obj in preferred_roots:
        if root_obj:
            visit(root_obj, True)

    if not (road or jibun or general):
        visit(raw, False)

    if isinstance(article_detail, dict):
        for key in road_keys:
            if not road and clean_addr(article_detail.get(key)):
                road = clean_addr(article_detail.get(key))

        for key in jibun_keys:
            if not jibun and clean_addr(article_detail.get(key)):
                jibun = clean_addr(article_detail.get(key))

    if road and jibun and road != jibun:
        return f"{road}\\n지번 {jibun}"

    if road:
        return road

    if jibun:
        return jibun

    if general:
        return general

    return ""
"""

if "def extract_complex_display_address(" not in text:
    anchor = "def extract_broker_description(detail):"
    if anchor not in text:
        raise RuntimeError("anchor not found: extract_broker_description")
    text = text.replace(anchor, helper + "\n\n" + anchor, 1)
    print("[PATCH] helper inserted")
else:
    print("[SKIP] helper already exists")

old = '    set_if_empty("address", article_detail.get("exposureAddress"), article_realtor.get("address") if (article_realtor := raw.get("articleRealtor") or {}) else "")'

new = """    article_realtor = raw.get("articleRealtor") or {}
    complex_display_address = extract_complex_display_address(raw, article_detail)
    if complex_display_address:
        print("[COMPLEX DISPLAY ADDRESS USED]", complex_display_address.replace("\\\\n", " / "))
    set_if_empty(
        "address",
        complex_display_address,
        article_detail.get("exposureAddress"),
        article_realtor.get("address") if article_realtor else "",
    )"""

if old in text:
    text = text.replace(old, new, 1)
    print("[PATCH] address priority replaced")
elif "complex_display_address = extract_complex_display_address(raw, article_detail)" in text:
    print("[SKIP] address priority already patched")
else:
    raise RuntimeError("address set_if_empty line not found")

TARGET.write_text(text, encoding="utf-8")
print("[DONE] patched complex address policy")
print("[TARGET]", TARGET)
