import sys, json, logging
sys.path.insert(0, '/home/jay/projects/ThreadAuto')
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)s %(levelname)s %(message)s')

logger = logging.getLogger(__name__)

# Step 1: 토픽 선택
from content.topic_selector import select_single_topic
topic = select_single_topic(category="정보제공")
logger.info("선택된 토픽: %s", json.dumps(topic, ensure_ascii=False, indent=2))

# Step 2: 5단계 파이프라인으로 콘텐츠 생성
from content.five_stage_pipeline import FiveStagePipeline
pipeline = FiveStagePipeline()
result = pipeline.generate(topic=topic, content_type="cardnews")
logger.info("파이프라인 결과 키: %s", list(result.keys()))

# 결과 저장 (디버깅용)
result_path = '/home/jay/projects/ThreadAuto/output/task677_result.json'
with open(result_path, 'w') as f:
    json.dump(result, f, ensure_ascii=False, indent=2)
logger.info("결과 JSON 저장: %s", result_path)

# Step 3+4: 카드뉴스 렌더링 + Threads 업로드
from publisher.threads_publisher import ThreadsPublisher
publisher = ThreadsPublisher()

# V2 파이프라인 결과에서 필요한 데이터 추출
title = result.get("topic_id", topic.get("title", "보험 정보"))
items = []
if "slides" in result:
    for slide in result["slides"]:
        items.append({
            "title": slide.get("title", ""),
            "description": slide.get("text", slide.get("subtitle", ""))
        })

# caption과 hashtags
caption = result.get("caption", "")
hashtags = result.get("hashtags", [])

# 카드뉴스 발행 (렌더링 + 업로드 동시 수행)
publish_result = publisher.publish_cardnews(
    title=title,
    items=items,
    caption=caption,
    hashtags=hashtags,
    content=result,  # V2 파이프라인: slides 기반 렌더링
)

logger.info("발행 결과: %s", json.dumps(publish_result, ensure_ascii=False, default=str))

# 최종 결과 출력
print("\n" + "="*60)
print("=== 최종 결과 ===")
print(f"성공 여부: {publish_result.get('success')}")
print(f"Threads Post ID: {publish_result.get('threads_post_id')}")
print(f"에러: {publish_result.get('error')}")
print(f"이미지 경로: {publish_result.get('image_paths', [])}")
print("="*60)
