# -*- coding: utf-8 -*-
"""
draft_id=202 초안에 중개사 지도 블록을 강제 삽입한다.
사용:
  cd /d D:\honghee\blog_api
  python tools\insert_realtor_map_into_draft.py --draft-id 202 --realtor-id 7
"""

import argparse
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from db import get_conn


def clean(v):
    return str(v or "").strip()


def insert_before_consult_section(html, map_html):
    html = clean(html)

    if not html:
        return html, "empty"

    if "realestate-realtor-map-image" in html:
        return html, "already"

    anchor = "상담 및 중개사 안내"
    pos = html.find(anchor)

    if pos >= 0:
        h2_pos = html.rfind("<h2", 0, pos)
        insert_pos = h2_pos if h2_pos >= 0 else pos
        return html[:insert_pos] + "\n" + map_html + "\n" + html[insert_pos:], "before_consult"

    legal_anchor = "realestate-legal-disclosure-table"
    pos = html.find(legal_anchor)
    if pos >= 0:
        return html[:pos] + "\n" + map_html + "\n" + html[pos:], "before_legal"

    close_pos = html.rfind("</div>")
    if close_pos >= 0:
        return html[:close_pos] + "\n" + map_html + "\n" + html[close_pos:], "before_last_div"

    return html + "\n" + map_html, "append"


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--draft-id", type=int, required=True)
    parser.add_argument("--realtor-id", type=int, required=True)
    args = parser.parse_args()

    conn = get_conn()

    try:
        with conn.cursor() as cur:
            cur.execute("""
                SELECT id, office_name, map_image_url
                FROM blog_realtors
                WHERE id=%s
                LIMIT 1
            """, (args.realtor_id,))
            realtor = cur.fetchone()

            if not realtor:
                raise RuntimeError(f"realtor not found: {args.realtor_id}")

            map_url = clean(realtor.get("map_image_url"))
            office_name = clean(realtor.get("office_name"))

            if not map_url:
                raise RuntimeError("map_image_url empty")

            title = f"{office_name} 위치 안내" if office_name else "중개사무소 위치 안내"

            map_html = f"""
<div class="realestate-realtor-map-image" style="margin:42px 0 28px; text-align:center; clear:both;">
  <div style="font-size:22px; font-weight:900; color:#111827; margin-bottom:16px; line-height:1.45; text-align:left;">
    {title}
  </div>
  <img src="{map_url}" alt="{title}" style="width:100%; max-width:900px; height:auto; display:block; margin:0 auto; border-radius:18px; border:1px solid #e5e7eb; box-shadow:0 14px 34px rgba(15,23,42,.12);">
  <div style="margin-top:12px; font-size:14px; line-height:1.7; color:#64748b; text-align:left;">
    방문 상담 전 매물 가능 여부와 상담 가능 시간을 먼저 확인해 주세요.
  </div>
</div>
""".strip()

            cur.execute("""
                SELECT id, draft_html, clipboard_html
                FROM blog_article_drafts
                WHERE id=%s
                LIMIT 1
            """, (args.draft_id,))
            draft = cur.fetchone()

            if not draft:
                raise RuntimeError(f"draft not found: {args.draft_id}")

            new_draft_html, mode1 = insert_before_consult_section(draft.get("draft_html"), map_html)
            new_clipboard_html, mode2 = insert_before_consult_section(draft.get("clipboard_html"), map_html)

            cur.execute("""
                UPDATE blog_article_drafts
                SET draft_html=%s,
                    clipboard_html=%s,
                    updated_at=NOW()
                WHERE id=%s
            """, (new_draft_html, new_clipboard_html, args.draft_id))

        conn.commit()

        print("[DONE]")
        print("draft_id:", args.draft_id)
        print("realtor_id:", args.realtor_id)
        print("map_url:", map_url)
        print("draft_html_mode:", mode1)
        print("clipboard_html_mode:", mode2)

    finally:
        conn.close()


if __name__ == "__main__":
    main()
