# -*- coding: utf-8 -*-
'''
운영 초안 생성 복구 패치 1차
- 중개사 매물설명을 AI/템플릿 문장으로 재조립하지 않는다.
- 네이버 중개사 원문 설명을 최대 1000자까지 보존한다.
- 줄바꿈/불필요 기호/전화번호 정도만 정리한다.

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

start = text.find("def build_broker_description_comment(detail):")
if start < 0:
    raise RuntimeError("build_broker_description_comment not found")

end = text.find("\ndef ", start + 1)
if end < 0:
    raise RuntimeError("next function after build_broker_description_comment not found")

new_func = '''def build_broker_description_comment(detail):
    """
    운영 복구 정책:
    - 네이버 부동산 중개사가 직접 작성한 매물설명을 최우선 사용한다.
    - AI/템플릿 문장으로 대체하지 않는다.
    - 최대 1000자까지 보존한다.
    - 줄바꿈/기호/전화번호 정도만 정리한다.
    """
    raw = extract_broker_description(detail)

    if not raw:
        return {
            "title": "",
            "content": "",
        }

    text = str(raw or "")
    text = text.replace("\\r\\n", "\\n").replace("\\r", "\\n")

    # 장식 기호 정리
    text = re.sub(r"[★☆■□◆◇▶▷●○◎※]+", " ", text)
    text = re.sub(r"[-=]{3,}", "\\n", text)
    text = re.sub(r"\\*+", " ", text)

    # 연락처는 법정 표시/중개사 정보에 별도 노출되므로 설명 본문에서는 제거
    text = re.sub(r"\\b0\\d{1,2}-\\d{3,4}-\\d{4}\\b", "", text)
    text = re.sub(r"\\b010-\\d{3,4}-\\d{4}\\b", "", text)
    text = re.sub(r"\\b010\\d{7,8}\\b", "", text)

    lines = []
    for line in text.split("\\n"):
        line = clean_text(line)
        line = line.strip("-·ㆍ*• ")

        if not line:
            continue

        # 너무 짧은 상호/전화 안내성 줄 제거
        if re.search(r"부동산|공인중개사|중개사무소", line) and len(line) <= 14:
            continue

        # 동일 줄 반복 제거
        if line not in lines:
            lines.append(line)

    if not lines:
        return {
            "title": "",
            "content": "",
        }

    paragraphs = []
    current = ""

    for line in lines:
        if len(current) + len(line) + 1 <= 180:
            current = (current + " " + line).strip()
        else:
            if current:
                paragraphs.append(current)
            current = line

    if current:
        paragraphs.append(current)

    content_parts = []
    total = 0

    for p in paragraphs:
        if total >= 1000:
            break

        remain = 1000 - total
        part = p[:remain].strip()

        if part:
            content_parts.append(part)
            total += len(part)

    content = "\\n\\n".join(content_parts).strip()

    if not content:
        return {
            "title": "",
            "content": "",
        }

    print("[BROKER DESCRIPTION RAW USED]", f"len={len(content)}")

    return {
        "title": "중개사 매물설명",
        "content": content,
    }

'''

text = text[:start] + new_func + text[end:]
TARGET.write_text(text, encoding="utf-8")

print("[DONE] patched broker description policy")
print("[TARGET]", TARGET)
