"""매일경제 보험 기사 기반 카드뉴스 생성 + Threads/Instagram 동시 업로드 스크립트 (task-1366.1)

출처: 매일경제 https://www.mk.co.kr/news/economy/12004967
핵심: 실손의료보험 과잉 진료 유발 요인 점검, 관리급여화 추진, 소비자 보호 강화
"""

import json
import logging
import os
import sys
from datetime import datetime

logging.basicConfig(
    level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s"
)
logger = logging.getLogger(__name__)

sys.path.insert(0, "/home/jay/projects/ThreadAuto")

from publisher.cross_publisher import CrossPublisher


# ---------------------------------------------------------------------------
# 슬라이드 데이터 (CardNewsRenderer 호환 형식)
# ---------------------------------------------------------------------------

slides = [
    {
        "type": "cover",
        "hook": "실손보험 적자 연 1조원",
        "title": "과잉 진료 차단, 보험업계가 움직인다",
        "keywords": ["실손보험", "과잉진료", "관리급여화"],
    },
    {
        "type": "card_list",
        "title": "보험연구원 점검 핵심 포인트",
        "items": [
            {
                "title": "10대 비급여 진료 집중 점검",
                "description": "도수치료 등 과잉 청구 의심 비급여 항목을 선별하여 실태 조사 추진",
            },
            {
                "title": "관리급여화 추진",
                "description": "비급여 진료를 건강보험 급여로 전환, 본인부담률 조정으로 과잉 진료 억제",
            },
            {
                "title": "소비자 보호 강화",
                "description": "보험료 인상 압력 완화 및 가입자 권익 보호를 위한 제도적 장치 마련",
            },
        ],
    },
    {
        "type": "detail",
        "title": "숫자로 보는 실손보험 현황",
        "items": [
            {"label": "연간 적자 규모", "value": "1조원 이상"},
            {"label": "핵심 원인", "value": "도수치료 등 비급여 과잉 진료"},
            {"label": "대응 방안", "value": "관리급여화 단계적 추진"},
            {"label": "추가 검토", "value": "자동차보험 자기부담금 제도 개선"},
        ],
    },
    {
        "type": "body",
        "title": "관리급여화란?",
        "description": (
            "비급여 진료 항목을 건강보험 급여로 전환하면서 본인부담률을 조정하는 제도입니다. "
            "무분별한 비급여 진료를 억제하고 보험료 인상 압력을 완화하는 효과가 기대됩니다."
        ),
    },
    {
        "type": "cta",
        "title": "보험 트렌드를 한발 앞서 파악하세요",
        "cta_text": "보험 전문가와 상담하기",
        "items": [
            {"label": "출처", "value": "매일경제"},
            {"label": "채널", "value": "서울대보험쌤"},
        ],
    },
]

caption = """실손보험 적자가 연 1조원을 넘어섰습니다.

보험연구원이 도수치료 등 비급여 과잉 진료를 집중 점검하고, 관리급여화를 추진합니다.

보험설계사라면 꼭 알아야 할 업계 핵심 이슈를 정리했습니다.

출처: 매일경제"""


# ---------------------------------------------------------------------------
# 메인 실행
# ---------------------------------------------------------------------------


def main():
    # cover 슬라이드(첫 번째)에서 title 추출
    cover_slide = slides[0]
    title = cover_slide.get("title") or cover_slide.get("hook", "")

    # card_list 슬라이드(두 번째)에서 items 추출
    card_list_slide = slides[1]
    items = card_list_slide.get("items", [])

    content = {"slides": slides, "caption": caption}

    logger.info("카드뉴스 업로드 시작")
    logger.info("title: %s", title)
    logger.info("슬라이드 수: %d", len(slides))
    logger.info("items 수: %d", len(items))

    publish_result: dict = {}

    try:
        publisher = CrossPublisher()
        publish_result = publisher.publish_cardnews(
            title=title,
            items=items,
            content=content,
            caption=caption,
            auto_generate=False,
        )

        threads_result = publish_result.get("threads", {})
        instagram_result = publish_result.get("instagram")

        if threads_result.get("success"):
            logger.info(
                "Threads 업로드 성공! post_id: %s",
                threads_result.get("threads_post_id"),
            )
        else:
            logger.error("Threads 업로드 실패: %s", threads_result.get("error"))

        if instagram_result and instagram_result.get("success"):
            logger.info(
                "Instagram 업로드 성공! post_id: %s",
                instagram_result.get("instagram_post_id"),
            )
        elif instagram_result:
            logger.error("Instagram 업로드 실패: %s", instagram_result.get("error"))
        else:
            logger.info("Instagram 크로스포스팅 비활성화 (CROSS_POST_ENABLED=False)")

    except Exception as exc:
        logger.error("업로드 중 예외 발생: %s", exc)
        publish_result = {
            "threads": {"success": False, "threads_post_id": None, "error": str(exc), "image_paths": []},
            "instagram": None,
            "overall_success": False,
        }

    threads_result = publish_result.get("threads", {})
    instagram_result = publish_result.get("instagram")

    summary = {
        "success": publish_result.get("overall_success", False),
        "post_id": threads_result.get("threads_post_id"),
        "instagram_post_id": (
            instagram_result.get("instagram_post_id") if instagram_result else None
        ),
        "title": title,
        "slide_count": len(slides),
        "caption": caption,
        "image_paths": threads_result.get("image_paths", []),
        "article_url": "https://www.mk.co.kr/news/economy/12004967",
        "article_source": "매일경제",
        "error": threads_result.get("error"),
        "instagram_error": instagram_result.get("error") if instagram_result else None,
    }

    print("\n" + "=" * 60)
    print("RESULT_JSON_START")
    print(json.dumps(summary, ensure_ascii=False, indent=2))
    print("RESULT_JSON_END")
    print("=" * 60)

    # 결과 JSON 파일 저장
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    output_path = (
        f"/home/jay/projects/ThreadAuto/output/cardnews_post_result_{timestamp}.json"
    )
    os.makedirs(os.path.dirname(output_path), exist_ok=True)
    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(summary, f, ensure_ascii=False, indent=2)
    logger.info("결과 저장: %s", output_path)

    return summary


if __name__ == "__main__":
    main()
