# -*- coding: utf-8 -*-
"""
STEP111-14 HEE Policy Service Test Tool

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

  draft 기준:
  python tools\test_hee_policy_service.py --draft-id 209

  article 기준:
  python tools\test_hee_policy_service.py --realtor-id 1 --article-no 2633019770
"""

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 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, args.draft_id, args.realtor_id, 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"))
        html = extract_html(draft)

        source = safe_json_loads(draft.get("source_json"))
        ai_sections = safe_json_loads(draft.get("ai_sections"))

        detail = {}
        detail.update(source.get("detail") or {})
        detail.update(article or {})

        result = resolve_publish_policy(
            detail,
            images=images,
            ai_sections=ai_sections,
            html=html,
        )

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

        analysis = result["analysis"]
        layout = result["layout"]

        print("=" * 80)
        print("[STEP111-14 HEE POLICY SERVICE TEST]")
        print("draft_id:", draft.get("id"))
        print("realtor_id:", draft.get("realtor_id"))
        print("article_no:", draft.get("article_no"))
        print("title:", draft.get("draft_title"))
        print("-" * 80)
        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("has_floorplan:", analysis.get("has_floorplan"))
        print("has_school:", analysis.get("has_school"))
        print("-" * 80)
        print("layout_mode:", layout.get("layout_mode"))
        print("selected_layout_type:", layout.get("selected_layout_type"))
        print("candidates:", ", ".join(layout.get("candidates") or []))
        print("-" * 80)
        print("publish_allowed:", result.get("publish_allowed"))
        print("block_reasons:", ", ".join(result.get("block_reasons") or []) or "(none)")
        print("warnings:")
        if result.get("warnings"):
            for w in result["warnings"]:
                print("-", w)
        else:
            print("(none)")
        print("=" * 80)

    finally:
        conn.close()


if __name__ == "__main__":
    main()
