# -*- coding: utf-8 -*-
"""
STEP111-16 HEE Block Order Preview Tool

목적:
- hee_policy_service.py가 판단한 property_class / richness / layout_mode / selected_layout_type 기준으로
  실제 본문 블록 순서를 미리 확인한다.
- 아직 운영 HTML 생성은 변경하지 않는다.
- 정보가 적어도 발행하되, compact/simple 블록으로 단순화하는 정책을 검증한다.

사용:
  cd /d D:\honghee\blog_api

  행복공인 테스트:
  python tools\hee_block_order_preview.py --draft-id 209

  특정 매물:
  python tools\hee_block_order_preview.py --realtor-id 5 --article-no 2633005438

  JSON:
  python tools\hee_block_order_preview.py --draft-id 209 --json
"""

import argparse
import json
import sys
from pathlib import Path

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

from db import get_conn
from services.hee_policy_service import resolve_publish_policy


def safe_json_loads(value):
    if not value:
        return {}
    if isinstance(value, dict):
        return value
    try:
        return json.loads(value)
    except Exception:
        return {}


def fetch_draft(conn, draft_id=None, realtor_id=None, article_no=None):
    with conn.cursor() as cur:
        if draft_id:
            cur.execute("SELECT * FROM blog_article_drafts WHERE id=%s LIMIT 1", (int(draft_id),))
            return cur.fetchone()

        cur.execute(
            """
            SELECT *
            FROM blog_article_drafts
            WHERE realtor_id=%s AND article_no=%s
            ORDER BY id DESC
            LIMIT 1
            """,
            (int(realtor_id), str(article_no)),
        )
        return cur.fetchone()


def fetch_article(conn, realtor_id, article_no):
    with conn.cursor() as cur:
        cur.execute(
            """
            SELECT *
            FROM blog_realtor_articles
            WHERE realtor_id=%s AND article_no=%s
            LIMIT 1
            """,
            (int(realtor_id), str(article_no)),
        )
        return cur.fetchone()


def fetch_images(conn, article_no):
    with conn.cursor() as cur:
        cur.execute(
            """
            SELECT *
            FROM blog_realestate_article_images
            WHERE article_no=%s
            ORDER BY sort_order ASC, id ASC
            """,
            (str(article_no),),
        )
        return cur.fetchall()


def extract_html(draft):
    return str(draft.get("clipboard_html") or draft.get("draft_html") or "")


def build_detail(article, draft):
    source = safe_json_loads(draft.get("source_json"))
    detail = {}
    detail.update(source.get("detail") or {})
    detail.update(article or {})
    return detail


def block_order_for(policy_result):
    analysis = policy_result["analysis"]
    layout = policy_result["layout"]

    property_class = analysis.get("property_class")
    richness = analysis.get("richness")
    layout_type = layout.get("selected_layout_type")

    # 공통 하단 고정
    bottom = [
        "realtor_profile",
        "legal_notice",
        "closing",
        "seo_footer",
    ]

    # 정보 부족: 반드시 간결하게. 발행은 하되 무리한 스토리 금지.
    if richness in ["minimal", "compact"]:
        if property_class == "land":
            core = [
                "intro",
                "summary",
                "feature_comment",
                "checklist",
                "gallery_light",
                "realtor_banner",
            ]
        elif property_class in ["store", "office", "factory_warehouse"]:
            core = [
                "intro",
                "summary",
                "business_checklist",
                "feature_comment",
                "gallery_light",
                "realtor_banner",
            ]
        else:
            core = [
                "intro",
                "summary",
                "feature_comment",
                "gallery_light",
                "realtor_banner",
                "checklist",
            ]

        return {
            "mode": "compact_publish_always",
            "layout_type": layout_type,
            "blocks": core + bottom,
            "notes": [
                "정보 부족은 발행 차단이 아니라 compact 구성을 사용합니다.",
                "사진/설명 부족 시 생활권·투자성 등 과장 블록은 최소화합니다.",
            ],
        }

    # 토지
    if property_class == "land":
        core = [
            "intro",
            "feature_comment",
            "summary",
            "checklist",
            "location",
            "point",
            "price_text",
            "gallery",
            "realtor_banner",
        ]
        return {
            "mode": "land_policy",
            "layout_type": "land_focus",
            "blocks": core + bottom,
            "notes": [
                "토지 유형은 land_focus 고정입니다.",
                "전/답/대지는 정확한 원천 유형일 때만 토지로 분기합니다.",
            ],
        }

    # 상가/사무실
    if property_class in ["store", "office"]:
        if richness == "rich":
            core = [
                "summary",
                "location",
                "business_checklist",
                "gallery",
                "feature_comment",
                "point",
                "prices",
                "realtor_banner",
            ]
        else:
            core = [
                "summary",
                "intro",
                "location",
                "business_checklist",
                "gallery",
                "feature_comment",
                "realtor_banner",
            ]

        return {
            "mode": "business_policy",
            "layout_type": layout_type,
            "blocks": core + bottom,
            "notes": [
                "상가/사무실은 생활권보다 접근성·용도·상권 조건 중심으로 구성합니다.",
            ],
        }

    # 공장/창고
    if property_class == "factory_warehouse":
        core = [
            "summary",
            "intro",
            "factory_checklist",
            "location",
            "gallery",
            "feature_comment",
            "realtor_banner",
        ]
        return {
            "mode": "factory_policy",
            "layout_type": layout_type,
            "blocks": core + bottom,
            "notes": [
                "공장/창고는 면적·진입·용도·주차/하역 등 확인 포인트 중심으로 구성합니다.",
            ],
        }

    # 주거형 풍부/보통
    if property_class in ["apartment", "officetel", "villa_house", "presale_right"]:
        if layout_type in ["photo_grid", "gallery_story"]:
            core = [
                "summary",
                "gallery",
                "floorplan",
                "intro",
                "feature_comment",
                "space",
                "point",
                "location",
                "facilities",
                "location_images",
                "realtor_banner",
                "checklist",
                "management_tax",
                "prices",
            ]
        elif layout_type in ["location_focus", "local_life", "family_recommend"]:
            core = [
                "intro",
                "location",
                "facilities",
                "location_images",
                "summary",
                "feature_comment",
                "space",
                "floorplan",
                "gallery",
                "point",
                "realtor_banner",
                "checklist",
                "management_tax",
                "prices",
            ]
        elif layout_type in ["storytelling", "story_first"]:
            core = [
                "intro",
                "feature_comment",
                "summary",
                "space",
                "floorplan",
                "gallery",
                "point",
                "location",
                "facilities",
                "location_images",
                "realtor_banner",
                "checklist",
                "management_tax",
                "prices",
            ]
        else:
            core = [
                "summary",
                "intro",
                "feature_comment",
                "checklist",
                "space",
                "floorplan",
                "gallery",
                "point",
                "location",
                "realtor_banner",
                "management_tax",
                "prices",
            ]

        return {
            "mode": "living_policy",
            "layout_type": layout_type,
            "blocks": core + bottom,
            "notes": [
                "주거형은 정보량에 따라 실거주·사진·기본정보 중심으로 순서를 조절합니다.",
                "학군/평면도/입지 이미지는 원천 데이터가 있을 때만 적극 사용합니다.",
            ],
        }

    # fallback
    return {
        "mode": "generic_policy",
        "layout_type": layout_type,
        "blocks": [
            "intro",
            "summary",
            "feature_comment",
            "gallery_light",
            "realtor_banner",
        ] + bottom,
        "notes": [
            "매물유형이 명확하지 않아 기본형으로 구성합니다.",
        ],
    }


