"""task-676.1: 새 주제 영상 생성 + Threads 업로드 파이프라인 실행 스크립트

파이프라인 4단계:
  Step 1: 토픽 선택 (topic_selector)
  Step 2: 콘텐츠 생성 (FiveStagePipeline)
  Step 3: 영상 렌더링 (generate_shortform_video)
  Step 4: Threads 업로드 (ThreadsPublisher)
"""

import asyncio
import json
import os
import sys
import traceback
import time

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

RESULT_PATH = "/home/jay/workspace/teams/dev1/scripts/task676_result.json"
OUTPUT_VIDEO_PATH = "/home/jay/projects/ThreadAuto/output/videos/task676_new_topic.mp4"

result = {
    "topic": None,
    "slides_count": None,
    "video_path": None,
    "file_size_mb": None,
    "threads_post_id": None,
    "success": False,
    "error": None,
}


def save_result():
    os.makedirs(os.path.dirname(RESULT_PATH), exist_ok=True)
    with open(RESULT_PATH, "w", encoding="utf-8") as f:
        json.dump(result, f, ensure_ascii=False, indent=2)
    print(f"\n[결과 저장] {RESULT_PATH}")


def print_sep(label: str):
    print("\n" + "=" * 60)
    print(f"  {label}")
    print("=" * 60)


# ---------------------------------------------------------------------------
# Step 1: 토픽 선택
# ---------------------------------------------------------------------------
print_sep("Step 1: 토픽 선택")
try:
    from content.topic_selector import select_single_topic

    topic = select_single_topic()
    result["topic"] = {
        "id": topic.get("id"),
        "category": topic.get("category"),
        "title": topic.get("title"),
    }
    print(f"  토픽 ID      : {topic.get('id')}")
    print(f"  카테고리     : {topic.get('category')}")
    print(f"  제목         : {topic.get('title')}")
    print(f"  설명         : {topic.get('description', '')[:100]}")
    print(f"  used_count   : {topic.get('used_count', 0)}")
    print("  [Step 1 완료]")
except Exception:
    result["error"] = f"Step 1 실패:\n{traceback.format_exc()}"
    print("[Step 1 실패]")
    print(traceback.format_exc())
    save_result()
    sys.exit(1)

# ---------------------------------------------------------------------------
# Step 2: 콘텐츠 생성 (FiveStagePipeline) — AI 호출로 최대 120초 소요 가능
# ---------------------------------------------------------------------------
print_sep("Step 2: 콘텐츠 생성 (FiveStagePipeline)")
print("  * 내부적으로 Claude CLI를 5단계 호출합니다. 최대 120초 소요될 수 있습니다.")
try:
    from content.five_stage_pipeline import FiveStagePipeline

    pipeline = FiveStagePipeline()
    t0 = time.time()
    content = pipeline.generate(topic=topic, content_type="cardnews")
    elapsed = time.time() - t0

    slides = content.get("slides", [])
    caption = content.get("caption", "")
    review_score = content.get("pipeline_metadata", {}).get("review_score", "N/A")

    result["slides_count"] = len(slides)
    print(f"  slides 수    : {len(slides)}")
    print(f"  caption 앞부분: {caption[:80]}...")
    print(f"  review_score : {review_score}")
    print(f"  소요 시간    : {elapsed:.1f}초")
    print("  [Step 2 완료]")
except Exception:
    result["error"] = f"Step 2 실패:\n{traceback.format_exc()}"
    print("[Step 2 실패]")
    print(traceback.format_exc())
    save_result()
    sys.exit(1)

# ---------------------------------------------------------------------------
# Step 3: 영상 렌더링
# ---------------------------------------------------------------------------
print_sep("Step 3: 영상 렌더링")
print(f"  출력 경로: {OUTPUT_VIDEO_PATH}")
try:
    from video.pipeline_orchestrator import generate_shortform_video

    os.makedirs(os.path.dirname(OUTPUT_VIDEO_PATH), exist_ok=True)

    t0 = time.time()
    video_path = asyncio.run(
        generate_shortform_video(
            slides=slides,
            output_path=OUTPUT_VIDEO_PATH,
        )
    )
    elapsed = time.time() - t0

    file_size_bytes = os.path.getsize(video_path)
    file_size_mb = file_size_bytes / (1024 * 1024)

    result["video_path"] = video_path
    result["file_size_mb"] = round(file_size_mb, 2)

    print(f"  영상 경로    : {video_path}")
    print(f"  파일 크기    : {file_size_mb:.2f} MB ({file_size_bytes:,} bytes)")
    print(f"  소요 시간    : {elapsed:.1f}초")
    print("  [Step 3 완료]")
except Exception:
    result["error"] = f"Step 3 실패:\n{traceback.format_exc()}"
    print("[Step 3 실패]")
    print(traceback.format_exc())
    save_result()
    sys.exit(1)

# ---------------------------------------------------------------------------
# Step 4: Threads 업로드
# ---------------------------------------------------------------------------
print_sep("Step 4: Threads 업로드")
try:
    from publisher.threads_publisher import ThreadsPublisher

    publisher = ThreadsPublisher()

    post_data = {
        "content": content,   # caption 포함
        "image_path": "",
        "video_path": video_path,
        "post_id": None,
    }

    publish_result = publisher.publish(post_data)

    threads_post_id = publish_result.get("threads_post_id")
    upload_success = publish_result.get("success", False)
    upload_error = publish_result.get("error")

    result["threads_post_id"] = threads_post_id

    if upload_success:
        print(f"  threads_post_id: {threads_post_id}")
        print("  [Step 4 완료]")
    else:
        raise RuntimeError(f"Threads 업로드 실패: {upload_error}")

except Exception:
    result["error"] = f"Step 4 실패:\n{traceback.format_exc()}"
    print("[Step 4 실패]")
    print(traceback.format_exc())
    # 영상은 생성됐으므로 partial success 저장 후 종료
    save_result()
    sys.exit(1)

# ---------------------------------------------------------------------------
# 최종 결과
# ---------------------------------------------------------------------------
result["success"] = True
print_sep("파이프라인 완료")
print(f"  토픽         : [{result['topic']['category']}] {result['topic']['title']}")
print(f"  slides 수    : {result['slides_count']}")
print(f"  영상 경로    : {result['video_path']}")
print(f"  영상 크기    : {result['file_size_mb']} MB")
print(f"  Threads ID   : {result['threads_post_id']}")
print(f"  성공 여부    : {result['success']}")

save_result()
