"""
通用处理工具，字符串切分
"""
from pathlib import Path

import cv2


def divide_string(s, num_parts):
    """
    切割字符串为指定均分的部分
    :param s: 待切割的字符串
    :param num_parts: 切割份数
    :return: 切分结果
    """
    n = len(s)
    part_size = n // num_parts
    sizes = [part_size + 1 if i < n % num_parts else part_size for i in range(num_parts)]
    parts = []
    start = 0
    for size in sizes:
        parts.append(s[start:start + size])
        start += size
    return parts


def find_relative_directories(root_dir, target_dir):
    """
    查找指定目录下的目标目录相对路径
    :param root_dir: 根目录
    :param target_dir: 目标目录
    :return: 根目录到目标目录的相对路径
    """
    root_path = Path(root_dir)
    yolox_paths = []

    # 递归查找指定目录
    for path in root_path.rglob(target_dir):
        if path.is_dir():
            # 计算相对路径
            relative_path = path.relative_to(root_path)
            yolox_paths.append(relative_path)

    return yolox_paths


def detect_and_decode_qr_code(img_path):
    """
    从图片中提取二维码中的内容
    :param img_path: 待提取二维码内容的图片地址
    :return: 提取信息
    """
    image = cv2.imread(img_path)
    # Initialize the QRCode detector
    qr_code_detector = cv2.QRCodeDetector()

    # Detect and decode the QR code
    decoded_text, points, _ = qr_code_detector.detectAndDecode(image)

    if points is not None:
        # Convert to integer type
        points = points[0].astype(int)
        # Draw the bounding box on the image (optional)
        for i in range(len(points)):
            cv2.line(image, tuple(points[i]), tuple(points[(i + 1) % len(points)]), (255, 0, 0), 2)
        return decoded_text, points
    else:
        return None, None


def get_file_extension(filename):
    """
    获取文件扩展名
    :param filename: 文件名
    :return: 扩展名
    """
    return filename.rsplit('.', 1)[1].lower()