def build_preview(draft, article, images):
    detail = build_detail(article, draft)
    html = extract_html(draft)
    ai_sections = safe_json_loads(draft.get("ai_sections"))

    policy_result = resolve_publish_policy(
        detail,
        images=images,
        ai_sections=ai_sections,
        html=html,
    )
    order = block_order_for(policy_result)

    return {
        "draft": {
            "id": draft.get("id"),
            "realtor_id": draft.get("realtor_id"),
            "article_no": draft.get("article_no"),
            "title": draft.get("draft_title"),
        },
        "policy": policy_result,
        "block_order_preview": order,
    }


def print_report(result):
    draft = result["draft"]
    policy = result["policy"]
    analysis = policy["analysis"]
    layout = policy["layout"]
    preview = result["block_order_preview"]

    print("=" * 80)
    print("[STEP111-16 HEE BLOCK ORDER PREVIEW]")
    print("draft_id:", draft.get("id"))
    print("realtor_id:", draft.get("realtor_id"))
    print("article_no:", draft.get("article_no"))
    print("title:", draft.get("title"))
    print("-" * 80)
    print("[POLICY]")
    print("property_class:", analysis.get("property_class"))
    print("property_name:", analysis.get("property_name"))
    print("richness:", analysis.get("richness"))
    print("image_count:", analysis.get("image_count"))
    print("broker_description_length:", analysis.get("broker_description_length"))
    print("layout_mode:", layout.get("layout_mode"))
    print("selected_layout_type:", layout.get("selected_layout_type"))
    print("publish_allowed:", policy.get("publish_allowed"))
    print("-" * 80)
    print("[BLOCK ORDER PREVIEW]")
    print("mode:", preview.get("mode"))
    print("layout_type:", preview.get("layout_type"))
    for idx, block in enumerate(preview.get("blocks") or [], start=1):
        print(f"{idx:02d}. {block}")
    print("-" * 80)
    print("[NOTES]")
    for note in preview.get("notes") or []:
        print("-", note)
    print("=" * 80)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--draft-id", type=int, default=None)
    parser.add_argument("--realtor-id", type=int, default=None)
    parser.add_argument("--article-no", default="")
    parser.add_argument("--json", action="store_true")
    args = parser.parse_args()

    if not args.draft_id and not (args.realtor_id and args.article_no):
        raise RuntimeError("--draft-id 또는 --realtor-id + --article-no 필요")

    conn = get_conn()

    try:
        draft = fetch_draft(conn, draft_id=args.draft_id, realtor_id=args.realtor_id, article_no=args.article_no)
        if not draft:
            raise RuntimeError("draft not found")

        article = fetch_article(conn, draft.get("realtor_id"), draft.get("article_no")) or {}
        images = fetch_images(conn, draft.get("article_no"))

        result = build_preview(draft, article, images)

        if args.json:
            print(json.dumps(result, ensure_ascii=False, indent=2, default=str))
        else:
            print_report(result)

    finally:
        conn.close()


if __name__ == "__main__":
    main()
