#!/usr/bin/env python3
"""
Basic usage examples for CAVORA.
"""

import numpy as np
from cavora.core import VanDerPolOscillator, CoupledVLFOscillator
from cavora.core import LimitCycleDetector, StabilityEnvelopeCalculator
from cavora.parameters import VerticalPassage, LateralConduit, FlowstoneDeposition
from cavora.cdz import CDZDetector
from cavora.prediction import FloodForecasting
from cavora.visualization import TimeSeriesPlots


def example_1_single_oscillator():
    """Example 1: Simulate single Van der Pol oscillator."""
    print("\n" + "="*60)
    print("Example 1: Single Van der Pol Oscillator")
    print("="*60)
    
    # Create oscillator
    vdp = VanDerPolOscillator(mu=0.15, omega0=0.05)
    
    # Simulate
    t_span = (0, 200)
    y0 = (0.5, 0.0)
    t_eval = np.linspace(0, 200, 1000)
    
    result = vdp.simulate(t_span, y0, t_eval=t_eval)
    
    print(f"Limit Cycle Amplitude: {vdp.get_limit_cycle_amplitude():.3f}")
    print(f"Limit Cycle Period: {vdp.get_limit_cycle_period():.1f} years")
    print(f"Final V: {result['V'][-1]:.3f} m")
    
    return result


def example_2_coupled_vlf():
    """Example 2: Simulate coupled VLF system."""
    print("\n" + "="*60)
    print("Example 2: Coupled VLF System")
    print("="*60)
    
    # Create coupled oscillator with default parameters from paper
    coupled = CoupledVLFOscillator()
    
    # Initial conditions (typical stable passage)
    y0 = (2.5, 3.0, 0.08)
    t_span = (0, 50)
    t_eval = np.linspace(0, 50, 500)
    
    result = coupled.simulate(t_span, y0, t_eval=t_eval)
    
    print(f"Final state after 50 years:")
    print(f"  V: {result['V'][-1]:.2f} m")
    print(f"  L: {result['L'][-1]:.2f} m")
    print(f"  F: {result['F'][-1]:.3f} mm")
    
    # Check stability
    stability = coupled.get_stability_envelope((result['V'][-1], result['L'][-1], result['F'][-1]))
    print(f"\nStability Assessment:")
    print(f"  Score: {stability['score']}/100")
    print(f"  Level: {stability['color']} {stability['level']}")
    print(f"  Action: {stability['action']}")
    
    return result


def example_3_limit_cycle_detection():
    """Example 3: Detect limit cycles in time series."""
    print("\n" + "="*60)
    print("Example 3: Limit Cycle Detection")
    print("="*60)
    
    # Generate sample data with limit cycle
    t = np.linspace(0, 50, 1000)
    # Limit cycle with noise
    V = 2.0 + 0.5 * np.sin(2 * np.pi * 0.05 * t) + 0.1 * np.random.randn(len(t))
    
    # Create detector
    detector = LimitCycleDetector()
    
    # Detect limit cycle
    result = detector.detect_from_trajectory(t, V)
    
    print(f"Limit Cycle Detected: {result['detected']}")
    print(f"Confidence: {result['confidence']:.1%}")
    print(f"Correlation Dimension: {result['correlation_dimension']:.3f}")
    
    if result['properties']:
        props = result['properties']
        print(f"\nLimit Cycle Properties:")
        print(f"  Amplitude: {props['amplitude']:.3f} m")
        print(f"  Period: {props['period']:.1f} years")
    
    return result


def example_4_vertical_passage_analysis():
    """Example 4: Analyze vertical passage measurements."""
    print("\n" + "="*60)
    print("Example 4: Vertical Passage Analysis")
    print("="*60)
    
    # Create vertical passage analyzer
    vp = VerticalPassage(alpha0=2.5)
    
    # Add measurements
    vp.add_measurement(2.8, 5.0, 2021.5, "V-001")
    vp.add_measurement(2.9, 6.0, 2022.5, "V-002")
    vp.add_measurement(3.1, 4.0, 2023.5, "V-003")
    
    # Calculate structural integrity
    integrity = vp.calculate_structural_integrity()
    print(f"Structural Integrity:")
    print(f"  Score: {integrity['score']}/100")
    print(f"  Assessment: {integrity['assessment']}")
    
    # Predict ceiling stability
    stability = vp.predict_ceiling_stability(span=3.5)
    print(f"\nCeiling Stability:")
    print(f"  Status: {stability['status']}")
    print(f"  Safety Factor: {stability['safety_factor']}")
    
    return vp


