"""
FutureSight - Predictive analytics
"""

import numpy as np
from datetime import datetime, timedelta
import logging

logger = logging.getLogger(__name__)


class FutureSight:
    """Forecasting system"""
    
    def __init__(self):
        self.forecast_history = []
        
    def predict_temperature(self, historical_data: list, hours_ahead: int = 24) -> dict:
        if len(historical_data) < 2:
            return {'error': 'Insufficient data'}
        
        temps = [d.get('temperature_c', 0) for d in historical_data]
        
        # Simple linear prediction
        x = np.arange(len(temps))
        coeffs = np.polyfit(x, temps, 1)
        
        predictions = []
        for i in range(1, hours_ahead + 1):
            pred_time = datetime.now() + timedelta(hours=i)
            pred_value = coeffs[0] * (len(temps) + i) + coeffs[1]
            
            predictions.append({
                'timestamp': pred_time.isoformat(),
                'temperature_c': float(pred_value),
                'confidence': max(0.7 - (i * 0.01), 0.3)  # Less confidence further out
            })
        
        forecast = {
            'forecast_id': f"temp_fc_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
            'created_at': datetime.now().isoformat(),
            'horizon_hours': hours_ahead,
            'predictions': predictions,
            'current_trend': 'increasing' if coeffs[0] > 0 else 'decreasing',
            'trend_strength': abs(coeffs[0])
        }
        
        self.forecast_history.append(forecast)
        logger.info(f"Temperature forecast created: {hours_ahead} hours ahead")
        
        return forecast
    
    def get_forecast_accuracy(self) -> dict:
        if len(self.forecast_history) < 2:
            return {'message': 'Not enough forecasts for accuracy calculation'}
        
        return {
            'total_forecasts': len(self.forecast_history),
            'latest_forecast': self.forecast_history[-1]['forecast_id'],
            'analysis_time': datetime.now().isoformat()
        }
