# -*- coding: utf-8 -*-
'''
STEP111-15 Patch: generate_blog_drafts.py uses services.hee_policy_service

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

import_line = 'from services.hee_policy_service import log_policy_recommendation\n'
if import_line not in text:
    marker = 'from services.extra_image_service import get_extra_images_if_needed\n'
    if marker not in text:
        raise RuntimeError('import marker not found')
    text = text.replace(marker, marker + import_line, 1)
    print('[PATCH] import log_policy_recommendation added')
else:
    print('[SKIP] import already exists')

old_call = """    hee_log_layout_recommendation(
        detail=detail_row,
        images=images,
        ai_sections=ai_sections,
        current_layout_type=layout_type,
    )
"""

new_call = """    # STEP111-15 HEE Policy Service - Log Only
    # 실제 layout_type은 아직 변경하지 않는다. 운영 안전을 위해 apply=False 유지.
    log_policy_recommendation(
        detail=detail_row,
        images=images,
        ai_sections=ai_sections,
        current_layout_type=layout_type,
        apply=False,
    )
"""

if new_call in text:
    print('[SKIP] service log call already exists')
elif old_call in text:
    text = text.replace(old_call, new_call, 1)
    print('[PATCH] hee_log_layout_recommendation call replaced with service call')
else:
    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",
    ])
"""
    if needle not in text:
        raise RuntimeError('layout_type random choice block not found and old call not found')
    text = text.replace(needle, needle + '\n' + new_call, 1)
    print('[PATCH] service log call inserted after random layout selection')

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