"""
Extract mass from NX measure expression

This extractor reads mass from a temp file written by solve_simulation.py journal.
The journal extracts the mass from expression p173 and writes it to _temp_mass.txt
"""

from pathlib import Path
from typing import Dict, Any
import sys


def extract_mass_from_expression(prt_file: Path, expression_name: str = "p173") -> float:
    """
    Extract mass from NX expression by reading temp file.

    The solve_simulation.py journal extracts the p173 expression value
    and writes it to _temp_mass.txt in the model directory.

    Args:
        prt_file: Path to .prt file with mass expression
        expression_name: Name of the expression containing mass (default: "p173")

    Returns:
        Mass in kilograms
    """
    prt_file = Path(prt_file)

    if not prt_file.exists():
        raise FileNotFoundError(f"Part file not found: {prt_file}")

    # The mass is written to _temp_mass.txt in the same directory as the .prt
    model_dir = prt_file.parent
    mass_file = model_dir / "_temp_mass.txt"

    if not mass_file.exists():
        raise FileNotFoundError(
            f"Mass temp file not found: {mass_file}\n"
            f"The solve_simulation.py journal should have created this file."
        )

    # Read mass from file
    try:
        with open(mass_file, 'r') as f:
            mass_kg = float(f.read().strip())

        print(f"[OK] Mass from {expression_name}: {mass_kg:.6f} kg ({mass_kg * 1000:.2f} g)")
        return mass_kg

    except ValueError as e:
        raise ValueError(f"Could not parse mass from {mass_file}: {e}")
    except Exception as e:
        raise RuntimeError(f"Failed to read mass file: {e}")


if __name__ == "__main__":
    if len(sys.argv) > 1:
        prt_file = Path(sys.argv[1])
        expression_name = sys.argv[2] if len(sys.argv) > 2 else "p173"
    else:
        print(f"Usage: python {sys.argv[0]} <prt_file> [expression_name]")
        sys.exit(1)

    try:
        mass_kg = extract_mass_from_expression(prt_file, expression_name)
        print(f"\nMass: {mass_kg:.6f} kg ({mass_kg * 1000:.2f} g)")
    except Exception as e:
        print(f"\nERROR: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
