"""
Threads 텍스트 포스트 업로드 스크립트
작성자: 엔키 (백엔드 팀원)

post1-anger-curiosity.txt, post2-fear-empathy.txt 두 파일을 순차적으로
Threads에 업로드하고 결과를 JSON으로 출력합니다.
"""

import json
import sys
import time
from pathlib import Path

# ThreadAuto 경로 추가
sys.path.insert(0, "/home/jay/projects/ThreadAuto")

from publisher.threads_publisher import ThreadsPublisher

# ------------------------------------------------------------
# 설정
# ------------------------------------------------------------

POST_FILES = [
    "/home/jay/workspace/teams/dev5-team/output/threads-posts/post1-anger-curiosity.txt",
    "/home/jay/workspace/teams/dev5-team/output/threads-posts/post2-fear-empathy.txt",
]

DELAY_BETWEEN_POSTS = 30  # 초 (API rate limit 방지)


# ------------------------------------------------------------
# 메인 로직
# ------------------------------------------------------------


def read_post_file(file_path: str) -> str:
    """텍스트 파일을 읽어 내용을 반환합니다."""
    path = Path(file_path)
    if not path.exists():
        raise FileNotFoundError(f"포스트 파일을 찾을 수 없습니다: {file_path}")
    return path.read_text(encoding="utf-8").strip()


def upload_post(publisher: ThreadsPublisher, text: str, file_path: str) -> dict:
    """단일 텍스트 포스트를 Threads에 업로드합니다."""
    post_data = {
        "content": {"text": text, "caption": text},
        "image_path": "",  # 빈 문자열 = 텍스트 전용
        "post_id": None,
    }
    result = publisher.publish(post_data)
    return {
        "file": file_path,
        "success": result.get("success", False),
        "threads_post_id": result.get("threads_post_id"),
        "error": result.get("error"),
    }


def main():
    results = []
    publisher = ThreadsPublisher()

    for idx, file_path in enumerate(POST_FILES):
        print(f"\n[{idx + 1}/{len(POST_FILES)}] 포스트 업로드 중: {Path(file_path).name}")

        try:
            text = read_post_file(file_path)
            result = upload_post(publisher, text, file_path)
        except Exception as exc:
            result = {
                "file": file_path,
                "success": False,
                "threads_post_id": None,
                "error": str(exc),
            }

        results.append(result)

        status = "성공" if result["success"] else "실패"
        print(f"  -> {status} | threads_post_id: {result['threads_post_id']} | error: {result['error']}")

        # 마지막 포스트가 아닌 경우 대기
        if idx < len(POST_FILES) - 1:
            print(f"\n  API rate limit 방지를 위해 {DELAY_BETWEEN_POSTS}초 대기 중...")
            time.sleep(DELAY_BETWEEN_POSTS)

    # 최종 결과 JSON 출력
    output = {
        "total": len(results),
        "success_count": sum(1 for r in results if r["success"]),
        "fail_count": sum(1 for r in results if not r["success"]),
        "posts": results,
    }

    print("\n" + "=" * 60)
    print("업로드 결과 (JSON):")
    print("=" * 60)
    print(json.dumps(output, ensure_ascii=False, indent=2))

    return output


if __name__ == "__main__":
    main()
