#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
YouTube Shorts Maker - 웹 인터페이스
Flask 기반 간단한 웹 UI
"""

from flask import Flask, render_template_string, request, jsonify, send_file
import os
from pathlib import Path
import threading
from youtube_shorts_maker import YouTubeShortsConverter

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB max

# 전역 변수
converter = YouTubeShortsConverter(output_dir="./web_shorts_output")
processing_status = {}

# HTML 템플릿
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>YouTube Shorts Maker</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            padding: 40px;
        }
        
        h1 {
            text-align: center;
            color: #333;
            margin-bottom: 10px;
            font-size: 2.5em;
        }
        
        .subtitle {
            text-align: center;
            color: #666;
            margin-bottom: 30px;
        }
        
        .input-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: 600;
        }
        
        input[type="text"],
        input[type="number"] {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        input[type="text"]:focus,
        input[type="number"]:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .checkbox-group {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }
        
        input[type="checkbox"] {
            width: 20px;
            height: 20px;
            margin-right: 10px;
            cursor: pointer;
        }
        
        .btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 18px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.4);
        }
        
        .btn:active {
            transform: translateY(0);
        }
        
        .btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }
        
        .status {
            margin-top: 30px;
            padding: 20px;
            border-radius: 10px;
            display: none;
        }
        
        .status.processing {
            background: #fff3cd;
            border: 2px solid #ffc107;
            display: block;
        }
        
        .status.success {
            background: #d4edda;
            border: 2px solid #28a745;
            display: block;
        }
        
        .status.error {
            background: #f8d7da;
            border: 2px solid #dc3545;
            display: block;
        }
        
        .status-title {
            font-weight: 600;
            margin-bottom: 10px;
            font-size: 18px;
        }
        
        .status-message {
            color: #555;
            line-height: 1.6;
        }
        
        .download-link {
            display: inline-block;
            margin-top: 15px;
            padding: 10px 20px;
            background: #28a745;
            color: white;
            text-decoration: none;
            border-radius: 5px;
            transition: background 0.3s;
        }
        
        .download-link:hover {
            background: #218838;
        }
        
        .progress-bar {
            width: 100%;
            height: 8px;
            background: #e0e0e0;
            border-radius: 4px;
            margin-top: 15px;
            overflow: hidden;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
            width: 0%;
            transition: width 0.3s;
            animation: pulse 1.5s ease-in-out infinite;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.7; }
        }
        
        .examples {
            margin-top: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
        }
        
        .examples h3 {
            color: #555;
            margin-bottom: 10px;
            font-size: 14px;
        }
        
        .example-url {
            color: #667eea;
            cursor: pointer;
            text-decoration: underline;
            font-size: 13px;
        }
        
        .example-url:hover {
            color: #764ba2;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🎬 YouTube Shorts Maker</h1>
        <p class="subtitle">유튜브 동영상을 1분 쇼츠로 자동 변환</p>
        
        <form id="convertForm">
            <div class="input-group">
                <label for="url">유튜브 URL</label>
                <input type="text" 
                       id="url" 
                       name="url" 
                       placeholder="https://www.youtube.com/watch?v=..." 
                       required>
            </div>
            
            <div class="input-group">
                <label for="duration">목표 길이 (초)</label>
                <input type="number" 
                       id="duration" 
                       name="duration" 
                       value="60" 
                       min="10" 
                       max="180" 
                       required>
            </div>
            
            <div class="checkbox-group">
                <input type="checkbox" id="watermark" name="watermark">
                <label for="watermark" style="margin-bottom: 0;">워터마크 추가</label>
            </div>
            
            <button type="submit" class="btn" id="submitBtn">
                쇼츠 만들기
            </button>
        </form>
        
        <div class="examples">
            <h3>📌 예제 URL (테스트용)</h3>
            <div class="example-url" onclick="setExampleUrl('https://www.youtube.com/watch?v=jNQXAC9IVRw')">
                Me at the zoo (짧은 동영상)
            </div>
        </div>
        
        <div id="status" class="status">
            <div class="status-title" id="statusTitle"></div>
            <div class="status-message" id="statusMessage"></div>
            <div class="progress-bar" id="progressBar" style="display: none;">
                <div class="progress-fill"></div>
            </div>
            <a id="downloadLink" class="download-link" style="display: none;">
                📥 쇼츠 다운로드
            </a>
        </div>
    </div>
    
    <script>
        const form = document.getElementById('convertForm');
        const status = document.getElementById('status');
        const statusTitle = document.getElementById('statusTitle');
        const statusMessage = document.getElementById('statusMessage');
        const progressBar = document.getElementById('progressBar');
        const downloadLink = document.getElementById('downloadLink');
        const submitBtn = document.getElementById('submitBtn');
        
        function setExampleUrl(url) {
            document.getElementById('url').value = url;
        }
        
        function updateStatus(type, title, message, showProgress = false) {
            status.className = 'status ' + type;
            statusTitle.textContent = title;
            statusMessage.textContent = message;
            progressBar.style.display = showProgress ? 'block' : 'none';
            downloadLink.style.display = 'none';
        }
        
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const url = document.getElementById('url').value;
            const duration = document.getElementById('duration').value;
            const watermark = document.getElementById('watermark').checked;
            
            // UI 업데이트
            submitBtn.disabled = true;
            submitBtn.textContent = '처리 중...';
            updateStatus('processing', '⏳ 처리 중', '유튜브 동영상을 다운로드하고 있습니다...', true);
            
            try {
                const response = await fetch('/convert', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        url: url,
                        duration: parseInt(duration),
                        watermark: watermark
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    updateStatus('success', '✅ 성공!', data.message);
                    downloadLink.href = '/download/' + data.filename;
                    downloadLink.style.display = 'inline-block';
                } else {
                    updateStatus('error', '❌ 실패', data.message);
                }
            } catch (error) {
                updateStatus('error', '❌ 오류', '처리 중 오류가 발생했습니다: ' + error.message);
            } finally {
                submitBtn.disabled = false;
                submitBtn.textContent = '쇼츠 만들기';
            }
        });
    </script>
</body>
</html>
"""


