"""
movgen_setup.py
더블클릭 한 번으로 전체 자동 설치
"""
import os, sys, subprocess, urllib.request, urllib.error, zipfile, shutil

BASE    = "C:\\youtube-news"
VENV_PY = os.path.join(BASE, "venv", "Scripts", "python.exe")
PIP     = os.path.join(BASE, "venv", "Scripts", "pip.exe")
CF      = "https://ytnews-api.maclub7.workers.dev"

PY_FILES = {
    "movgen.py":      f"{CF}/download/movgen",
    "collector.py":   f"{CF}/download/collector",
    "writer.py":      f"{CF}/download/writer",
    "tts.py":         f"{CF}/download/tts",
    "video_maker.py": f"{CF}/download/video_maker",
    "uploader.py":    f"{CF}/download/uploader",
    "config.py":      f"{CF}/download/config",
}

# Cloudflare 차단 방지용 헤더
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}

def download(url, dest):
    req = urllib.request.Request(url, headers=HEADERS)
    with urllib.request.urlopen(req, timeout=30) as r:
        with open(dest, 'wb') as f:
            f.write(r.read())

def title(msg):
    print(f"\n{'─'*50}\n  {msg}\n{'─'*50}")

def run(cmd):
    return subprocess.run(cmd, shell=True, capture_output=True).returncode == 0

def main():
    os.system("cls")
    print("""
╔══════════════════════════════════════════╗
║   MOVGEN  자동 설치 프로그램             ║
║   잠시 기다려주세요... (약 3~5분)        ║
╚══════════════════════════════════════════╝
    """)

    title("1/5  폴더 생성")
    os.makedirs(BASE, exist_ok=True)
    os.makedirs(os.path.join(BASE, "output"), exist_ok=True)
    print("  ✅ C:\\youtube-news 생성 완료")

    title("2/5  Python 가상환경 설정")
    if not os.path.exists(VENV_PY):
        run(f'python -m venv "{BASE}\\venv"')
    print("  ✅ 완료")

    title("3/5  필요 패키지 설치 (잠시 기다려주세요)")
    pkgs = "google-api-python-client google-auth-oauthlib google-auth-httplib2 youtube-transcript-api anthropic google-cloud-texttospeech requests pillow yt-dlp fal-client"
    run(f'"{PIP}" install {pkgs} -q')
    print("  ✅ 패키지 설치 완료")

    title("4/5  FFmpeg 설치")
    if os.path.exists("C:\\ffmpeg\\bin\\ffmpeg.exe"):
        print("  ✅ 이미 설치됨")
    else:
        print("  다운로드 중...")
        try:
            url = "https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip"
            zp  = os.path.join(BASE, "ffmpeg.zip")
            req = urllib.request.Request(url, headers=HEADERS)
            with urllib.request.urlopen(req, timeout=120) as r:
                with open(zp, 'wb') as f:
                    f.write(r.read())
            with zipfile.ZipFile(zp,'r') as z: z.extractall("C:\\")
            for item in os.listdir("C:\\"):
                if item.startswith("ffmpeg-") and os.path.isdir(f"C:\\{item}"):
                    if os.path.exists("C:\\ffmpeg"): shutil.rmtree("C:\\ffmpeg")
                    os.rename(f"C:\\{item}", "C:\\ffmpeg")
                    break
            os.remove(zp)
            run('setx PATH "%PATH%;C:\\ffmpeg\\bin"')
            print("  ✅ FFmpeg 설치 완료")
        except Exception as e:
            print(f"  ⚠️  FFmpeg 자동 설치 실패: {e}")
            print("     수동 설치: https://www.gyan.dev/ffmpeg/builds")

    title("5/5  MOVGEN 파일 자동 다운로드")
    for fname, url in PY_FILES.items():
        dest = os.path.join(BASE, fname)
        try:
            download(url, dest)
            print(f"  ✅ {fname}")
        except Exception as e:
            print(f"  ❌ {fname} 실패: {e}")

    print(f"""
╔══════════════════════════════════════════╗
║  ✅ 설치 완료!                           ║
║                                          ║
║  C:\\youtube-news\\movgen.py              ║
║  를 더블클릭하면 바로 실행됩니다!        ║
╚══════════════════════════════════════════╝
    """)
    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()
        print("\n  해결책:")
        print("  Python 설치 시 'Add Python to PATH' 체크 후 재설치")
        input("\n  엔터 누르면 닫힙니다...")
        sys.exit(1)
