# -*- coding: utf-8 -*-
# STEP110-03 Draft Engine 운영품질 보강 패치
# 사용: cd /d D:\honghee\blog_api && python tools\patch_draft_engine_use_operating_cli.py

from pathlib import Path
from datetime import datetime

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

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

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

if 'import subprocess' not in text:
    text = text.replace('import json\n', 'import json\nimport subprocess\n', 1)
    print('[PATCH] subprocess import inserted')

marker = 'DRAFT_JOB = BASE_DIR / "jobs" / "generate_blog_drafts.py"'
if marker not in text:
    text = text.replace(
        'from db import get_conn\n',
        'from db import get_conn\n\nDRAFT_JOB = BASE_DIR / "jobs" / "generate_blog_drafts.py"\nPYTHON = sys.executable\n',
        1,
    )
    print('[PATCH] DRAFT_JOB/PYTHON inserted')

start = text.find('def create_draft_for_article_row(conn, row):')
if start < 0:
    raise RuntimeError('create_draft_for_article_row not found')

end = text.find('\ndef create_one_latest_draft', start)
if end < 0:
    raise RuntimeError('create_one_latest_draft boundary not found')

new_func_lines = [
    'def create_draft_for_article_row(conn, row):',
    '    # 운영 품질 보강: process_article 직접 호출 대신 운영 CLI를 사용한다.',
    '    article_no = str(row.get("article_no") or "").strip()',
    '    realtor_id = int(row.get("realtor_id") or 0)',
    '',
    '    if not article_no or not realtor_id:',
    '        return {',
    '            "ok": False,',
    '            "article_no": article_no,',
    '            "reason": "article_no or realtor_id empty",',
    '            "result": "invalid_target",',
    '        }',
    '',
    '    if not DRAFT_JOB.exists():',
    '        return {',
    '            "ok": False,',
    '            "article_no": article_no,',
    '            "reason": f"draft job not found: {DRAFT_JOB}",',
    '            "result": "draft_job_missing",',
    '        }',
    '',
    '    cmd = [',
    '        PYTHON,',
    '        str(DRAFT_JOB),',
    '        "--realtor-id",',
    '        str(realtor_id),',
    '        "--article-no",',
    '        article_no,',
    '        "--limit",',
    '        "1",',
    '        "--no-db-lock",',
    '    ]',
    '',
    '    log("[STEP110 OPERATING DRAFT CLI]", " ".join(cmd))',
    '',
    '    result = subprocess.run(',
    '        cmd,',
    '        cwd=str(BASE_DIR),',
    '        text=True,',
    '        encoding="utf-8",',
    '        errors="replace",',
    '        timeout=1800,',
    '    )',
    '',
    '    if result.returncode != 0:',
    '        return {',
    '            "ok": False,',
    '            "article_no": article_no,',
    '            "reason": f"generate_blog_drafts.py returncode={result.returncode}",',
    '            "result": "operating_cli_failed",',
    '        }',
    '',
    '    return {',
    '        "ok": True,',
    '        "article_no": article_no,',
    '        "result": "created_by_operating_cli",',
    '    }',
    '',
]

new_func = '\n'.join(new_func_lines) + '\n'
text = text[:start] + new_func + text[end:]
TARGET.write_text(text, encoding='utf-8')

print('[DONE] patched core/draft_engine.py to use operating CLI')
print('[TARGET]', TARGET)
