#!/usr/bin/env python

"""████
 ██    ██    Datature
   ██  ██    Powering Breakthrough AI
     ██

@File    :   helper.py
@Author  :   Wei Loon Cheng
@Contact :   developers@datature.io
@License :   Apache License 2.0
@Desc    :   Datature Vi SDK assets utils helper module.
"""

from pathlib import Path

from vi.api.resources.datasets.assets.types import FilePart


def calculate_parts(file_size: int, part_count: int) -> list[FilePart]:
    """Calculate byte ranges for splitting a file into parts.

    Matches the backend's JavaScript implementation which gives remainder
    bytes to the last part.

    Args:
        file_size: Total file size in bytes.
        part_count: Number of parts to split the file into.

    Returns:
        List of FilePart objects defining byte ranges.

    Raises:
        ValueError: If part_count is less than 1.

    """
    if part_count < 1:
        raise ValueError(f"part_count must be >= 1, got {part_count}")

    part_size = file_size // part_count

    parts = []
    for part_number in range(1, part_count + 1):
        start = (part_number - 1) * part_size
        # Last part gets any remainder bytes
        end = part_number * part_size if part_number < part_count else file_size
        parts.append(
            FilePart(
                part_number=part_number,
                start_byte=start,
                end_byte=end,
            )
        )

    return parts


def read_part(file_path: str | Path, part: FilePart) -> bytes:
    """Read a specific part's bytes from file.

    Args:
        file_path: Path to the file.
        part: FilePart defining the byte range to read.

    Returns:
        Bytes content of the specified part.

    """
    with open(file_path, "rb") as f:
        f.seek(part.start_byte)
        return f.read(part.size)
