from colorama import init
from typing import Literal
from datetime import datetime


def GLength(text):
    length = 0
    for char in text:
        if "\u4e00" <= char <= "\u9fff":
            length += 2.5
        else:
            length += 1
    return length


def FSplit(text, max_length=50):
    lines = []
    current_line = ""
    current_length = 0
    for char in text:
        char_length = 2.5 if "\u4e00" <= char <= "\u9fff" else 1
        if current_length + char_length > max_length:
            lines.append(current_line)
            current_line = char
            current_length = char_length
        else:
            current_line += char
            current_length += char_length
    if current_line:
        lines.append(current_line)
    return lines


def FConcat(prefix, output, color):
    prefix = f"{prefix} "
    prefix_length = GLength(prefix)
    available_length = 50 - prefix_length
    lines = FSplit(output, available_length)
    print(f"\033[9{color}m\033[1m\n{prefix}{lines[0]}\033[0m")
    for line in lines[1:]:
        print(f"\033[9{color}m\033[1m{' ' * len(prefix)}{line}\033[0m")


def FPrint(
    format: Literal["error", "warning", "info", "default"] = "default",
    output="",
    mark=True,
):
    init(autoreset=True)

    padding = (50 - len(f"[ {datetime.now().strftime('%Y-%m-%d  %H:%M:%S')} ]")) / 2

    if mark:
        print(
            f"\033[96m\033[1m\n\n {int(padding) * '='}[ {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ]{int(padding) * '='}\n\033[0m"
        )
    if format == "error":
        FConcat(" [ ERROR ]", output, 1)
    elif format == "warning":
        FConcat(" [ WARN ]", output, 3)
    elif format == "info":
        FConcat(" [ INFO ]", output, 4)
    elif format == "default":
        FConcat(" [ OUTPUT ]", output, 2)
    else:
        return False
    if mark:
        print(f"\033[96m\033[1m \n {'=' * 49} \n\033[0m")