def example_5_lateral_conduit_analysis():
    """Example 5: Analyze lateral conduit measurements."""
    print("\n" + "="*60)
    print("Example 5: Lateral Conduit Analysis")
    print("="*60)
    
    # Create lateral conduit analyzer
    lc = LateralConduit(beta0=3.0)
    
    # Add measurements
    lc.add_measurement(3.2, 0.15, 0.45, 2021.5, "L-001")
    lc.add_measurement(3.4, 0.22, 0.62, 2022.5, "L-002")
    lc.add_measurement(3.6, 0.35, 0.85, 2023.5, "L-003")
    
    # Calculate adaptation score
    score = lc.calculate_adaptation_score()
    print(f"Adaptation Score:")
    print(f"  Score: {score['score']}/100")
    print(f"  Assessment: {score['assessment']}")
    
    # Analyze flood response
    flood = lc.analyze_flood_response(flood_peak_discharge=5.2)
    print(f"\nFlood Response:")
    print(f"  Peak Width: {flood['peak_width']} m")
    print(f"  Stabilized Width: {flood['stabilized_width']} m")
    
    return lc


def example_6_flowstone_analysis():
    """Example 6: Analyze flowstone deposition."""
    print("\n" + "="*60)
    print("Example 6: Flowstone Deposition Analysis")
    print("="*60)
    
    # Create flowstone analyzer
    fd = FlowstoneDeposition(F0=0.5)
    
    # Add measurements
    fd.add_measurement(2.5, 0.087, 15, 2015.5, "F-001")
    fd.add_measurement(3.2, 0.085, 18, 2020.5, "F-002")
    fd.add_measurement(3.8, 0.082, 21, 2024.5, "F-003")
    
    # Analyze deposition rate
    rates = fd.analyze_deposition_rate()
    print(f"Deposition Rate Analysis:")
    print(f"  Mean Rate: {rates['mean_rate']} mm/yr")
    print(f"  Trend: {rates['trend']}")
    
    # Detect climate signal
    climate = fd.detect_climate_signal()
    print(f"\nClimate Signal:")
    print(f"  {climate['trend_interpretation']}")
    
    # Predict future
    prediction = fd.predict_future_deposition(years_ahead=25, scenario='warming')
    print(f"\nFuture Prediction (25 years):")
    print(f"  Final Rate: {prediction['final_rate']} mm/yr")
    print(f"  Rate Reduction: {prediction['rate_reduction']}%")
    
    return fd


def example_7_cdz_detection():
    """Example 7: Detect Creative Dissolution Zones."""
    print("\n" + "="*60)
    print("Example 7: CDZ Detection")
    print("="*60)
    
    # Generate sample data with CDZ
    t = np.linspace(0, 10, 1000)
    V = 2.5 + 0.2 * np.sin(2 * np.pi * 0.5 * t)
    # Add CDZ at t=5
    cdz_region = (t > 4.5) & (t < 5.5)
    V[cdz_region] += 1.5 * np.exp(-((t[cdz_region] - 5)**2) / 0.1)
    
    # Create detector
    detector = CDZDetector()
    
    # Detect CDZs
    cdzs = detector.detect_from_trajectory(t, V, location="Test Passage")
    
    print(f"Detected CDZs: {len(cdzs)}")
    for i, cdz in enumerate(cdzs):
        print(f"\nCDZ {i+1}:")
        print(f"  Period: {cdz['start_time']:.2f} - {cdz['end_time']:.2f} years")
        print(f"  Duration: {cdz['duration']:.2f} years")
        print(f"  Peak Divergence: {cdz['peak_divergence']:.2f}σ")
        print(f"  Confidence: {cdz['confidence']:.0%}")
    
    return cdzs


def example_8_flood_forecasting():
    """Example 8: Forecast flood events."""
    print("\n" + "="*60)
    print("Example 8: Flood Forecasting")
    print("="*60)
    
    # Create flood forecaster
    ff = FloodForecasting()
    
    # Precipitation events (from Vikos Gorge example)
    precipitation = [
        {'time': 0, 'amount': 25},
        {'time': 6, 'amount': 40},
        {'time': 12, 'amount': 15}
    ]
    
    # Generate forecast
    forecast = ff.forecast_from_precipitation(
        precipitation,
        current_discharge=0.15,
        current_level=0.45,
        soil_saturation=0.65
    )
    
    print(f"Flood Forecast:")
    print(f"  Severity: {forecast.severity}")
    print(f"  Peak Discharge: {forecast.peak_discharge} m³/s")
    print(f"  Time to Peak: {forecast.time_to_peak} hours")
    print(f"  Duration: {forecast.duration} hours")
    print(f"  Probability: {forecast.probability:.0%}")
    
    # Evacuation timing
    timing = ff.get_evacuation_timing(forecast, exit_time=2.0)
    print(f"\nEvacuation Timing:")
    print(f"  Action: {timing['action']}")
    print(f"  Time Available: {timing['time_available_hours']} hours")
    
    return forecast


