# -*- coding: utf-8 -*-
'''
STEP111-13 Patch: HEE Layout Recommendation Log Mode

사용:
  cd /d D:\honghee\blog_api
  python tools\patch_hee_layout_log_mode.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_hee_layout_log_{datetime.now().strftime('%Y%m%d_%H%M%S')}.py"
)
backup.write_text(text, encoding='utf-8')
print('[BACKUP]', backup)

helper_code = r"""

# ---------------------------------------------------------
# STEP111-13 HEE Layout Recommendation - Log Only
# ---------------------------------------------------------
def _hee_clean_text_for_layout(value):
    import re
    from html import unescape
    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 _hee_detect_property_class_for_layout(detail):
    raw = parse_json_safely(detail.get("raw_json"))
    article_detail = raw.get("articleDetail") if isinstance(raw, dict) else {}
    article_addition = raw.get("articleAddition") if isinstance(raw, dict) else {}

    type_name = _hee_clean_text_for_layout(
        detail.get("real_estate_type")
        or detail.get("real_estate_type_name")
        or (article_detail.get("realestateTypeName") if isinstance(article_detail, dict) else "")
        or (article_addition.get("articleRealEstateTypeName") if isinstance(article_addition, dict) else "")
        or (article_addition.get("realEstateTypeName") if isinstance(article_addition, dict) else "")
    )

    type_code = _hee_clean_text_for_layout(
        (article_detail.get("articleTypeCode") if isinstance(article_detail, dict) else "")
        or (article_detail.get("realestateTypeCode") if isinstance(article_detail, dict) else "")
        or (article_addition.get("articleRealEstateTypeCode") if isinstance(article_addition, dict) else "")
        or (article_addition.get("realEstateTypeCode") if isinstance(article_addition, dict) else "")
    ).upper()

    if type_name in ["아파트"] or type_code in ["A01", "APT"]:
        return "apartment"
    if type_name in ["오피스텔"]:
        return "officetel"
    if type_name in ["빌라", "연립", "다세대", "주택"]:
        return "villa_house"
    if type_name in ["상가", "상가점포"]:
        return "store"
    if type_name in ["사무실"]:
        return "office"
    if type_name in ["공장", "창고"]:
        return "factory_warehouse"
    if type_name in ["토지", "대", "전", "답", "임야", "대지", "잡종지", "공장용지", "창고용지"] or type_code in ["TJ", "LAND", "TOJI", "E03"]:
        return "land"
    if type_name in ["분양권", "입주권"]:
        return "presale_right"

    return "unknown"


def _hee_layout_mode_from_detail(detail, images, ai_sections=None):
    property_class = _hee_detect_property_class_for_layout(detail)

    try:
        image_count = len(images or [])
    except Exception:
        image_count = 0

    broker_desc = _hee_clean_text_for_layout(
        detail.get("article_feature_desc")
        or detail.get("article_desc")
        or detail.get("article_description")
        or ""
    )
    broker_desc_len = len(broker_desc)

    if broker_desc_len <= 0 and ai_sections:
        broker_desc_len = len(_hee_clean_text_for_layout((ai_sections or {}).get("intro") or ""))

    if image_count <= 0 and broker_desc_len < 20:
        base = "minimal"
    elif image_count <= 1 or broker_desc_len < 40:
        base = "compact"
    elif image_count <= 4 or broker_desc_len < 80:
        base = "simple"
    elif image_count <= 10:
        base = "balanced"
    else:
        base = "rich"

    if property_class == "land":
        layout_mode = f"land_{base}"
    elif property_class == "factory_warehouse":
        layout_mode = f"factory_{base}"
    elif property_class in ["store", "office"]:
        layout_mode = f"business_{base}"
    elif property_class in ["apartment", "officetel", "villa_house", "presale_right"]:
        layout_mode = f"living_{base}"
    else:
        layout_mode = f"generic_{base}"

    return {
        "property_class": property_class,
        "image_count": image_count,
        "broker_desc_len": broker_desc_len,
        "layout_mode": layout_mode,
    }


def _hee_recommended_layout_type(layout_mode, realtor_id=None, article_no=None):
    import random

    candidates_map = {
        "living_rich": ["storytelling", "magazine_style", "local_life", "family_recommend", "premium_report", "gallery_story"],
        "living_balanced": ["story_first", "location_focus", "recommendation_focus", "storytelling", "local_life", "photo_grid"],
        "living_simple": ["summary_first", "minimal_modern", "short_review_style", "checklist_style"],
        "living_compact": ["summary_first", "minimal_modern", "checklist_style"],
        "living_minimal": ["summary_first", "minimal_modern"],

        "business_rich": ["office_focus", "location_focus", "broker_expert", "premium_report"],
        "business_balanced": ["office_focus", "location_focus", "summary_first", "checklist_style"],
        "business_simple": ["office_focus", "summary_first", "minimal_modern"],
        "business_compact": ["summary_first", "minimal_modern"],
        "business_minimal": ["summary_first", "minimal_modern"],

        "factory_rich": ["office_focus", "broker_expert", "checklist_style", "summary_first"],
        "factory_balanced": ["office_focus", "summary_first", "checklist_style"],
        "factory_simple": ["summary_first", "checklist_style", "minimal_modern"],
        "factory_compact": ["summary_first", "minimal_modern"],
        "factory_minimal": ["summary_first", "minimal_modern"],

        "land_rich": ["land_focus"],
        "land_balanced": ["land_focus"],
        "land_simple": ["land_focus"],
        "land_compact": ["land_focus"],
        "land_minimal": ["land_focus"],

        "generic_rich": ["story_first", "summary_first", "checklist_style"],
        "generic_balanced": ["summary_first", "checklist_style", "minimal_modern"],
        "generic_simple": ["summary_first", "minimal_modern"],
        "generic_compact": ["summary_first", "minimal_modern"],
        "generic_minimal": ["summary_first", "minimal_modern"],
    }

    candidates = candidates_map.get(layout_mode) or candidates_map.get("generic_simple")
    seed_text = f"{realtor_id or ''}:{article_no or ''}:{layout_mode}"
    rnd = random.Random(seed_text)

    return rnd.choice(candidates), candidates


def hee_log_layout_recommendation(detail, images, ai_sections, current_layout_type):
    try:
        info = _hee_layout_mode_from_detail(detail, images, ai_sections)
        recommended, candidates = _hee_recommended_layout_type(
            info.get("layout_mode"),
            realtor_id=detail.get("realtor_id"),
            article_no=detail.get("article_no"),
        )

        print(
            "[HEE LAYOUT RECOMMEND] "
            f"property_class={info.get('property_class')}, "
            f"image_count={info.get('image_count')}, "
            f"broker_desc_len={info.get('broker_desc_len')}, "
            f"layout_mode={info.get('layout_mode')}, "
            f"recommended={recommended}, "
            f"current={current_layout_type}, "
            f"apply=False"
        )
    except Exception as e:
        print("[HEE LAYOUT RECOMMEND ERROR]", str(e))

"""

if 'def hee_log_layout_recommendation' not in text:
    marker = '\ndef fetch_article_images'
    if marker not in text:
        raise RuntimeError('cannot find insertion marker: def fetch_article_images')
    text = text.replace(marker, helper_code + marker, 1)
    print('[PATCH] helper functions inserted')
else:
    print('[SKIP] helper functions already exist')

needle = """    layout_type = random.choice([
        "story_first",
        "photo_first",
        "summary_first",
        "gallery_story",
        "location_focus",
        "recommendation_focus",
        "magazine_style",
        "interview_style",
        "checklist_style",
        "quiet_luxury",
        "short_review_style",
        "wide_visual",
        "photo_grid",
        "minimal_modern",
        "storytelling",
        "local_life",
        "broker_expert",
        "premium_report",
    ])
"""

replacement = needle + """
    hee_log_layout_recommendation(
        detail=detail_row,
        images=images,
        ai_sections=ai_sections,
        current_layout_type=layout_type,
    )
"""

if 'hee_log_layout_recommendation(\n        detail=detail_row' in text:
    print('[SKIP] log call already inserted')
elif needle in text:
    text = text.replace(needle, replacement, 1)
    print('[PATCH] log call inserted after random layout selection')
else:
    raise RuntimeError('layout_type random choice block not found')

TARGET.write_text(text, encoding='utf-8')
print('[DONE]', TARGET)
