#!/usr/bin/env python3
"""
Test GoldSim Reset Logic
Verifies that Period 1 calls reset state properly for Tutorial 2 initial conditions
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from gspy_interface import run_modflow_step
import time

def test_goldsim_reset():
    """Test the reset logic for GoldSim integration"""
    
    print("=" * 70)
    print("GOLDSIM RESET LOGIC TEST")
    print("Testing automatic state reset for Period 1 calls")
    print("=" * 70)
    
    # First call should reset and start with 10.0m
    print("\n--- Test 1: First Period 1 Call (should reset) ---")
    head1 = run_modflow_step(1, 0.0, 10.0, 0.3)[0]
    print(f"Period 1 head: {head1:.6f} m")
    
    if abs(head1 - 10.0) < 0.01:
        print("✓ PASS: Started with proper Tutorial 2 initial conditions")
    else:
        print(f"⚠ CONCERN: Expected ~10.0m, got {head1:.6f}m")
    
    # Second call should use previous state
    print("\n--- Test 2: Period 2 Call (should use state) ---")
    head2 = run_modflow_step(2, 0.0, 10.0, 0.3)[0]
    print(f"Period 2 head: {head2:.6f} m")
    print(f"Change from Period 1: {head2 - head1:+.6f} m")
    
    # Simulate time gap (like GoldSim restart)
    print("\n--- Test 3: Period 1 after gap (should reset) ---")
    time.sleep(1)  # Small gap
    head3 = run_modflow_step(1, 0.0, 10.0, 0.3)[0]  # This should NOT reset (gap too small)
    print(f"Period 1 after small gap: {head3:.6f} m")
    
    # Larger gap
    print("\n--- Test 4: Period 1 after large gap (should reset) ---")
    time.sleep(11)  # Gap > 10 seconds
    head4 = run_modflow_step(1, 0.0, 10.0, 0.3)[0]  # This SHOULD reset
    print(f"Period 1 after large gap: {head4:.6f} m")
    
    if abs(head4 - 10.0) < 0.01:
        print("✓ PASS: Reset properly after time gap")
    else:
        print(f"⚠ ISSUE: Expected reset to ~10.0m, got {head4:.6f}m")
    
    print("\n--- Test 5: Period 3 -> Period 1 transition (should reset) ---")
    # Simulate end of simulation
    head5 = run_modflow_step(3, -500.0, 10.0, 0.3)[0]
    print(f"Period 3 pumping: {head5:.6f} m")
    
    # New simulation starts
    head6 = run_modflow_step(1, 0.0, 10.0, 0.3)[0]
    print(f"New simulation Period 1: {head6:.6f} m")
    
    if abs(head6 - 10.0) < 0.01:
        print("✓ PASS: Reset properly after Period 3->1 transition")
    else:
        print(f"⚠ ISSUE: Expected reset to ~10.0m, got {head6:.6f}m")
    
    print("\n" + "=" * 70)
    print("RESET LOGIC TEST COMPLETE")
    print("GoldSim should now start with proper 10.0m initial conditions")
    print("=" * 70)

if __name__ == "__main__":
    test_goldsim_reset()