from pathlib import Path
from typing import Union
from . import __version__


def write_header(path: Union[str, Path]):
    """Write the header for the new Zacros input file.

    Parameters
    ----------
    path: Union[str, Path]
        Path of the input file where the header will be written.

    Raises
    ------
    IOError
        If the file cannot be opened for writing.
    """
    line_width = 80  # Fixed width for each header line

    try:
        path = Path(path)
        with path.open('w') as infile:
            # Top border
            border = '#' * line_width
            infile.write(border + '\n')

            # Version line
            line = f"#  Zacros input file generated by ZacrosTools (version {__version__})"
            pad = max(line_width - len(line) - 1, 1)
            infile.write(f"{line}{' ' * pad}#\n")

            # Source code line
            line = "#  Source code: https://github.com/hprats/ZacrosTools"
            pad = max(line_width - len(line) - 1, 1)
            infile.write(f"{line}{' ' * pad}#\n")

            # Citation split across three lines
            citations = [
                "#  If you use ZacrosTools in your research, please cite:",
                "#    Prats, H. J. Phys. Chem. A 2025, 129, 6608–6614.",
                "#    DOI: 10.1021/acs.jpca.5c02802"
            ]
            for c in citations:
                pad = max(line_width - len(c) - 1, 1)
                infile.write(f"{c}{' ' * pad}#\n")

            # Blank line before author
            blank = "#"
            pad = line_width - len(blank) - 1
            infile.write(f"{blank}{' ' * pad}#\n")

            # Author line (last before closing border)
            line = "#  Hector Prats, PhD"
            pad = max(line_width - len(line) - 1, 1)
            infile.write(f"{line}{' ' * pad}#\n")

            # Closing border + one blank line
            infile.write(border + '\n\n')

    except IOError as e:
        raise IOError(f"Failed to write header to '{path}': {e}")