@app.route('/')
def index():
    """메인 페이지"""
    return render_template_string(HTML_TEMPLATE)


@app.route('/convert', methods=['POST'])
def convert_video():
    """동영상 변환 API"""
    try:
        data = request.get_json()
        
        url = data.get('url')
        duration = data.get('duration', 60)
        watermark = data.get('watermark', False)
        
        if not url:
            return jsonify({
                'success': False,
                'message': 'URL이 필요합니다.'
            }), 400
        
        # 변환 실행
        shorts_path = converter.convert_url_to_shorts(
            youtube_url=url,
            target_duration=duration,
            add_watermark=watermark,
            keep_temp=False
        )
        
        filename = os.path.basename(shorts_path)
        
        return jsonify({
            'success': True,
            'message': f'쇼츠가 성공적으로 생성되었습니다! ({duration}초)',
            'filename': filename,
            'path': shorts_path
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'오류: {str(e)}'
        }), 500


@app.route('/download/<filename>')
def download_file(filename):
    """파일 다운로드"""
    try:
        file_path = converter.output_dir / filename
        
        if not file_path.exists():
            return jsonify({
                'success': False,
                'message': '파일을 찾을 수 없습니다.'
            }), 404
        
        return send_file(
            file_path,
            as_attachment=True,
            download_name=filename,
            mimetype='video/mp4'
        )
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'다운로드 오류: {str(e)}'
        }), 500


def main():
    """웹 서버 실행"""
    print("=" * 60)
    print("🌐 YouTube Shorts Maker - 웹 인터페이스")
    print("=" * 60)
    print("\n📍 브라우저에서 http://localhost:5000 접속")
    print("🛑 종료하려면 Ctrl+C 누르기\n")
    
    app.run(
        host='0.0.0.0',
        port=5000,
        debug=True
    )


if __name__ == '__main__':
    main()
