#!/usr/bin/env python3
# -*- coding:utf-8 -*-

from __future__ import annotations

import re
import unicodedata
from datetime import datetime

import pytz

from pendingai import config


def format_filesize(num_bytes: int | float, suffix: str = "B") -> str:
    """
    Format a number of bytes into a human readable format.

    Args:
        num_bytes (int | float): Number of bytes to convert.
        suffix (str, optional): Suffix for output unit. Defaults to "B".

    Returns:
        str: Human readable filesize.
    """
    for unit in ("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"):
        if abs(num_bytes) < 1024.0:
            return f"{num_bytes:3.1f}{unit}{suffix}"
        num_bytes /= 1024.0
    return f"{num_bytes:.1f}Yi{suffix}"


def format_filename(filename: str) -> str:
    """
    Format a filename into a sanitized string.

    Args:
        filename (str): File basename to sanitize.

    Returns:
        str: Sanitized filename.
    """
    filename = (
        unicodedata.normalize("NFKD", filename).encode("ascii", "ignore").decode("ascii")
    )
    filename = re.sub(r"[^\.\w\s-]", "", filename.lower())
    return re.sub(r"[-\.\s]+", "_", filename).strip("-_")


def localize_datetime(dt: datetime) -> datetime:
    """
    Localize a datetime timestamp into timezone-considerate UTC with
    offset +00:00 and then cast to the local timezone for the user.

    Args:
        dt (datetime): Datetime object.

    Returns:
        datetime: Datetime object with local timezone.
    """

    return pytz.utc.localize(dt).astimezone(config.LOCAL_TZINFO)
