#!/usr/bin/env python3
"""
Generate comprehensive stability report for cave passage.
Command-line utility for CAVORA.

Author: Samir Baladi
"""

import argparse
import sys
import json
from datetime import datetime
import numpy as np

sys.path.insert(0, '.')

try:
    from cavora.core import VanDerPolOscillator, CoupledVLFOscillator
    from cavora.core import LimitCycleDetector, StabilityEnvelopeCalculator
    from cavora.parameters import VerticalPassage, LateralConduit, FlowstoneDeposition
    from cavora.utils.logger import setup_logger
except ImportError:
    print("Error: CAVORA package not found. Make sure it's installed.")
    sys.exit(1)


def main():
    parser = argparse.ArgumentParser(
        description="Generate stability report for cave passage"
    )
    parser.add_argument("--v", type=float, default=2.8,
                       help="Vertical passage dimension (m)")
    parser.add_argument("--l", type=float, default=3.2,
                       help="Lateral conduit dimension (m)")
    parser.add_argument("--f", type=float, default=0.087,
                       help="Flowstone thickness (mm)")
    parser.add_argument("--q", type=float, default=0.15,
                       help="Water discharge (m³/s)")
    parser.add_argument("--co2", type=float, default=850,
                       help="CO₂ concentration (ppm)")
    parser.add_argument("--output", "-o", type=str,
                       help="Output file (JSON format)")
    parser.add_argument("--verbose", "-v", action="store_true",
                       help="Verbose output")
    
    args = parser.parse_args()
    
    # Setup logging
    logger = setup_logger("stability_report", 
                         log_level="DEBUG" if args.verbose else "INFO")
    
    print("\n" + "="*60)
    print("CAVORA - Stability Report Generator")
    print("="*60)
    print(f"\nAnalyzing passage state:")
    print(f"  V = {args.v} m")
    print(f"  L = {args.l} m")
    print(f"  F = {args.f} mm")
    print(f"  Q = {args.q} m³/s")
    print(f"  CO₂ = {args.co2} ppm")
    
    # Initialize calculators
    from cavora.parameters import PassageState
    from cavora.prediction import StabilityEnvelopePredictor
    
    state = PassageState(
        V=args.v,
        L=args.l,
        F=args.f,
        Q=args.q,
        CO2=args.co2
    )
    
    calculator = StabilityEnvelopeCalculator()
    predictor = StabilityEnvelopePredictor()
    
    # Calculate stability
    envelope = calculator.calculate_envelope(state)
    
    print(f"\n{'='*60}")
    print(f"STABILITY ASSESSMENT")
    print(f"{'='*60}")
    print(f"\nStability Score: {envelope.score}/100")
    print(f"Level: {envelope.color} {envelope.level}")
    print(f"CDZ Proximity: {envelope.p_cdz:.1%}")
    print(f"Action: {envelope.action}")
    print(f"Max Team Hours: {envelope.max_hours}")
    
    if envelope.safe_until:
        print(f"Safe Until: {envelope.safe_until:.1f} hours")
    
    # Risk components
    print(f"\n{'='*60}")
    print(f"RISK COMPONENTS")
    print(f"{'='*60}")
    
    # V risk
    v_dev = abs(args.v - 2.5) / 2.5 * 100
    print(f"\nVertical (V): {args.v:.1f} m")
    print(f"  Deviation from ideal: {v_dev:.1f}%")
    
    # L risk
    l_dev = abs(args.l - 3.0) / 3.0 * 100
    print(f"\nLateral (L): {args.l:.1f} m")
    print(f"  Deviation from ideal: {l_dev:.1f}%")
    
    # F risk
    f_dev = abs(args.f - 0.087) / 0.087 * 100
    print(f"\nFlowstone (F): {args.f:.3f} mm")
    print(f"  Deviation from ideal: {f_dev:.1f}%")
    
    # Hydrological risk
    print(f"\nHydrology:")
    if args.q < 0.5:
        print(f"  Discharge: {args.q:.2f} m³/s (SAFE)")
    elif args.q < 2.0:
        print(f"  Discharge: {args.q:.2f} m³/s (CAUTION)")
    elif args.q < 5.0:
        print(f"  Discharge: {args.q:.2f} m³/s (HIGH RISK)")
    else:
        print(f"  Discharge: {args.q:.2f} m³/s (CRITICAL)")
    
    # CO₂ risk
    print(f"\nAir Quality:")
    if args.co2 < 1000:
        print(f"  CO₂: {args.co2} ppm (NORMAL)")
    elif args.co2 < 2000:
        print(f"  CO₂: {args.co2} ppm (ELEVATED)")
    elif args.co2 < 5000:
        print(f"  CO₂: {args.co2} ppm (HIGH)")
    else:
        print(f"  CO₂: {args.co2} ppm (DANGEROUS)")
    
    # Recommendations
    print(f"\n{'='*60}")
    print(f"RECOMMENDATIONS")
    print(f"{'='*60}")
    
    recommendations = []
    if envelope.level == "STABLE":
        recommendations = [
            "Standard survey procedures",
            "Normal documentation interval (5m)",
            "Continue monitoring"
        ]
    elif envelope.level == "CAUTION":
        recommendations = [
            "Increase measurement frequency to 2m",
            "Deploy additional sensors",
            "Monitor CO₂ and water level continuously",
            "Limit team size to 4 maximum"
        ]
    elif envelope.level == "UNSTABLE":
        recommendations = [
            "ACTIVATE CDZ PROTOCOL",
            "Maximum documentation (0.5m interval)",
            "Two-team configuration with safety backup",
            "Continuous sensor monitoring",
            "Mark evacuation route"
        ]
    elif envelope.level == "HIGH RISK":
        recommendations = [
            "PREPARE FOR EVACUATION",
            "Move to safe zone",
            "Deploy emergency beacons",
            "Contact surface support"
        ]
    else:  # CRITICAL
        recommendations = [
            "IMMEDIATE EVACUATION REQUIRED",
            "Abandon non-essential gear",
            "Proceed to nearest exit",
            "Do not re-enter"
        ]
    
    for i, rec in enumerate(recommendations, 1):
        print(f"{i}. {rec}")
    
    # Save report if requested
    if args.output:
        report = {
            'timestamp': datetime.now().isoformat(),
            'input': {
                'V': args.v,
                'L': args.l,
                'F': args.f,
                'Q': args.q,
                'CO2': args.co2
            },
            'stability': {
                'score': envelope.score,
                'level': envelope.level,
                'color': envelope.color,
                'cdz_proximity': envelope.p_cdz,
                'action': envelope.action,
                'max_hours': envelope.max_hours
            },
            'recommendations': recommendations
        }
        
        with open(args.output, 'w') as f:
            json.dump(report, f, indent=2)
        
        print(f"\nReport saved to: {args.output}")
    
    print("\n" + "="*60)


if __name__ == "__main__":
    main()
