#!/usr/bin/env python3
"""
Energy Harvesting Analysis Example

This example analyzes piezoelectric energy harvesting potential
from various pressure fluctuation sources in the hadal zone.
"""

import numpy as np
import matplotlib.pyplot as plt
from src.energy.piezo_harvester import PiezoHarvester
from src.sensing.pressure_sensing import PressureSensing


def main():
    """Run energy harvesting analysis"""
    print("=" * 60)
    print("HADEX - Energy Harvesting Analysis")
    print("=" * 60)
    
    # 1. Initialize harvester
    harvester = PiezoHarvester(material="PZT-5H", area=10)
    print(f"\nHarvester: {harvester.material}, {harvester.area} cm²")
    
    # 2. Analyze different pressure sources
    print("\n1. Pressure Source Analysis")
    print("-" * 40)
    
    sources = [
        {"name": "Turbidity Current", "stress": 2000, "freq": 0.05},
        {"name": "Seismic Microseism", "stress": 87, "freq": 0.2},
        {"name": "Current Turbulence", "stress": 23, "freq": 1.5},
        {"name": "Biological Activity", "stress": 8, "freq": 8.0}
    ]
    
    print(f"{'Source':20} {'Stress (Pa)':12} {'Freq (Hz)':10} {'Power (mW)':12}")
    print("-" * 55)
    
    for source in sources:
        power = harvester.calculate_power(
            stress=source["stress"],
            frequency=source["freq"]
        ) * 1000  # Convert to mW
        
        print(f"{source['name']:20} {source['stress']:12} "
              f"{source['freq']:10.2f} {power:12.2f}")
    
    # 3. Frequency response analysis
    print("\n2. Frequency Response Analysis")
    print("-" * 40)
    
    frequencies = np.logspace(-2, 1, 50)
    powers = []
    
    for f in frequencies:
        power = harvester.calculate_power(stress=1000, frequency=f) * 1000
        powers.append(power)
    
    # Find optimal frequency
    opt_idx = np.argmax(powers)
    opt_freq = frequencies[opt_idx]
    opt_power = powers[opt_idx]
    
    print(f"Optimal frequency: {opt_freq:.2f} Hz")
    print(f"Max power at 1 kPa: {opt_power:.2f} mW")
    
    # Plot frequency response
    plt.figure(figsize=(10, 6))
    plt.semilogx(frequencies, powers, 'b-', linewidth=2)
    plt.plot(opt_freq, opt_power, 'ro', markersize=10, 
             label=f'Optimal: {opt_freq:.2f} Hz')
    plt.grid(True, alpha=0.3)
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Power Output (mW)')
    plt.title('Piezoelectric Harvester Frequency Response')
    plt.legend()
    plt.savefig('frequency_response.png', dpi=150)
    print("\nFrequency response plot saved to: frequency_response.png")
    
    # 4. Area scaling analysis
    print("\n3. Area Scaling Analysis")
    print("-" * 40)
    
    areas = [1, 2, 5, 10, 20, 50, 100]  # cm²
    area_powers = []
    
    for area in areas:
        h = PiezoHarvester(material="PZT-5H", area=area)
        power = h.calculate_power(stress=2000, frequency=0.05) * 1000
        area_powers.append(power)
    
    print(f"{'Area (cm²)':12} {'Power (mW)':12}")
    print("-" * 25)
    
    for area, power in zip(areas, area_powers):
        print(f"{area:12} {power:12.2f}")
    
    # 5. Long-term energy estimation
    print("\n4. Long-term Energy Harvesting")
    print("-" * 40)
    
    durations = [1, 7, 30, 365]  # days
    
    print(f"{'Duration (days)':16} {'Energy (Wh)':12} {'Battery Cycles':18}")
    print("-" * 48)
    
    battery_capacity = 180  # Wh
    
    for days in durations:
        energy = harvester.estimate_harvestable_energy(
            duration_days=days,
            duty_cycle=0.8
        )
        cycles = energy / battery_capacity
        
        print(f"{days:16} {energy:12.2f} {cycles:18.2f}")
    
    # 6. Material comparison
    print("\n5. Material Comparison")
    print("-" * 40)
    
    materials = [
        {"name": "PZT-5H", "d33": 650},
        {"name": "PZT-5A", "d33": 374},
        {"name": "PZT-4", "d33": 289},
        {"name": "BaTiO3", "d33": 190},
        {"name": "PVDF", "d33": 30}
    ]
    
    print(f"{'Material':12} {'d33 (pC/N)':12} {'Power (mW)':12}")
    print("-" * 38)
    
    for mat in materials:
        h = PiezoHarvester(material=mat["name"], area=10, d33=mat["d33"])
        power = h.calculate_power(stress=2000, frequency=0.05) * 1000
        print(f"{mat['name']:12} {mat['d33']:12} {power:12.2f}")
    
    # 7. Realistic simulation with pressure sensor
    print("\n6. Realistic Pressure Fluctuation Simulation")
    print("-" * 40)
    
    pressure_sensor = PressureSensing(sample_rate=10)
    readings = pressure_sensor.measure(depth=10911, duration=3600)  # 1 hour
    
    # Extract pressure values
    pressures = np.array([r.pressure for r in readings])
    time = np.array([r.timestamp for r in readings])
    
    # Convert pressure to stress (simplified)
    stress = (pressures - np.mean(pressures)) * 1e6  # MPa to Pa
    
    # Calculate instantaneous power
    instant_power = []
    for s in stress:
        # Use dominant frequency from spectrum
        p = harvester.calculate_power(stress=abs(s), frequency=0.1) * 1000
        instant_power.append(p)
    
    avg_power = np.mean(instant_power)
    peak_power = np.max(instant_power)
    
    print(f"Average power from realistic fluctuations: {avg_power:.2f} mW")
    print(f"Peak power: {peak_power:.2f} mW")
    
    # Plot time series
    plt.figure(figsize=(12, 8))
    
    plt.subplot(2, 1, 1)
    plt.plot(time[:600], stress[:600], 'b-', linewidth=1)  # First 10 minutes
    plt.ylabel('Stress (Pa)')
    plt.title('Pressure Fluctuations (First 10 minutes)')
    plt.grid(True, alpha=0.3)
    
    plt.subplot(2, 1, 2)
    plt.plot(time[:600], instant_power[:600], 'g-', linewidth=1)
    plt.xlabel('Time (s)')
    plt.ylabel('Power (mW)')
    plt.title('Instantaneous Harvested Power')
    plt.grid(True, alpha=0.3)
    
    plt.tight_layout()
    plt.savefig('realistic_harvesting.png', dpi=150)
    print("Realistic harvesting plot saved to: realistic_harvesting.png")
    
    print("\n" + "=" * 60)
    print("Energy harvesting analysis completed!")
    print("=" * 60)


if __name__ == "__main__":
    main()
