#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Smart Shorts Maker - DB 연동 Wrapper (pymysql 버전)
PHP에서 호출되어 쇼츠를 생성하고 결과를 DB에 저장
"""

import os
import sys
import argparse
import time
import pymysql
from pathlib import Path
from smart_shorts_maker import SmartShortsConverter

# 데이터베이스 설정
DB_HOST = 'localhost'
DB_USER = 'root'
DB_PASS = 'choi4man1!'
DB_NAME = 'ndegree'

def get_db_connection():
    """데이터베이스 연결"""
    try:
        conn = pymysql.connect(
            host=DB_HOST,
            user=DB_USER,
            password=DB_PASS,
            database=DB_NAME,
            charset='utf8mb4'
        )
        return conn
    except Exception as e:
        print(f"DB 연결 실패: {str(e)}", file=sys.stderr)
        sys.exit(1)

def update_shorts_status(conn, shorts_id, status, **kwargs):
    """쇼츠 상태 업데이트"""
    try:
        cursor = conn.cursor()
        
        # 동적으로 UPDATE 쿼리 생성
        updates = ['status = %s']
        values = [status]
        
        for key, value in kwargs.items():
            updates.append(f"{key} = %s")
            values.append(value)
        
        updates.append('updated_at = NOW()')
        
        if status == 'completed':
            updates.append('completed_at = NOW()')
        
        query = f"UPDATE shorts_videos SET {', '.join(updates)} WHERE id = %s"
        values.append(shorts_id)
        
        cursor.execute(query, values)
        conn.commit()
        cursor.close()
        
    except Exception as e:
        print(f"DB 업데이트 실패: {str(e)}", file=sys.stderr)

def main():
    parser = argparse.ArgumentParser(description='Smart Shorts Maker - DB Wrapper')
    parser.add_argument('--shorts-id', type=int, required=True, help='Shorts ID')
    parser.add_argument('--source-type', required=True, choices=['file', 'youtube'], help='Source type')
    parser.add_argument('--source-path', required=True, help='Source path or URL')
    parser.add_argument('--duration', type=int, default=60, help='Target duration')
    parser.add_argument('--subtitles', action='store_true', help='Include subtitles')
    parser.add_argument('--language', default='ko', help='Language')
    
    args = parser.parse_args()
    
    # DB 연결
    conn = get_db_connection()
    
    # 시작 시간
    start_time = time.time()
    
    try:
        print(f"쇼츠 생성 시작 (ID: {args.shorts_id})")
        
        # SmartShortsConverter 초기화
        converter = SmartShortsConverter(
            output_dir="/var/www/html/bicorn/ndegree/smart_shorts_output",
            openai_api_key=os.getenv('OPENAI_API_KEY')
        )
        
        # 쇼츠 생성
        if args.source_type == 'file':
            # 파일 업로드인 경우
            print("📁 업로드된 파일 처리 중...")
            
            # 업로드된 파일을 직접 처리
            # convert_existing_video 방식 사용
            from moviepy.editor import VideoFileClip
            
            # 파일 존재 확인
            if not os.path.exists(args.source_path):
                raise FileNotFoundError(f"파일을 찾을 수 없습니다: {args.source_path}")
            
            # 동영상 로드 및 전사
            transcription = converter.transcribe_video(args.source_path, language=args.language)
            
            # 동영상 길이 확인
            video = VideoFileClip(args.source_path)
            video_duration = video.duration
            video.close()
            
            # 중요 구간 분석
            scored_segments = converter.analyze_important_segments(transcription, video_duration)
            
            # 목표 시간에 맞게 구간 선택
            selected_segments = converter.select_segments_for_target_duration(
                scored_segments, args.duration
            )
            
            # 쇼츠 동영상 생성
            shorts_path = converter.create_smart_shorts(
                args.source_path, selected_segments, args.subtitles
            )
            
            # ChatGPT 요약 생성
            summary = converter.generate_summary_with_gpt(transcription)
            
            # 요약 파일 저장
            summary_file = converter.save_summary_file(summary, selected_segments, shorts_path)
            
        else:  # YouTube
            print("▶️  YouTube 다운로드 및 처리...")
            
            shorts_path, summary = converter.convert_url_to_smart_shorts(
                youtube_url=args.source_path,
                target_duration=args.duration,
                add_subtitles=args.subtitles,
                keep_temp=False,
                language=args.language
            )
        
        # 처리 시간 계산
        processing_time = int(time.time() - start_time)
        
        # 파일 정보
        shorts_size = os.path.getsize(shorts_path) if os.path.exists(shorts_path) else 0
        shorts_filename = os.path.basename(shorts_path)
        
        # 요약 파일 경로
        summary_file = str(Path(shorts_path).with_suffix('.txt'))
        
        # DB 업데이트
        update_shorts_status(
            conn,
            args.shorts_id,
            'completed',
            shorts_filename=shorts_filename,
            shorts_path=shorts_path,
            shorts_size=shorts_size,
            ai_summary=summary,
            summary_file=summary_file if os.path.exists(summary_file) else None,
            processing_time=processing_time
        )
        
        print(f"✅ 쇼츠 생성 완료!")
        print(f"   파일: {shorts_filename}")
        print(f"   요약: {summary}")
        print(f"   처리 시간: {processing_time}초")
        
        conn.close()
        sys.exit(0)
        
    except Exception as e:
        # 에러 발생
        processing_time = int(time.time() - start_time)
        error_message = str(e)
        
        print(f"❌ 에러: {error_message}", file=sys.stderr)
        
        # DB에 에러 기록
        update_shorts_status(
            conn,
            args.shorts_id,
            'failed',
            error_message=error_message,
            processing_time=processing_time
        )
        
        conn.close()
        sys.exit(1)

if __name__ == '__main__':
    main()