# -*- coding: utf-8 -*-
"""STEP105-04: Tail Comment property detection v3 + duplicate reinforcement fix.

Run:
  cd /d D:\honghee\blog_api
  python tools\patch_tail_comment_detection_v3.py
"""

from pathlib import Path
from datetime import datetime

ROOT = Path(__file__).resolve().parents[1]
TARGET = ROOT / "workers" / "publish_modules" / "tail_comment.py"

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

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

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

old = """    if normalized == "default":
        if any(x in merged for x in ["다가구", "단독주택", "상가주택", "주택"]):
            normalized = "building"
        elif any(x in merged for x in ["아파트", "맨션"]):
            normalized = "apartment"
        elif any(x in merged for x in ["상가", "점포", "사무실"]):
            normalized = "store"
        elif any(x in merged for x in ["토지", "대지", "임야", "전답"]):
            normalized = "land"

    return normalized
"""

new = """    if normalized == "default":
        apartment_keywords = [
            "아파트", "맨션", "단지", "마스터힐스", "힐스테이트", "자이", "푸르지오",
            "래미안", "아이파크", "더샵", "롯데캐슬", "e편한세상", "이편한세상",
            "센트럴", "리버파크", "파크뷰", "파크", "시티", "타워", "스위첸",
            "우미린", "호반", "중흥", "한신", "한화", "꿈에그린", "데시앙",
            "리슈빌", "마을", "주공", "휴먼시아", "LH", "해밀", "가온", "새뜸",
            "도램", "범지기", "수루배", "첫마을"
        ]

        building_keywords = [
            "다가구", "단독주택", "상가주택", "건물", "원룸건물", "꼬마빌딩"
        ]

        store_keywords = [
            "상가", "점포", "사무실", "근린생활", "근생", "상업시설"
        ]

        land_keywords = [
            "토지", "대지", "임야", "전답", "농지", "공장용지"
        ]

        villa_keywords = [
            "빌라", "연립", "다세대", "주택형빌라"
        ]

        officetel_keywords = [
            "오피스텔", "오피스", "생활형숙박"
        ]

        if any(x in merged for x in apartment_keywords):
            normalized = "apartment"
        elif any(x in merged for x in officetel_keywords):
            normalized = "officetel"
        elif any(x in merged for x in villa_keywords):
            normalized = "villa"
        elif any(x in merged for x in store_keywords):
            normalized = "store"
        elif any(x in merged for x in land_keywords):
            normalized = "land"
        elif any(x in merged for x in building_keywords):
            normalized = "building"

    return normalized
"""

if old not in text:
    print("[WARN] property detection block not found; maybe already patched")
else:
    text = text.replace(old, new, 1)
    print("[PATCH] property detection keyword boost applied")

old2 = """def _ensure_min_tail_length(comment, context=None, min_len=300):
    comment = str(comment or "").strip()

    extras = [
        "방문 전에는 현재 매물 가능 여부와 조건 변동 여부를 먼저 확인해 주세요. 같은 조건처럼 보여도 실제 현장에서는 채광, 소음, 주차, 동선에서 차이가 날 수 있습니다.",
        "사진과 기본 정보만으로는 판단하기 어려운 부분이 있으니 가능하다면 직접 방문해서 구조와 주변 분위기를 함께 보시는 것을 추천드립니다.",
        "가격과 입주 가능일, 관리비, 수리 여부는 상담 시점에 다시 확인하는 것이 가장 정확합니다. 문의 주시면 현재 확인 가능한 기준으로 안내드리겠습니다.",
        "생활권을 함께 비교하시면 선택이 더 쉬워집니다. 출퇴근 동선, 장보기, 병원, 학교, 대중교통 접근성처럼 매일 이용하는 부분도 함께 체크해보시면 좋습니다.",
    ]

    guard = 0
    while len(comment) < min_len and guard < 4:
        extra = random.choice(extras)
        if extra not in comment:
            comment = (comment + "\\n\\n" + extra).strip()
        guard += 1

    return comment
"""

new2 = """def _sentence_key(text):
    text = str(text or "").strip()
    text = text.replace("\\n", " ")
    text = " ".join(text.split())
    return text[:42]


def _ensure_min_tail_length(comment, context=None, min_len=300):
    comment = str(comment or "").strip()

    extras = [
        "방문 전에는 현재 매물 가능 여부와 조건 변동 여부를 먼저 확인해 주세요. 같은 조건처럼 보여도 실제 현장에서는 채광, 소음, 주차, 동선에서 차이가 날 수 있습니다.",
        "사진과 기본 정보만으로는 판단하기 어려운 부분이 있으니 가능하다면 직접 방문해서 구조와 주변 분위기를 함께 보시는 것을 추천드립니다.",
        "가격과 입주 가능일, 관리비, 수리 여부는 상담 시점에 다시 확인하는 것이 가장 정확합니다. 문의 주시면 현재 확인 가능한 기준으로 안내드리겠습니다.",
        "생활권을 함께 비교하시면 선택이 더 쉬워집니다. 출퇴근 동선, 장보기, 병원, 학교, 대중교통 접근성처럼 매일 이용하는 부분도 함께 체크해보시면 좋습니다.",
        "실제 방문하실 때는 낮 시간대의 채광과 저녁 시간대의 주변 분위기를 함께 비교해보시면 더 현실적인 판단에 도움이 됩니다.",
        "계약을 검토하실 때는 등기, 대출 가능 여부, 잔금 일정처럼 실제 진행 과정에서 필요한 부분도 함께 확인하는 것이 좋습니다.",
        "조건이 마음에 드신다면 비슷한 매물과 가격, 위치, 내부 상태를 함께 비교해보시는 것도 좋은 방법입니다.",
        "문의 주시면 현재 확인 가능한 매물 상태와 방문 가능 시간을 기준으로 차분히 안내드리겠습니다.",
    ]

    existing_keys = set()
    for block in comment.split("\\n\\n"):
        key = _sentence_key(block)
        if key:
            existing_keys.add(key)

    random.shuffle(extras)

    for extra in extras:
        if len(comment) >= min_len:
            break

        key = _sentence_key(extra)
        if not key or key in existing_keys:
            continue

        if extra[:28] in comment or extra[-28:] in comment:
            continue

        comment = (comment + "\\n\\n" + extra).strip()
        existing_keys.add(key)

    if len(comment) < min_len:
        fallback = "매물 조건은 시점에 따라 달라질 수 있으니 상담 시 최신 기준으로 다시 확인해드리겠습니다."
        if fallback not in comment:
            comment = (comment + "\\n\\n" + fallback).strip()

    return comment
"""

if old2 not in text:
    print("[WARN] min length block not found; maybe already patched")
else:
    text = text.replace(old2, new2, 1)
    print("[PATCH] duplicate-safe length reinforcement applied")

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