"""
Test: Verify NX regenerates .dat and .op2 files with new timestamps

This test verifies the fix for OP2 caching by checking file timestamps.
"""

from pathlib import Path
import sys
import time

sys.path.insert(0, str(Path(__file__).parent.parent))

from optimization_engine.nx.solver import NXSolver

print("=" * 60)
print("Testing timestamp verification fix")
print("=" * 60)

sim_file = Path('studies/bracket_displacement_maximizing/model/Bracket_sim1.sim')

if not sim_file.exists():
    print(f"ERROR: Simulation file not found: {sim_file}")
    sys.exit(1)

# Check current timestamps
dat_file = sim_file.parent / "bracket_sim1-solution_1.dat"
op2_file = sim_file.parent / "bracket_sim1-solution_1.op2"

print(f"\nSimulation file: {sim_file}")
print(f"Working directory: {sim_file.parent}")

if dat_file.exists():
    old_dat_time = dat_file.stat().st_mtime
    print(f"\nBefore solve:")
    print(f"  .dat modified: {time.ctime(old_dat_time)}")

if op2_file.exists():
    old_op2_time = op2_file.stat().st_mtime
    print(f"  .op2 modified: {time.ctime(old_op2_time)}")

# Run solve with timestamp verification
print(f"\nRunning solve with timestamp verification...")
solver = NXSolver(nastran_version='2412', use_journal=True)
result = solver.run_simulation(sim_file)

print(f"\nSolve result: {'SUCCESS' if result['success'] else 'FAILED'}")

# Check new timestamps
if op2_file.exists():
    new_op2_time = op2_file.stat().st_mtime
    print(f"\nAfter solve:")
    print(f"  .op2 modified: {time.ctime(new_op2_time)}")

    if 'old_op2_time' in locals():
        if new_op2_time > old_op2_time:
            print(f"\n  ✓ SUCCESS! .op2 file was regenerated!")
            print(f"    Time difference: {new_op2_time - old_op2_time:.1f} seconds")
        else:
            print(f"\n  ✗ FAILED! .op2 file was NOT updated")
            print(f"    This means NX did not regenerate the file")
    else:
        print(f"\n  ✓ New .op2 file created")

if dat_file.exists():
    new_dat_time = dat_file.stat().st_mtime
    print(f"  .dat modified: {time.ctime(new_dat_time)}")

    if 'old_dat_time' in locals():
        if new_dat_time > old_dat_time:
            print(f"\n  ✓ .dat file was also regenerated")
