"""
Legacy .dat file output for compatibility with existing tools.
"""

from __future__ import annotations

from pathlib import Path

from flow_state._version import __version__
from flow_state.core import FlowState


def write_flow_conditions_dat(
    state: FlowState,
    path: str | Path = "flow_conditions.dat",
    include_header: bool = True,
) -> None:
    """
    Write flow conditions to a legacy .dat file format.

    This produces a simple key = value format compatible with older tools
    that expect flow_conditions.dat files.

    Args:
        state: FlowState to write.
        path: Output file path. Defaults to "flow_conditions.dat".
        include_header: Whether to include a comment header. Defaults to True.

    File format:
        # flow_conditions.dat
        # Generated by flow_state vX.X.X
        p = 101325.0
        T = 300.0
        rho = 1.1768
        ...
    """
    path = Path(path)

    lines: list[str] = []

    if include_header:
        lines.extend([
            "# flow_conditions.dat",
            f"# Generated by flow_state v{__version__}",
            f"# Gas model: {state.gas_model}",
            f"# Transport model: {state.transport_model or 'None'}",
            "#",
        ])

    # Write primary thermodynamic properties
    lines.append(f"pres = {state.pres:.6e}")
    lines.append(f"temp = {state.temp:.6f}")
    lines.append(f"dens = {state.dens:.6e}")
    lines.append(f"gamma = {state.gamma:.6f}")
    lines.append(f"r_gas = {state.r_gas:.6f}")

    # Write derived thermodynamic properties
    if state.cp is not None:
        lines.append(f"cp = {state.cp:.6f}")
    if state.cv is not None:
        lines.append(f"cv = {state.cv:.6f}")

    # Write kinematic properties
    lines.append(f"a = {state.a:.6f}")
    if state.mach is not None:
        lines.append(f"M = {state.mach:.6f}")
    if state.uvel is not None:
        lines.append(f"uvel = {state.uvel:.6f}")

    # Write transport properties
    if state.mu is not None:
        lines.append(f"mu = {state.mu:.6e}")
    if state.nu is not None:
        lines.append(f"nu = {state.nu:.6e}")
    if state.pr is not None:
        lines.append(f"pr = {state.pr:.6f}")
    if state.re1 is not None:
        lines.append(f"re1 = {state.re1:.6e}")

    # Write to file
    with path.open("w") as f:
        f.write("\n".join(lines))
        f.write("\n")
