# -*- coding: utf-8 -*-
"""
긴급 패치: services/blog_layout_blocks.py is_land_property() 오판 수정

원인:
- LAND_REAL_ESTATE_TYPES에 '전'이 포함되어 있음
- 기존 코드가 `if word in text` 부분검색을 수행
- '전세', '대전' 안의 '전' 때문에 아파트가 토지로 오판됨

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

from pathlib import Path
from datetime import datetime

ROOT = Path(__file__).resolve().parents[1]
TARGET = ROOT / 'services' / 'blog_layout_blocks.py'

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

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

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

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

end = text.find('\n\ndef land_type_label', start)
if end < 0:
    raise RuntimeError('def land_type_label not found after is_land_property')

new_func = """def is_land_property(detail):
    \"\"\"
    토지 매물 여부 판별.

    중요:
    - 부분 문자열 검색으로 '전'을 찾으면 안 된다.
      예: 전세, 대전 안의 '전' 때문에 아파트가 토지로 오판된다.
    - raw_json/DB의 명확한 건축물 유형이 있으면 무조건 False.
    \"\"\"
    detail = detail or {}

    values = [
        detail.get('real_estate_type'),
        detail.get('real_estate_type_name'),
        raw_json_get(detail, ['articleDetail', 'realestateTypeName']),
        raw_json_get(detail, ['articleAddition', 'articleRealEstateTypeName']),
        raw_json_get(detail, ['articleAddition', 'realEstateTypeName']),
        raw_json_get(detail, ['articleDetail', 'buildingTypeName']),
    ]

    codes = [
        raw_json_get(detail, ['articleDetail', 'tradeBuildingTypeCode']),
        raw_json_get(detail, ['articleDetail', 'articleTypeCode']),
        raw_json_get(detail, ['articleDetail', 'realestateTypeCode']),
        raw_json_get(detail, ['articleAddition', 'articleRealEstateTypeCode']),
        raw_json_get(detail, ['articleAddition', 'realEstateTypeCode']),
    ]

    exact_building_types = {
        '아파트', '오피스텔', '빌라', '연립', '다세대', '주택',
        '상가', '상가점포', '사무실', '공장', '창고', '분양권', '입주권',
    }
    building_codes = {
        'APT', 'A01', 'OPST', 'OP', 'VL', 'DDDGG', 'JWJT',
        'SG', 'SMS', 'GJCG', 'GM', 'CW',
    }

    for value in values:
        v = str(value or '').strip()
        if v in exact_building_types:
            return False

    for code in codes:
        c = str(code or '').strip().upper()
        if c in building_codes:
            return False

    exact_land_types = {
        '대', '전', '답', '임야', '잡종지', '공장용지', '창고용지',
        '토지', '대지', '도로', '구거', '토지/임야',
    }
    land_codes = {'TJ', 'LAND', 'TOJI', 'E03'}

    for value in values:
        v = str(value or '').strip()
        if v in exact_land_types:
            return True

    for code in codes:
        c = str(code or '').strip().upper()
        if c in land_codes:
            return True

    # 긴 단어만 보조 검색 허용. 한 글자 지목(대/전/답)은 절대 부분검색 금지.
    text = ' '.join([
        str(detail.get('real_estate_type') or ''),
        str(detail.get('real_estate_type_name') or ''),
        str(raw_json_get(detail, ['articleDetail', 'realestateTypeName']) or ''),
        str(raw_json_get(detail, ['articleAddition', 'articleRealEstateTypeName']) or ''),
    ])

    for word in ['토지', '대지', '임야', '잡종지', '공장용지', '창고용지', '계획관리지역', '자연녹지', '생산녹지']:
        if word in text:
            return True

    return False
"""

text = text[:start] + new_func + text[end:]
TARGET.write_text(text, encoding='utf-8')
print('[PATCH] is_land_property fixed')
print('[DONE]', TARGET)