#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
辅助工具函数
"""

from datetime import datetime
import json
import os

def format_datetime(dt):
    """格式化日期时间"""
    if isinstance(dt, str):
        return dt
    if dt:
        return dt.strftime('%Y-%m-%d %H:%M:%S')
    return None

def safe_json_loads(json_str, default=None):
    """安全的JSON解析"""
    try:
        if isinstance(json_str, str):
            return json.loads(json_str)
        return json_str
    except (json.JSONDecodeError, TypeError):
        return default or {}

def safe_json_dumps(obj, default=None):
    """安全的JSON序列化"""
    try:
        return json.dumps(obj, ensure_ascii=False, indent=2)
    except (TypeError, ValueError):
        return default or '{}'

def ensure_dir_exists(dir_path):
    """确保目录存在"""
    if not os.path.exists(dir_path):
        os.makedirs(dir_path, exist_ok=True)
    return dir_path

def get_file_size(file_path):
    """获取文件大小（字节）"""
    try:
        return os.path.getsize(file_path)
    except OSError:
        return 0

def format_file_size(size_bytes):
    """格式化文件大小"""
    if size_bytes == 0:
        return "0B"
    size_names = ["B", "KB", "MB", "GB"]
    i = 0
    while size_bytes >= 1024 and i < len(size_names) - 1:
        size_bytes /= 1024.0
        i += 1
    return f"{size_bytes:.1f}{size_names[i]}"

def truncate_text(text, max_length=100):
    """截断文本"""
    if not text:
        return ""
    if len(text) <= max_length:
        return text
    return text[:max_length] + "..."

def validate_case_number(case_number):
    """验证病历号格式"""
    if not case_number:
        return False
    # 简单验证：非空且长度合理
    return len(case_number.strip()) > 0 and len(case_number.strip()) <= 50

def sanitize_filename(filename):
    """清理文件名，移除不安全字符"""
    import re
    # 移除或替换不安全字符
    filename = re.sub(r'[<>:"/\\|?*]', '_', filename)
    # 移除多余的空格和点
    filename = re.sub(r'\s+', '_', filename.strip())
    filename = filename.strip('.')
    return filename or 'unnamed'
