"""
movgen.py - 전체 파이프라인 자동 실행
대시보드에서 설정 후 이 파일만 더블클릭하면 됩니다
"""
import os, sys, subprocess, datetime, requests, json

BASE   = "C:\\youtube-news"
PYTHON = os.path.join(BASE, "venv", "Scripts", "python.exe")
GCLOUD = os.path.join(BASE, "gcloud-key.json")
CF_API = "https://ytnews-api.maclub7.workers.dev"

STEPS = [
    ("collect", "영상 수집",    "collector.py", ""),
    ("write",   "뉴스 재작성",  "writer.py",    ""),
    ("tts",     "TTS 나레이션", "tts.py",       ""),
    ("video",   "영상 합성",    "video_maker.py",""),
    ("upload",  "유튜브 업로드","uploader.py",  ""),
]

def save_status(steps_dict, msg=""):
    try:
        requests.post(CF_API+'/save-status',
            json={"steps": steps_dict, "last_msg": msg},
            headers={'Content-Type':'application/json'}, timeout=5)
    except: pass

def get_write_count():
    try:
        r = requests.get(CF_API+'/get-status', timeout=5)
        return int(r.json().get('write_count', 5))
    except: return 5

def check():
    if not os.path.exists(PYTHON):
        print("❌ movgen_setup.py를 먼저 실행하세요")
        input("엔터를 누르면 닫힙니다..."); sys.exit(1)

def main():
    check()
    count = get_write_count()

    os.system("cls")
    print(f"""
╔══════════════════════════════════════════╗
║   MOVGEN  유튜브 뉴스 자동화            ║
║   처리 갯수: {count}개                          
║   시작: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}            
╚══════════════════════════════════════════╝
""")

    # 전체 초기화
    status = {k:"idle" for k,_,_,_ in STEPS}
    save_status(status)

    env = os.environ.copy()
    if os.path.exists(GCLOUD):
        env["GOOGLE_APPLICATION_CREDENTIALS"] = GCLOUD

    for key, name, script, _ in STEPS:
        print(f"\n{'─'*50}")
        print(f"  ▶ {name} 시작...")
        print(f"{'─'*50}")

        # 실행 중 상태 저장 → 대시보드 자동 업데이트
        status[key] = "running"
        save_status(status, f"{name} 진행중...")

        # writer.py에는 --count 인수 전달
        cmd = [PYTHON, os.path.join(BASE, script)]
        if key == "write":
            cmd += ["--count", str(count)]

        result = subprocess.run(cmd, env=env, cwd=BASE)

        if result.returncode != 0:
            status[key] = "error"
            save_status(status)
            print(f"\n❌ {name} 실패")
            input("엔터를 누르면 닫힙니다..."); sys.exit(1)

        # 완료 상태 저장 → 대시보드 자동 다음 단계
        status[key] = "done"
        save_status(status, f"{name} 완료 ✅")
        print(f"  ✅ {name} 완료")

    print(f"""
╔══════════════════════════════════════════╗
║  🎉 전체 파이프라인 완료!               ║
║  https://ytnews-dashboard.pages.dev      ║
╚══════════════════════════════════════════╝
""")
    input("엔터를 누르면 닫힙니다...")

if __name__ == "__main__":
    import sys, traceback
    try:
        main()
    except SystemExit:
        pass
    except Exception as e:
        print("\n" + "="*50)
        print(f"  오류: {e}")
        print("="*50)
        traceback.print_exc()
        input("\n  엔터 누르면 닫힙니다...")
        sys.exit(1)
