#!/usr/bin/env python3
"""
Test GoldSim Starting with Period 2
Simulates the exact scenario from the user's log where GoldSim starts with Period 2
"""

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

# Simulate fresh Python module load by restarting globals
import importlib
import gspy_interface
importlib.reload(gspy_interface)

from gspy_interface import run_modflow_step

def test_period2_start():
    """Test what happens when GoldSim starts with Period 2 (like in user's log)"""
    
    print("=" * 80)
    print("GOLDSIM PERIOD 2 START TEST")
    print("Simulating user's log scenario where GoldSim starts with Period 2")
    print("=" * 80)
    
    print("\n--- Simulating User's Log Scenario ---")
    print("GoldSim starts directly with Period 2 calls (no Period 1)")
    
    # First call: Period 2 (like in user's log)
    print("\n1st Call: Period 2 (should trigger reset)")
    head1 = run_modflow_step(2, 0.0, 10.0, 0.3)[0]
    print(f"   Result: {head1:.6f} m")
    
    # Second call: Period 2 (continuing simulation)
    print("\n2nd Call: Period 2 (should use state)")
    head2 = run_modflow_step(2, 0.0, 10.0, 0.3)[0]
    print(f"   Result: {head2:.6f} m")
    print(f"   Change: {head2 - head1:+.6f} m")
    
    # Third call: Period 2 (continuing simulation)
    print("\n3rd Call: Period 2 (should use state)")
    head3 = run_modflow_step(2, 0.0, 10.0, 0.3)[0]
    print(f"   Result: {head3:.6f} m")
    print(f"   Change: {head3 - head2:+.6f} m")
    
    print("\n--- Analysis ---")
    
    # Check if reset worked
    if abs(head1 - 10.0) < 1.0:  # Should be close to 10.0 if reset worked
        print("✅ RESET DETECTION: Working correctly")
        print("   First call triggered state reset despite being Period 2")
    else:
        print("❌ RESET DETECTION: Failed")
        print(f"   First call used old state: {head1:.6f}m")
    
    # Check state persistence
    if head1 != head2:
        print("✅ STATE PERSISTENCE: Working correctly")
        print("   Subsequent calls use previous state")
    else:
        print("❌ STATE PERSISTENCE: Failed")
        print("   Heads not changing between calls")
    
    print(f"\nHead Progression:")
    print(f"  Call 1: {head1:.6f} m")
    print(f"  Call 2: {head2:.6f} m") 
    print(f"  Call 3: {head3:.6f} m")
    
    # Expected behavior
    print(f"\nExpected vs Actual:")
    print(f"  Expected Call 1: ~10.0m (reset)")
    print(f"  Actual Call 1:   {head1:.6f}m")
    
    if abs(head1 - 10.0) < 1.0:
        success = "✅ SUCCESS"
        status = "GoldSim integration will work correctly even starting with Period 2"
    else:
        success = "⚠ NEEDS ADJUSTMENT"
        status = "May need stronger reset detection"
    
    print(f"\n{success}: {status}")
    
    print("\n" + "=" * 80)
    print("PERIOD 2 START TEST COMPLETE")
    print("=" * 80)

if __name__ == "__main__":
    test_period2_start()