# -*- coding: utf-8 -*-
"""
工具函数
"""

import os
from datetime import datetime
from typing import Optional


def parse_datetime(date_str: str) -> Optional[datetime]:
    """
    解析日期时间字符串
    支持多种格式
    """
    if not date_str:
        return None
    
    formats = [
        "%Y-%m-%d %H:%M:%S",
        "%Y-%m-%d %H:%M",
        "%Y/%m/%d %H:%M:%S",
        "%Y/%m/%d %H:%M",
        "%Y-%m-%dT%H:%M:%S",
        "%Y-%m-%dT%H:%M:%SZ",
    ]
    
    for fmt in formats:
        try:
            return datetime.strptime(date_str, fmt)
        except ValueError:
            continue
    
    return None


def validate_video_file(video_path: str) -> bool:
    """
    验证视频文件是否存在且有效
    """
    if not video_path:
        return False
    
    if not os.path.exists(video_path):
        return False
    
    if not os.path.isfile(video_path):
        return False
    
    # 检查文件扩展名
    valid_extensions = ['.mp4', '.mov', '.avi', '.mkv', '.flv', '.wmv', '.webm']
    ext = os.path.splitext(video_path)[1].lower()
    if ext not in valid_extensions:
        return False
    
    # 检查文件大小（至少 1KB）
    if os.path.getsize(video_path) < 1024:
        return False
    
    return True


def get_video_duration(video_path: str) -> Optional[float]:
    """
    获取视频时长（秒）
    需要安装 ffprobe
    """
    try:
        import subprocess
        result = subprocess.run(
            ['ffprobe', '-v', 'error', '-show_entries', 'format=duration',
             '-of', 'default=noprint_wrappers=1:nokey=1', video_path],
            capture_output=True,
            text=True
        )
        return float(result.stdout.strip())
    except:
        return None


def format_file_size(size_bytes: int) -> str:
    """
    格式化文件大小
    """
    for unit in ['B', 'KB', 'MB', 'GB']:
        if size_bytes < 1024.0:
            return f"{size_bytes:.2f} {unit}"
        size_bytes /= 1024.0
    return f"{size_bytes:.2f} TB"
