#!/usr/bin/env python3
"""
Batch limit cycle detection script.
Detects limit cycles in multiple cave passages.
"""

import argparse
import sys
import numpy as np
import pandas as pd
from pathlib import Path

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

try:
    from cavora.core import LimitCycleDetector
    from cavora.utils.logger import setup_logger
except ImportError:
    print("Error: CAVORA package not found")
    sys.exit(1)


def main():
    parser = argparse.ArgumentParser(description="Detect limit cycles in cave passages")
    parser.add_argument("--input", "-i", required=True, help="Input CSV file with time series")
    parser.add_argument("--output", "-o", default="limit_cycles_report.csv", help="Output report")
    parser.add_argument("--verbose", "-v", action="store_true", help="Verbose output")
    
    args = parser.parse_args()
    
    # Setup logging
    logger = setup_logger("limit_cycle_detection", 
                         log_level="DEBUG" if args.verbose else "INFO")
    
    print("\n" + "="*60)
    print("CAVORA - Limit Cycle Detection")
    print("="*60)
    
    # Load data
    print(f"\nLoading data from: {args.input}")
    try:
        df = pd.read_csv(args.input)
        print(f"Loaded {len(df)} rows with columns: {list(df.columns)}")
    except Exception as e:
        print(f"Error loading data: {e}")
        sys.exit(1)
    
    # Check required columns
    required = ['passage_id', 'time', 'V']
    missing = [col for col in required if col not in df.columns]
    if missing:
        print(f"Missing required columns: {missing}")
        sys.exit(1)
    
    # Initialize detector
    detector = LimitCycleDetector()
    
    # Process each passage
    results = []
    passages = df['passage_id'].unique()
    
    print(f"\nProcessing {len(passages)} passages...")
    
    for passage in passages:
        print(f"  Analyzing: {passage}")
        
        # Get data for this passage
        passage_data = df[df['passage_id'] == passage].sort_values('time')
        
        if len(passage_data) < 10:
            print(f"    Skipping: insufficient data ({len(passage_data)} points)")
            continue
        
        # Extract time and V
        t = passage_data['time'].values
        V = passage_data['V'].values
        
        # Detect limit cycle
        result = detector.detect_from_trajectory(t, V)
        
        # Store results
        results.append({
            'passage_id': passage,
            'n_points': len(passage_data),
            'time_span': t[-1] - t[0],
            'limit_cycle_detected': result['detected'],
            'confidence': result['confidence'],
            'correlation_dimension': result['correlation_dimension'],
            'lyapunov_1': result['lyapunov_exponents']['lambda_1'],
            'lyapunov_2': result['lyapunov_exponents']['lambda_2'],
            'lyapunov_3': result['lyapunov_exponents']['lambda_3'],
            'amplitude': result['properties'].get('amplitude', 0) if result['properties'] else 0,
            'period': result['properties'].get('period', 0) if result['properties'] else 0
        })
    
    # Create report
    results_df = pd.DataFrame(results)
    results_df.to_csv(args.output, index=False)
    
    print(f"\nResults saved to: {args.output}")
    print(f"\nSummary:")
    print(f"  Total passages analyzed: {len(results)}")
    print(f"  Limit cycles detected: {results_df['limit_cycle_detected'].sum()}")
    print(f"  Detection rate: {results_df['limit_cycle_detected'].mean()*100:.1f}%")
    
    print("\n" + "="*60)


if __name__ == "__main__":
    main()
