"""
WEL Package Sign Convention Diagnostic Test
Tests specifically for the Period 3 pumping sign convention issue
"""

import sys
import os

# Add current directory to Python path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from gspy_interface import run_modflow_step, reset_state

def test_wel_sign_convention():
    """Test that Period 3 pumping uses correct negative sign (pumping, not injection)"""
    
    print("=" * 80)
    print("WEL PACKAGE SIGN CONVENTION DIAGNOSTIC TEST")
    print("Testing Period 3 pumping: -500.0 m³/day should be PUMPING (negative)")
    print("=" * 80)
    
    # Reset state for clean test
    reset_state()
    
    # Test parameters - Period 3 with pumping
    tutorial_period = 3
    well_rate_m3_per_day = -500.0  # NEGATIVE = PUMPING
    hk = 10.0
    sy = 0.3
    
    print(f"\nTest Parameters:")
    print(f"  tutorial_period = {tutorial_period}")
    print(f"  well_rate_m3_per_day = {well_rate_m3_per_day:.1f} m³/day (PUMPING)")
    print(f"  hk = {hk:.1f} m/day")
    print(f"  sy = {sy:.1f}")
    
    print(f"\nExpected Behavior:")
    print(f"  ✓ WEL package should use exactly -500.0 m³/day")
    print(f"  ✓ Center cell head should DECREASE (drawdown)")
    print(f"  ✓ Log should show 'center well = -500.0 m³/day'")
    
    try:
        print(f"\nRunning Period 3 simulation with pumping...")
        result = run_modflow_step(tutorial_period, well_rate_m3_per_day, hk, sy)
        center_head = result[0]
        
        print(f"\n{'='*50}")
        print(f"RESULTS:")
        print(f"  Center Head = {center_head:.6f} m")
        print(f"{'='*50}")
        
        # Now test injection for comparison
        print(f"\nTesting INJECTION (+500.0) for comparison...")
        well_rate_injection = +500.0  # POSITIVE = INJECTION
        result_injection = run_modflow_step(tutorial_period, well_rate_injection, hk, sy)
        center_head_injection = result_injection[0]
        
        print(f"  Injection Head = {center_head_injection:.6f} m")
        
        # Compare results
        head_difference = center_head_injection - center_head
        print(f"\nCOMPARISON:")
        print(f"  Head difference (Injection - Pumping) = {head_difference:.6f} m")
        
        if head_difference > 0.001:
            print(f"  ✓ CORRECT: Injection head > Pumping head (as expected)")
            print(f"  ✓ Sign convention appears correct")
        else:
            print(f"  ✗ ERROR: No clear difference between injection and pumping")
            print(f"  ✗ Possible sign convention error!")
            
        # Test baseline (no pumping)
        print(f"\nTesting BASELINE (no pumping) for reference...")
        well_rate_none = 0.0
        result_none = run_modflow_step(tutorial_period, well_rate_none, hk, sy)
        center_head_none = result_none[0]
        
        print(f"  No pumping Head = {center_head_none:.6f} m")
        
        print(f"\nFULL COMPARISON:")
        print(f"  Injection (+500):  {center_head_injection:.6f} m")
        print(f"  No pumping (0):    {center_head_none:.6f} m") 
        print(f"  Pumping (-500):    {center_head:.6f} m")
        
        if center_head_injection > center_head_none > center_head:
            print(f"  ✓ CORRECT ORDER: Injection > Baseline > Pumping")
        else:
            print(f"  ✗ INCORRECT ORDER: Possible sign error!")
            
    except Exception as e:
        print(f"ERROR: {str(e)}")
        return False
    
    return True

def check_modflow_input_files():
    """Check the actual MODFLOW input files for WEL package data"""
    
    print(f"\n{'='*80}")
    print("CHECKING MODFLOW INPUT FILES")
    print("=" * 80)
    
    # Look for .wel file (WEL package input)
    model_files = [
        'gspy_tutorial2.wel',
        'gspy_tutorial2.nam',
        'gspy_tutorial2.list'
    ]
    
    for filename in model_files:
        filepath = os.path.join(os.getcwd(), filename)
        if os.path.exists(filepath):
            print(f"\n📁 Found: {filename}")
            try:
                with open(filepath, 'r') as f:
                    content = f.read()
                    if '.wel' in filename.lower():
                        print("WEL file content:")
                        print(content)
                    elif '.nam' in filename.lower():
                        print("NAM file excerpt (looking for WEL):")
                        lines = content.split('\n')
                        for line in lines:
                            if 'wel' in line.lower():
                                print(f"  {line}")
                    elif '.list' in filename.lower():
                        print("LIST file excerpt (looking for WEL):")
                        lines = content.split('\n')
                        for i, line in enumerate(lines):
                            if 'wel' in line.lower() or 'well' in line.lower():
                                # Print context around WEL mentions
                                start = max(0, i-2)
                                end = min(len(lines), i+3)
                                for j in range(start, end):
                                    marker = ">>> " if j == i else "    "
                                    print(f"  {marker}{lines[j]}")
                                print()
            except Exception as e:
                print(f"  Error reading {filename}: {e}")
        else:
            print(f"❌ Not found: {filename}")

if __name__ == "__main__":
    print("Running WEL package sign convention diagnostic...")
    success = test_wel_sign_convention()
    check_modflow_input_files()
    
    if success:
        print(f"\n🎯 DIAGNOSTIC COMPLETE")
    else:
        print(f"\n❌ DIAGNOSTIC FAILED")
        sys.exit(1)