import matplotlib.pyplot as plt
import numpy as np


def print_streamfile_time(file_path: str) -> None:
    if not file_path.endswith(".str"):
        file_path += ".str"

    pass_time = 0

    # Open the file and read all lines.
    with open(file_path, 'r') as f:
        lines = f.readlines()

    passes = int(lines[1].strip())

    # Skip the first three header lines.
    for line in lines[3:]:
        line = line.strip()
        if not line:  # Skip empty lines, if any.
            continue

        # Split the line into parts.
        parts = line.split()
        pass_time += float(parts[0])

    pass_time_us = pass_time / 10
    pass_time_s = pass_time_us * 1e-6
    total_time = pass_time_s * passes

    # Convert total seconds to HH:MM:SS format
    hours, remainder = divmod(int(total_time), 3600)
    minutes, seconds = divmod(remainder, 60)

    string = ""
    if seconds == 0:
        print("Mill time is below 0 seconds.")
        return
    else:
        if seconds > 1:
            string += str(seconds) + " seconds."
        else:
            string += str(seconds) + " second."
    if minutes != 0:
        if minutes > 1:
            string = str(minutes) + " minutes, and " + string
        else:
            string = str(minutes) + " minute, and " + string
    if hours != 0:
        if hours > 1:
            string = str(hours) + " hours, "
        else:
            string = str(hours) + " hour, "

    print("Mill time: " + string)


def plot_stream_file(file_path: str, title: str = None) -> None:

    if not file_path.endswith(".str"):
        file_path += ".str"

    segments = []  # List to store segments (each segment is a list of (x, y) tuples)
    current_segment = []  # List to store the current segment

    # Open the file and read all lines.
    with open(file_path, 'r') as f:
        lines = f.readlines()

    # Skip the first three header lines.
    for line in lines[3:]:
        line = line.strip()
        if not line:  # Skip empty lines, if any.
            continue

        # Split the line into parts.
        parts = line.split()

        # We expect at least three numbers per line.
        if len(parts) < 3:
            continue

        # The second and third elements are x and y pixel coordinates.
        # (Remember: list indices start at 0, so parts[1] is the second element.)
        try:
            x = int(parts[1])
            y = int(parts[2])
        except ValueError:
            raise ValueError(f"x and y-coordinates must be integers representing a pixel. "
                             f"Got: ({parts[1]}, {parts[2]}).")

        # Check if there is a fourth element.
        if len(parts) >= 4:
            if current_segment:
                segments.append(current_segment.copy())
            current_segment = [(x, y)]

        else:
            current_segment.append((x, y))

    segments.append(current_segment.copy())

    # Now, plot each segment.
    for seg in segments:
        # Unzip the list of (x,y) tuples into separate x and y lists.
        seg = np.array(seg)
        seg *= np.array([1, -1])
        seg += np.array([0, 65536])
        xs, ys = zip(*seg)
        plt.plot(xs, ys, "o-")  # You can remove or adjust marker style if desired.

    plt.xlabel("X Pixels")
    plt.ylabel("Y Pixels")
    plt.title("Streamlines")
    plt.xlim(0, 65535)
    plt.ylim(0, 65535)
    plt.gca().set_aspect("equal")
    plt.show()
