"""
GCP Data Loader
Global Carbon Project - Annual carbon budget
"""

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


class GCPLoader:
    """
    Loader for Global Carbon Project budget data
    """
    
    def __init__(self, data_dir: str = "./data"):
        """
        Initialize GCP loader
        
        Parameters
        ----------
        data_dir : str
            Base data directory
        """
        self.data_dir = data_dir
        self.gcp_dir = f"{data_dir}/gcp"
        self.data = []
        self._load_reference_data()
    
    def _load_reference_data(self):
        """Load reference data from research paper"""
        self.reference_data = [
            {'year': 1960, 'E_anth': 2.8, 'E_LUC': 0.8, 'S_ocean': -1.21, 'S_land': -1.59},
            {'year': 1970, 'E_anth': 4.1, 'E_LUC': 0.9, 'S_ocean': -1.44, 'S_land': -1.76},
            {'year': 1980, 'E_anth': 5.3, 'E_LUC': 1.0, 'S_ocean': -1.78, 'S_land': -1.92},
            {'year': 1990, 'E_anth': 6.1, 'E_LUC': 1.1, 'S_ocean': -1.93, 'S_land': -2.17},
            {'year': 2000, 'E_anth': 6.8, 'E_LUC': 1.2, 'S_ocean': -2.24, 'S_land': -2.36},
            {'year': 2010, 'E_anth': 9.1, 'E_LUC': 1.1, 'S_ocean': -2.71, 'S_land': -2.89},
            {'year': 2020, 'E_anth': 10.5, 'E_LUC': 1.1, 'S_ocean': -3.05, 'S_land': -3.15},
            {'year': 2025, 'E_anth': 11.2, 'E_LUC': 1.1, 'S_ocean': -3.08, 'S_land': -3.22}
        ]
        
        # Country-level emissions (2025, PgC/yr)
        self.country_emissions = {
            'china': 3.2,
            'usa': 1.4,
            'eu': 0.9,
            'india': 0.8,
            'russia': 0.5,
            'japan': 0.3,
            'other': 4.1
        }
    
    def load_from_file(self, filepath: str) -> List[Dict]:
        """
        Load GCP data from CSV file
        
        Parameters
        ----------
        filepath : str
            Path to CSV file
        
        Returns
        -------
        list
            List of budget 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:
                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 get_emissions(self, year: int, include_luc: bool = True) -> float:
        """
        Get anthropogenic emissions for given year
        
        Parameters
        ----------
        year : int
            Target year
        include_luc : bool
            Include land-use change emissions
        
        Returns
        -------
        float
            Total emissions (PgC/yr)
        """
        closest = min(self.reference_data, key=lambda x: abs(x['year'] - year))
        
        if include_luc:
            return closest['E_anth']
        else:
            # Fossil fuel only (E_anth - E_LUC)
            return closest['E_anth'] - closest.get('E_LUC', 1.1)
    
    def get_sinks(self, year: int) -> Dict:
        """
        Get sink strengths for given year
        
        Parameters
        ----------
        year : int
            Target year
        
        Returns
        -------
        dict
            Sink strengths (PgC/yr)
        """
        closest = min(self.reference_data, key=lambda x: abs(x['year'] - year))
        
        return {
            'ocean': closest['S_ocean'],
            'land': closest['S_land'],
            'total': closest['S_ocean'] + closest['S_land']
        }
    
    def get_residual(self, year: int) -> float:
        """
        Get budget residual (atmospheric accumulation)
        
        Parameters
        ----------
        year : int
            Target year
        
        Returns
        -------
        float
            Residual (PgC/yr)
        """
        closest = min(self.reference_data, key=lambda x: abs(x['year'] - year))
        
        # dC_atm/dt = E_anth - S_ocean - S_land
        residual = closest['E_anth'] - closest['S_ocean'] - closest['S_land']
        
        return residual
    
    def get_country_emissions(self, country: str) -> float:
        """
        Get emissions for specific country
        
        Parameters
        ----------
        country : str
            Country name
        
        Returns
        -------
        float
            Emissions (PgC/yr)
        """
        return self.country_emissions.get(country.lower(), 0.0)
    
    def summary(self) -> str:
        """Print summary of GCP data"""
        latest = self.reference_data[-1]
        residual = self.get_residual(2025)
        
        summary = f"""
╔════════════════════════════════════════════════════════════════╗
║              Global Carbon Project Summary (2025)              ║
╠════════════════════════════════════════════════════════════════╣
║  Total emissions   : {latest['E_anth']:.1f} PgC/yr                     ║
║    - Fossil fuel   : {latest['E_anth'] - latest['E_LUC']:.1f} PgC/yr            ║
║    - Land use      : {latest['E_LUC']:.1f} PgC/yr                           ║
╠════════════════════════════════════════════════════════════════╣
║  Ocean sink        : {latest['S_ocean']:.2f} PgC/yr                    ║
║  Land sink         : {latest['S_land']:.2f} PgC/yr                     ║
║  Atmospheric accumulation: {residual:.2f} PgC/yr ({residual*0.47:.1f} ppm/yr)║
╠════════════════════════════════════════════════════════════════╣
║  Top emitters (2025):                                           ║
║    China  : {self.country_emissions['china']:.1f} PgC/yr                         ║
║    USA    : {self.country_emissions['usa']:.1f} PgC/yr                         ║
║    EU     : {self.country_emissions['eu']:.1f} PgC/yr                         ║
║    India  : {self.country_emissions['india']:.1f} PgC/yr                         ║
╚════════════════════════════════════════════════════════════════╝
        """
        return summary
