"""
Keeling Curve Data Loader
NOAA/Scripps Mauna Loa CO₂ measurements (1960-2025)
"""

import csv
import os
from typing import Dict, List, Optional


class KeelingLoader:
    """
    Loader for Keeling Curve atmospheric CO₂ data
    """
    
    def __init__(self, data_dir: str = "./data"):
        """
        Initialize Keeling loader
        
        Parameters
        ----------
        data_dir : str
            Base data directory
        """
        self.data_dir = data_dir
        self.keeling_dir = f"{data_dir}/keeling"
        self.data = []
        self._load_reference_data()
    
    def _load_reference_data(self):
        """Load reference data from research paper"""
        self.reference_data = [
            {'year': 1960, 'co2_ppm': 316.9, 'growth_rate': 0.90},
            {'year': 1965, 'co2_ppm': 320.0, 'growth_rate': 1.10},
            {'year': 1970, 'co2_ppm': 325.7, 'growth_rate': 1.28},
            {'year': 1975, 'co2_ppm': 331.1, 'growth_rate': 1.40},
            {'year': 1980, 'co2_ppm': 338.7, 'growth_rate': 1.51},
            {'year': 1985, 'co2_ppm': 346.0, 'growth_rate': 1.58},
            {'year': 1990, 'co2_ppm': 354.2, 'growth_rate': 1.63},
            {'year': 1995, 'co2_ppm': 360.8, 'growth_rate': 1.70},
            {'year': 2000, 'co2_ppm': 369.4, 'growth_rate': 1.88},
            {'year': 2005, 'co2_ppm': 379.7, 'growth_rate': 2.04},
            {'year': 2010, 'co2_ppm': 389.8, 'growth_rate': 2.19},
            {'year': 2015, 'co2_ppm': 400.8, 'growth_rate': 2.28},
            {'year': 2020, 'co2_ppm': 414.2, 'growth_rate': 2.35},
            {'year': 2025, 'co2_ppm': 424.0, 'growth_rate': 2.38}
        ]
    
    def load_from_file(self, filepath: str) -> List[Dict]:
        """
        Load Keeling data from CSV file
        
        Parameters
        ----------
        filepath : str
            Path to CSV file
        
        Returns
        -------
        list
            List of data records
        """
        if not os.path.exists(filepath):
            return self.reference_data
        
        data = []
        with open(filepath, 'r') as f:
            reader = csv.DictReader(f)
            for row in reader:
                # Convert strings to numbers
                record = {}
                for key, value in row.items():
                    try:
                        record[key] = float(value)
                    except ValueError:
                        record[key] = value
                data.append(record)
        
        self.data = data
        return data
    
    def load_from_url(self, url: str = "https://gml.noaa.gov/webdata/ccgg/trends/co2/co2_mm_mlo.txt") -> List[Dict]:
        """
        Load Keeling data from NOAA URL (simulated)
        
        Parameters
        ----------
        url : str
            NOAA data URL
        
        Returns
        -------
        list
            List of data records
        """
        # In a real implementation, this would download from NOAA
        # For now, return reference data
        print(f"📡 Would download from: {url}")
        print("📊 Using reference data instead")
        return self.reference_data
    
    def get_annual_means(self) -> List[Dict]:
        """
        Get annual mean CO₂ concentrations
        
        Returns
        -------
        list
            Annual means
        """
        if self.data:
            # Group by year and compute mean
            years = {}
            for record in self.data:
                year = record.get('year')
                if year and 'co2_ppm' in record:
                    if year not in years:
                        years[year] = []
                    years[year].append(record['co2_ppm'])
            
            annual = []
            for year, values in years.items():
                annual.append({
                    'year': year,
                    'co2_ppm': sum(values) / len(values)
                })
            return sorted(annual, key=lambda x: x['year'])
        else:
            return self.reference_data
    
    def get_monthly_data(self) -> List[Dict]:
        """
        Get monthly data (if available)
        
        Returns
        -------
        list
            Monthly data
        """
        # In a real implementation, this would return monthly data
        # For now, return annual data with month=6 (June average)
        monthly = []
        for record in self.reference_data:
            monthly.append({
                'year': record['year'],
                'month': 6,
                'co2_ppm': record['co2_ppm']
            })
        return monthly
    
    def compute_growth_rate(self, year: int) -> float:
        """
        Compute growth rate for specific year
        
        Parameters
        ----------
        year : int
            Target year
        
        Returns
        -------
        float
            Growth rate in ppm/yr
        """
        # Find closest year in reference data
        closest = min(self.reference_data, key=lambda x: abs(x['year'] - year))
        return closest['growth_rate']
    
    def get_time_series(self, start_year: int = 1960, 
                       end_year: int = 2025) -> List[Dict]:
        """
        Get complete time series
        
        Parameters
        ----------
        start_year : int
            Start year
        end_year : int
            End year
        
        Returns
        -------
        list
            Time series data
        """
        return [r for r in self.reference_data 
                if start_year <= r['year'] <= end_year]
    
    def summary(self) -> str:
        """Print summary of Keeling data"""
        first = self.reference_data[0]
        last = self.reference_data[-1]
        
        summary = f"""
╔════════════════════════════════════════════════════════════════╗
║                    Keeling Curve Summary                       ║
╠════════════════════════════════════════════════════════════════╣
║  Period      : {first['year']} - {last['year']} ({last['year']-first['year']} years)  ║
║  First CO₂   : {first['co2_ppm']:.1f} ppm ({first['year']})               ║
║  Latest CO₂  : {last['co2_ppm']:.1f} ppm ({last['year']})                ║
║  Total rise  : {last['co2_ppm'] - first['co2_ppm']:.1f} ppm               ║
║  Growth rate : {last['growth_rate']:.2f} ppm/yr (2025)           ║
╚════════════════════════════════════════════════════════════════╝
        """
        return summary
