"""
Tests for Energy modules
"""

import pytest
import numpy as np
from src.energy.piezo_harvester import PiezoHarvester
from src.energy.energy_storage import EnergyStorage, StorageType


class TestPiezoHarvester:
    """Test suite for PiezoHarvester"""
    
    def test_initialization(self):
        """Test initialization"""
        harvester = PiezoHarvester(material="PZT-5H", area=10)
        assert harvester.material == "PZT-5H"
        assert harvester.area == 10
    
    def test_calculate_power(self):
        """Test power calculation"""
        harvester = PiezoHarvester(area=10)
        
        # Calculate power
        power = harvester.calculate_power(stress=2000, frequency=0.05)
        
        # Power should be positive and reasonable
        assert power > 0
        assert power < 1  # Less than 1 W
    
    def test_measure_power(self):
        """Test power measurement"""
        harvester = PiezoHarvester(area=10)
        stats = harvester.measure_power(duration=3600)
        
        assert stats.continuous_power > 0
        assert stats.peak_power > 0
    
    def test_estimate_harvestable_energy(self):
        """Test energy estimation"""
        harvester = PiezoHarvester()
        energy = harvester.estimate_harvestable_energy(duration_days=10)
        assert energy > 0


class TestEnergyStorage:
    """Test suite for EnergyStorage"""
    
    def test_initialization(self):
        """Test initialization"""
        storage = EnergyStorage(battery_capacity=180)
        assert storage.battery_capacity == 180
    
    def test_state_of_charge(self):
        """Test state of charge"""
        storage = EnergyStorage()
        soc = storage.state_of_charge()
        assert soc == 100
    
    def test_manage_power_charging(self):
        """Test power management - charging"""
        storage = EnergyStorage()
        
        initial_soc = storage.battery_soc
        storage.manage_power(harvested_power=0.01, load_power=0.005)
        
        # SOC should increase or stay the same
        assert storage.battery_soc >= initial_soc
    
    def test_manage_power_discharging(self):
        """Test power management - discharging"""
        storage = EnergyStorage()
        
        initial_soc = storage.battery_soc
        storage.manage_power(harvested_power=0.001, load_power=0.01)
        
        # SOC should decrease
        assert storage.battery_soc <= initial_soc
    
    def test_buffer_fluctuations(self):
        """Test power smoothing"""
        storage = EnergyStorage()
        
        input_power = [1, 2, 1, 10, 1, 2, 1]
        smoothed = storage.buffer_fluctuations(input_power)
        
        assert len(smoothed) == len(input_power)
    
    def test_estimate_endurance(self):
        """Test endurance estimation"""
        storage = EnergyStorage(battery_capacity=180)
        endurance = storage.estimate_endurance(avg_power_consumption=2.5)
        assert endurance > 0
