"""
GSPy-MODFLOW Interface - Main Entry Point
FloPy Tutorial 2 Benchmark Model for GoldSim coupling
"""

import os
import time
from groundwater_models import GroundwaterCalculator

try:
    import gspy
    GSPy_AVAILABLE = True
except ImportError:
    GSPy_AVAILABLE = False

# Track simulation state for reset detection
_last_call_time = 0
_last_period_called = None
_call_counter = 0


def debug_log(message, level=2):
    """Enhanced logging with fallback"""
    if GSPy_AVAILABLE:
        gspy.log(message, level)
    else:
        print(f"DEBUG: {message}")


def run_modflow_step(*args):
    """
    GSPy entry point for FloPy Tutorial 2 Benchmark Model
    
    Args:
        args[0]: tutorial_period (int) - 1 (Day 1), 2 (Days 2-101), or 3 (Days 102-201)
        args[1]: well_rate_m3_per_day (float) - Well pumping rate (-500.0 for Period 3, 0.0 otherwise)
        args[2]: hk (float) - Hydraulic Conductivity (must be 10.0 m/day)
        args[3]: sy (float) - Specific Yield (must be 0.3)
        
    Returns:
        tuple: (Center_Cell_Head,) - Head at center cell (0,4,4) in meters
    """
    global _last_call_time, _last_period_called, _call_counter
    
    _call_counter += 1
    
    try:
        # Enhanced input parameter logging
        debug_log("=" * 60, 2)
        debug_log(f"GOLDSIM CALL #{_call_counter} - DIAGNOSTIC ANALYSIS", 2)
        debug_log("=" * 60, 2)
        
        tutorial_period = int(args[0])
        well_rate = float(args[1])
        hk = float(args[2])
        sy = float(args[3])
        
        debug_log(f"Input Parameters:", 2)
        debug_log(f"  - tutorial_period: {tutorial_period}", 3)
        debug_log(f"  - well_rate_m3_per_day: {well_rate}", 3)
        debug_log(f"  - hydraulic_conductivity: {hk} m/day", 3)
        debug_log(f"  - specific_yield: {sy}", 3)
        
        current_time = time.time()
        time_gap = current_time - _last_call_time
        debug_log(f"Timing Analysis:", 3)
        debug_log(f"  - Time since last call: {time_gap:.2f} seconds", 3)
        debug_log(f"  - Last period called: {_last_period_called}", 3)
        
        # Detect new GoldSim simulation: Period 1 calls that indicate simulation start
        # 1. Period 1 after time gap (GoldSim restart)
        # 2. Period 1 after Period 3 (simulation cycle restart)
        # 3. First Period 1 call ever (module initialization)
        is_new_simulation = (
            tutorial_period == 1 and 
            (current_time - _last_call_time > 10 or 
             _last_period_called == 3 or 
             _last_period_called is None)
        )
        
        debug_log(f"Reset Detection:", 2)
        debug_log(f"  - Is new simulation: {is_new_simulation}", 3)
        debug_log(f"  - Reset criteria: Period={tutorial_period}, Gap>{time_gap:.1f}s, Last={_last_period_called}", 3)
        
        if is_new_simulation:
            debug_log("*** RESET TRIGGERED: Starting fresh Tutorial 2 simulation ***", 2)
            from state_manager import StateManager
            # Create a simple logger object for StateManager
            class SimpleLogger:
                def log(self, message, level=2):
                    debug_log(message, level)
            
            simple_logger = SimpleLogger()
            state_mgr = StateManager(simple_logger)
            state_mgr.reset_state()
            debug_log("State reset completed - should start with 10.0m initial heads", 2)
        else:
            debug_log("Using persistent state from previous call", 2)
        
        # Check state file before calculation
        state_file = "modflow_state.pkl"
        if os.path.exists(state_file):
            debug_log(f"State file exists: {state_file}", 3)
            file_size = os.path.getsize(state_file)
            file_time = os.path.getmtime(state_file)
            debug_log(f"  - File size: {file_size} bytes", 3)
            debug_log(f"  - Last modified: {time.ctime(file_time)}", 3)
        else:
            debug_log("No state file found - will use default initial conditions", 1)
        
        _last_call_time = current_time
        _last_period_called = tutorial_period
        
        debug_log("Calling GroundwaterCalculator...", 2)
        calculator = GroundwaterCalculator()
        center_head = calculator.calculate_tutorial_head(*args)
        
        debug_log(f"RESULT ANALYSIS:", 2)
        debug_log(f"  - Center cell head: {center_head:.6f} m", 2)
        
        # Compare with expected Tutorial 2 values
        if tutorial_period == 1:
            expected = 10.0
            if abs(center_head - expected) < 0.001:
                debug_log(f"✓ EXPECTED: Period 1 head ~{expected:.1f}m", 2)
            else:
                debug_log(f"⚠ UNEXPECTED: Period 1 head {center_head:.6f}m (expected ~{expected:.1f}m)", 1)
        elif tutorial_period == 2:
            if 9.0 < center_head < 11.0:
                debug_log(f"✓ REASONABLE: Period 2 head in expected range", 2)
            else:
                debug_log(f"⚠ UNUSUAL: Period 2 head {center_head:.6f}m outside expected range", 1)
        elif tutorial_period == 3:
            if 8.0 < center_head < 11.0:
                debug_log(f"✓ REASONABLE: Period 3 head in expected range", 2)
            else:
                debug_log(f"⚠ UNUSUAL: Period 3 head {center_head:.6f}m outside expected range", 1)
        
        debug_log(f"Call #{_call_counter} completed successfully", 2)
        debug_log("=" * 60, 2)
        
        return (center_head,)
        
    except Exception as e:
        debug_log(f"ERROR in run_modflow_step: {str(e)}", 0)
        debug_log("Returning safe fallback value: 10.0m", 1)
        return (10.0,)


def process_data(*args):
    """Alternative GSPy entry point"""
    return run_modflow_step(*args)


def main(*args):
    """Alternative GSPy entry point"""
    return run_modflow_step(*args)


def reset_state():
    """Reset persistent groundwater state - useful for testing"""
    try:
        calculator = GroundwaterCalculator()
        calculator.reset_state()
    except Exception:
        pass


# Test functionality if run directly
if __name__ == "__main__":
    print("GSPy-MODFLOW interface loaded successfully")
    
    # Test with target recharge
    test_recharge = 0.075  # m/day
    result = run_modflow_step(test_recharge, 0.3, 0.5, 0.1, 10.0, 0.15, 500.0)
    print(f"Test: {test_recharge} m/day → {result[0]:.6f} m³/s")