"""
task691_cardnews.py
-------------------
ThreadAuto 프로젝트 카드뉴스 생성 스크립트 (토픽: eg-202)
토픽: AI 도구가 보험 영업을 어떻게 바꾸는가
담당: 토르 (개발2팀 백엔드)
"""

from __future__ import annotations

import asyncio
import sys

# ThreadAuto 프로젝트 경로 주입
sys.path.insert(0, "/home/jay/projects/ThreadAuto")

# ---------------------------------------------------------------------------
# Step 2: 카드뉴스 콘텐츠 정의
# ---------------------------------------------------------------------------

# 카드뉴스 메인 타이틀 (커버)
title = "AI 도구가 보험 영업을 바꾼다"

# 커버 hook 문구 (검증 30자 이상 필요: 32자)
hook_text = "챗GPT와 AI 자동화 도구로 달라지는 보험 설계사의 하루"

# 본문 카드 리스트 (각 description: 30~80자, 금칙어 없음)
items = [
    {
        "title": "상담 준비, AI가 대신한다",
        "description": "고객 정보를 입력하면 맞춤 보장 분석과 대화 스크립트를 자동으로 생성합니다.",
    },
    {
        "title": "SNS 마케팅도 자동화 시대",
        "description": "AI가 타깃 고객층에 맞는 콘텐츠를 초안부터 예약 발행까지 처리해 줍니다.",
    },
    {
        "title": "행정 업무 시간을 영업에 투자",
        "description": "계약서 정리·청약 안내 등 반복 행정을 AI로 처리하고 고객 면담 시간을 늘립니다.",
    },
    {
        "title": "신규 GA 이직 설계사에게 유리",
        "description": "AI 도구 활용 역량이 높을수록 이직 초기 정착 속도와 실적 회복이 빠릅니다.",
    },
]

# 마지막 슬라이드 CTA 문구 (검증 30자 이상 필요: 34자)
cta_text = "AI 활용 영업의 새 기준, 지금 바로 상담을 신청해 보세요!"

# ---------------------------------------------------------------------------
# Step 3: 콘텐츠 검증
# ---------------------------------------------------------------------------
print("=" * 60)
print("[Step 3] 콘텐츠 검증")
print("=" * 60)

from content.validate_rules import validate_cardnews_content

# 각 슬라이드 body를 description 키로 구성 (검증 시 description 우선 추출)
content = {
    "slides": [
        {"title": title, "body": hook_text},  # 커버 슬라이드 (body=hook_text, 32자)
    ]
}
# 본문 카드 슬라이드 추가
for item in items:
    content["slides"].append(
        {
            "title": item["title"],
            "description": item["description"],
        }
    )
# CTA 슬라이드
content["slides"].append({"title": "AI 활용 시작하기", "description": cta_text})

result = validate_cardnews_content(content)
print(f"  passed  : {result.passed}")
print(f"  errors  : {result.errors}")
print(f"  warnings: {result.warnings}")

if not result.passed:
    print("\n[WARN] 검증 실패 — 에러 내용을 확인하세요.")
    for e in result.errors:
        print(f"  ERROR: {e}")
else:
    print("  => 검증 통과!")

# ---------------------------------------------------------------------------
# Step 4: 이미지 렌더링
# ---------------------------------------------------------------------------
print("\n" + "=" * 60)
print("[Step 4] 이미지 렌더링")
print("=" * 60)

from renderer.cardnews import CardNewsRenderer
from renderer.themes import get_random_theme

renderer = CardNewsRenderer()
theme = get_random_theme()
print(f"  선택된 테마: {theme.name}")

slide_paths = renderer.render_all(
    title=title,
    hook_text=hook_text,
    items=items,
    cta_text=cta_text,
    theme=theme,
)

print(f"  생성된 슬라이드 수: {len(slide_paths)}장")
for i, p in enumerate(slide_paths):
    print(f"  [{i}] {p}")

# ---------------------------------------------------------------------------
# Step 5: 이미지 서버 확인 + 공개 URL 생성
# ---------------------------------------------------------------------------
print("\n" + "=" * 60)
print("[Step 5] 이미지 서버 확인 + 공개 URL 생성")
print("=" * 60)

from publisher.image_server import get_default_server

server = get_default_server()
server_ok = server.ensure_server()
print(f"  서버 상태: {'정상' if server_ok else '비정상'}")

cover_path = str(slide_paths[0])
public_url = server.get_public_url(cover_path)
print(f"  공개 URL: {public_url}")

is_valid = server.verify_url(public_url)
print(f"  URL 접근 가능: {is_valid}")

# ---------------------------------------------------------------------------
# Step 6: Threads 업로드
# ---------------------------------------------------------------------------
print("\n" + "=" * 60)
print("[Step 6] Threads 업로드")
print("=" * 60)

from api.client import ThreadsClient
from auth.token_store import get_valid_token

token = get_valid_token()
if not token:
    print("  [ERROR] 유효한 토큰이 없습니다. 인증이 필요합니다.")
    sys.exit(1)

print(f"  토큰 획득 완료 (길이: {len(token)}자)")

caption = (
    "AI가 보험 영업의 판도를 바꾸고 있습니다.\n\n"
    "챗GPT와 자동화 도구로 상담 준비부터 SNS 마케팅까지, "
    "설계사의 하루가 달라집니다.\n\n"
    "GA 이직을 고민 중이라면 AI 활용 역량이 조기 정착의 열쇠입니다.\n\n"
    "#보험설계사 #AI마케팅 #보험영업 #자동화 #GA이직"
)

print(f"  캡션 미리보기:\n{caption}\n")


async def upload():
    client = ThreadsClient(access_token=token)
    post_id = await client.post_image(public_url, caption)
    return post_id


try:
    post_id = asyncio.run(upload())
    print(f"  [SUCCESS] Threads Post ID: {post_id}")
except Exception as exc:
    print(f"  [ERROR] 업로드 실패: {exc}")
    import traceback

    traceback.print_exc()
    post_id = None

# ---------------------------------------------------------------------------
# 최종 결과 보고
# ---------------------------------------------------------------------------
print("\n" + "=" * 60)
print("[최종 결과 보고]")
print("=" * 60)
print(f"  토픽 ID   : eg-202")
print(f"  타이틀    : {title}")
print(f"  Hook 문구 : {hook_text}")
print("  본문 슬라이드:")
for i, item in enumerate(items, 1):
    print(f"    [{i}] {item['title']}")
    print(f"         {item['description']}")
print(f"  CTA       : {cta_text}")
print()
print(f"  검증 결과 : {'PASSED' if result.passed else 'FAILED'}")
print(f"  테마      : {theme.name}")
print(f"  슬라이드 파일 목록:")
for p in slide_paths:
    print(f"    {p}")
print(f"  공개 URL  : {public_url}")
print(f"  URL 유효  : {is_valid}")
print(f"  Post ID   : {post_id if post_id else 'N/A (업로드 실패)'}")