def example_9_stability_envelope():
    """Example 9: Calculate stability envelope."""
    print("\n" + "="*60)
    print("Example 9: Stability Envelope")
    print("="*60)
    
    from cavora.parameters import PassageState
    from cavora.prediction import StabilityEnvelopePredictor
    
    # Create state (from Vikos Gorge)
    state = PassageState(V=2.8, L=3.2, F=0.087, Q=0.15, CO2=850)
    
    # Create predictor
    predictor = StabilityEnvelopePredictor()
    
    # Predict envelope
    envelope = predictor.predict_envelope((state.V, state.L, state.F), time_horizon=2.0)
    
    print(f"Stability Envelope (2 years):")
    print(f"  V: [{envelope.v_min:.2f}, {envelope.v_max:.2f}] m")
    print(f"  L: [{envelope.l_min:.2f}, {envelope.l_max:.2f}] m")
    print(f"  F: [{envelope.f_min:.3f}, {envelope.f_max:.3f}] mm")
    print(f"  Probability: {envelope.probability:.0%}")
    
    return envelope


def example_10_complete_workflow():
    """Example 10: Complete workflow from data to report."""
    print("\n" + "="*60)
    print("Example 10: Complete Workflow")
    print("="*60)
    
    # 1. Load/input survey data
    print("\n1. Survey Data:")
    survey_data = {
        'station': 'GAMMA-7',
        'V': 2.8,  # m
        'L': 3.2,  # m
        'F': 0.087,  # mm
        'Q': 0.15,  # m³/s
        'CO2': 850,  # ppm
        'water_level': 0.45,  # m
        'temperature': 11.2,  # °C
        'humidity': 98.5,  # %
    }
    print(f"  Station: {survey_data['station']}")
    print(f"  V = {survey_data['V']} m")
    print(f"  L = {survey_data['L']} m")
    print(f"  F = {survey_data['F']} mm")
    
    # 2. Analyze stability
    print("\n2. Stability Analysis:")
    from cavora.prediction import StabilityEnvelopePredictor
    from cavora.parameters import PassageState
    
    state = PassageState(**survey_data)
    predictor = StabilityEnvelopePredictor()
    envelope = predictor.predict_envelope((state.V, state.L, state.F), 1.0)
    
    print(f"  Stability Score: {envelope.probability*100:.1f}/100")
    print(f"  CDZ Proximity: {1-envelope.probability:.2%}")
    
    # 3. Check flood risk
    print("\n3. Flood Risk Assessment:")
    ff = FloodForecasting()
    
    # Check current conditions
    if state.Q < 0.5:
        risk = "SAFE"
        color = "🟢"
    elif state.Q < 2.0:
        risk = "CAUTION"
        color = "🟡"
    elif state.Q < 5.0:
        risk = "HIGH RISK"
        color = "🔴"
    else:
        risk = "CRITICAL"
        color = "⚫"
    
    print(f"  Current Discharge: {state.Q} m³/s - {color} {risk}")
    
    # 4. Generate recommendations
    print("\n4. Recommendations:")
    if envelope.probability > 0.8:
        print("  ✅ Standard Survey Mode")
        print("  • Normal documentation interval (5m)")
        print("  • Team size: 2-3")
    elif envelope.probability > 0.6:
        print("  ⚠️ Enhanced Monitoring Mode")
        print("  • Increased measurement frequency (2m)")
        print("  • Deploy additional sensors")
        print("  • Team size: 3-4")
    elif envelope.probability > 0.4:
        print("  🚨 CDZ Active Mode")
        print("  • Maximum documentation (0.5m)")
        print("  • Continuous monitoring")
        print("  • Team size: 5-6")
    else:
        print("  ⚠️ HIGH RISK - Consider evacuation")
    
    # 5. Summary
    print("\n" + "-"*40)
    print("SUMMARY")
    print("-"*40)
    print(f"Location: {survey_data['station']}")
    print(f"Stability: {envelope.probability*100:.1f}/100")
    print(f"Flood Risk: {risk}")
    print(f"Recommended Protocol: {'Tier 1' if envelope.probability>0.8 else 'Tier 2' if envelope.probability>0.6 else 'Tier 3'}")
    
    return survey_data


if __name__ == "__main__":
    print("="*60)
    print("CAVORA - Basic Usage Examples")
    print("="*60)
    
    # Run examples
    example_1_single_oscillator()
    example_2_coupled_vlf()
    example_3_limit_cycle_detection()
    example_4_vertical_passage_analysis()
    example_5_lateral_conduit_analysis()
    example_6_flowstone_analysis()
    example_7_cdz_detection()
    example_8_flood_forecasting()
    example_9_stability_envelope()
    example_10_complete_workflow()
    
    print("\n" + "="*60)
    print("All examples completed successfully!")
    print("="*60)
