#!/usr/bin/env python3
"""
Challenger Deep Mission Simulation

This example simulates a 72-hour swarm mission to the Challenger Deep,
the deepest point on Earth at 10,911 meters.
"""

import numpy as np
import argparse
import time
from src.core.fluid_properties import FluidProperties
from src.navigation.swarm_algorithm import SwarmNavigationEngine
from src.sensing.oxygen_flux import OxygenFlux
from src.sensing.bioluminescence import BioluminescenceDetector
from src.sensing.pressure_sensing import PressureSensing
from src.energy.piezo_harvester import PiezoHarvester
from src.energy.energy_storage import EnergyStorage
from src.utils.visualization import Visualization
from src.utils.logging import MissionLogger


def parse_args():
    """Parse command line arguments"""
    parser = argparse.ArgumentParser(description='Challenger Deep Mission Simulation')
    parser.add_argument('--duration', type=float, default=72,
                       help='Mission duration in hours')
    parser.add_argument('--num_vehicles', type=int, default=12,
                       help='Number of vehicles in swarm')
    parser.add_argument('--survey_area', type=float, default=500,
                       help='Survey area size in meters')
    parser.add_argument('--output', type=str, default='results/mission.json',
                       help='Output file path')
    return parser.parse_args()


def main():
    """Run Challenger Deep mission simulation"""
    args = parse_args()
    
    # Initialize mission logger
    logger = MissionLogger(
        mission_name=f"challenger_deep_{int(time.time())}",
        log_level="INFO"
    )
    
    logger.info("=" * 60)
    logger.info("CHALLENGER DEEP MISSION SIMULATION")
    logger.info("=" * 60)
    logger.info(f"Duration: {args.duration} hours")
    logger.info(f"Vehicles: {args.num_vehicles}")
    logger.info(f"Survey Area: {args.survey_area} m")
    
    # Mission parameters
    depth = 10911  # meters
    temperature = 1.9  # °C
    salinity = 34.68  # PSU
    
    # 1. Initialize fluid properties
    logger.info("\n1. Initializing fluid properties...")
    props = FluidProperties(
        temperature=temperature,
        salinity=salinity,
        depth=depth
    )
    logger.info(f"   Density: {props.density:.1f} kg/m³")
    logger.info(f"   Sound Velocity: {props.sound_speed:.1f} m/s")
    logger.info(f"   Pressure: {props.pressure:.2f} MPa")
    
    # 2. Initialize swarm
    logger.info("\n2. Initializing swarm navigation...")
    swarm = SwarmNavigationEngine(
        num_vehicles=args.num_vehicles,
        acoustic_frequency=12000,
        max_range=500,
        update_rate=30
    )
    logger.info(f"   Swarm initialized with {args.num_vehicles} vehicles")
    
    # 3. Initialize sensors
    logger.info("\n3. Initializing sensor suite...")
    oxygen_sensor = OxygenFlux()
    bio_detector = BioluminescenceDetector()
    pressure_sensor = PressureSensing()
    logger.info("   Sensors: Oxygen, Bioluminescence, Pressure")
    
    # 4. Initialize energy systems
    logger.info("\n4. Initializing energy systems...")
    harvester = PiezoHarvester(material="PZT-5H", area=10)
    storage = EnergyStorage(battery_capacity=180)
    logger.info(f"   Harvester: {harvester.material}, {harvester.area} cm²")
    logger.info(f"   Battery: {storage.battery_capacity} Wh")
    
    # 5. Run mission simulation
    logger.info("\n5. Running mission simulation...")
    logger.info(f"   Duration: {args.duration} hours")
    logger.info(f"   Depth: {depth} m")
    
    # Simulate swarm mission
    nav_results = swarm.simulate_mission(
        duration_hours=args.duration,
        depth=depth,
        survey_area=args.survey_area
    )
    
    logger.info(f"\n   Navigation Results:")
    logger.info(f"   - RMS Error: {nav_results['rms_error']:.2f} m")
    logger.info(f"   - Max Error: {nav_results['max_error']:.2f} m")
    logger.info(f"   - Improvement Factor: {nav_results['improvement_factor']:.1f}x")
    
    # Simulate sensor measurements
    logger.info("\n6. Collecting sensor data...")
    
    # Oxygen measurements
    oxygen_profile = oxygen_sensor.measure_profile()
    logger.info(f"   Oxygen penetration depth: {oxygen_profile.penetration_depth:.2f} cm")
    
    # Bioluminescence measurements
    bio_events = bio_detector.measure(duration=args.duration * 3600)
    logger.info(f"   Bioluminescence events: {len(bio_events)}")
    
    if bio_events:
        wavelengths = [e.wavelength for e in bio_events]
        logger.info(f"   Peak wavelength: {np.mean(wavelengths):.1f} nm")
    
    # Pressure measurements
    pressure_readings = pressure_sensor.measure(depth=depth, duration=3600)
    fluctuations = pressure_sensor.detect_oscillations(pressure_readings)
    logger.info(f"   Pressure fluctuations detected: {len(fluctuations)}")
    
    # Energy harvesting
    energy_stats = harvester.measure_power(duration=args.duration * 3600)
    logger.info(f"\n7. Energy harvesting results:")
    logger.info(f"   Average power: {energy_stats.continuous_power:.2f} mW")
    logger.info(f"   Peak power: {energy_stats.peak_power:.2f} mW")
    logger.info(f"   Total energy: {energy_stats.total_energy:.2f} mWh")
    logger.info(f"   Efficiency: {energy_stats.efficiency:.1f}%")
    
    # 8. Mission summary
    logger.info("\n" + "=" * 60)
    logger.info("MISSION SUMMARY")
    logger.info("=" * 60)
    
    summary = {
        'mission': {
            'duration_hours': args.duration,
            'num_vehicles': args.num_vehicles,
            'depth_m': depth,
            'survey_area_m': args.survey_area
        },
        'navigation': {
            'rms_error_m': nav_results['rms_error'],
            'max_error_m': nav_results['max_error'],
            'improvement_factor': nav_results['improvement_factor']
        },
        'sensors': {
            'oxygen_penetration_cm': oxygen_profile.penetration_depth,
            'bioluminescence_events': len(bio_events),
            'pressure_fluctuations': len(fluctuations)
        },
        'energy': {
            'avg_power_mW': energy_stats.continuous_power,
            'peak_power_mW': energy_stats.peak_power,
            'total_energy_mWh': energy_stats.total_energy,
            'efficiency_percent': energy_stats.efficiency
        },
        'fluid_properties': props.all_properties()
    }
    
    # Print summary
    for category, data in summary.items():
        logger.info(f"\n{category.upper()}:")
        for key, value in data.items():
            if isinstance(value, dict):
                logger.info(f"  {key}:")
                for k, v in value.items():
                    logger.info(f"    {k}: {v}")
            else:
                logger.info(f"  {key}: {value}")
    
    # Export results
    import json
    import os
    
    os.makedirs(os.path.dirname(args.output), exist_ok=True)
    with open(args.output, 'w') as f:
        # Convert numpy types to Python types
        def convert(o):
            if isinstance(o, np.integer):
                return int(o)
            if isinstance(o, np.floating):
                return float(o)
            if isinstance(o, np.ndarray):
                return o.tolist()
            return o
        
        json.dump(summary, f, indent=2, default=convert)
    
    logger.info(f"\nResults saved to: {args.output}")
    logger.info("\nMission simulation completed successfully!")
    
    return summary


if __name__ == "__main__":
    main()
