"""
GTN-P Data Loader
Global Terrestrial Network for Permafrost - Borehole temperatures
"""

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


class GTNPLoader:
    """
    Loader for GTN-P permafrost data
    """
    
    def __init__(self, data_dir: str = "./data"):
        """
        Initialize GTN-P loader
        
        Parameters
        ----------
        data_dir : str
            Base data directory
        """
        self.data_dir = data_dir
        self.gtnp_dir = f"{data_dir}/gtnp"
        self.data = []
        self._load_reference_data()
    
    def _load_reference_data(self):
        """Load reference data from research paper"""
        # Regional permafrost data
        self.regional_data = {
            'western_siberia': {
                'area_km2': 2.5e6,
                'carbon_density': 28.1,
                'magt_2025': -0.5,
                'magt_trend': 0.08,
                'flux_2025': 0.62,
                'abrupt_fraction': 0.28
            },
            'canadian_zone': {
                'area_km2': 2.2e6,
                'carbon_density': 25.3,
                'magt_2025': -0.8,
                'magt_trend': 0.07,
                'flux_2025': 0.51,
                'abrupt_fraction': 0.25
            },
            'alaska': {
                'area_km2': 1.5e6,
                'carbon_density': 22.8,
                'magt_2025': -0.3,
                'magt_trend': 0.09,
                'flux_2025': 0.28,
                'abrupt_fraction': 0.32
            },
            'esas': {  # East Siberian Arctic Shelf
                'area_km2': 2.1e6,
                'carbon_density': 140.0,
                'magt_2025': -1.5,
                'magt_trend': 0.08,
                'flux_2025': 0.15,
                'abrupt_fraction': 0.45,
                'notes': 'submarine permafrost'
            }
        }
        
        # Global totals
        self.global_totals = {
            'total_area': 21.0e6,  # km²
            'total_carbon': 1500,  # PgC
            'flux_2025': 1.71,
            'abrupt_fraction': 0.31,
            'n_boreholes': 1240
        }
    
    def load_from_file(self, filepath: str) -> List[Dict]:
        """
        Load GTN-P data from CSV file
        
        Parameters
        ----------
        filepath : str
            Path to CSV file
        
        Returns
        -------
        list
            List of borehole records
        """
        if not os.path.exists(filepath):
            # Return synthetic data
            return self._generate_synthetic_boreholes()
        
        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 _generate_synthetic_boreholes(self, n: int = 100) -> List[Dict]:
        """Generate synthetic borehole data for testing"""
        boreholes = []
        
        regions = list(self.regional_data.keys())
        
        for i in range(n):
            region = regions[i % len(regions)]
            reg_data = self.regional_data[region]
            
            boreholes.append({
                'id': f"BORE{i:04d}",
                'region': region,
                'latitude': 60 + (i % 30),
                'longitude': -120 + (i % 60),
                'magt_2025': reg_data['magt_2025'] + (i % 10) * 0.1,
                'active_layer_depth': 0.5 + (i % 20) * 0.1,
                'carbon_density': reg_data['carbon_density'],
                'trend': reg_data['magt_trend']
            })
        
        return boreholes
    
    def get_region_flux(self, region: str, year: int = 2025) -> float:
        """
        Get permafrost flux for specific region
        
        Parameters
        ----------
        region : str
            Region name
        year : int
            Target year
        
        Returns
        -------
        float
            Regional flux (PgC/yr)
        """
        if region not in self.regional_data:
            return 0.0
        
        base_flux = self.regional_data[region]['flux_2025']
        
        if year == 2025:
            return base_flux
        elif year < 2025:
            # Scale down for earlier years
            return base_flux * (0.2 + 0.8 * (year - 1990) / 35)
        else:
            # Project forward
            return base_flux * (1 + 0.05 * (year - 2025))
    
    def get_global_flux(self, year: int = 2025) -> float:
        """
        Get global permafrost flux
        
        Parameters
        ----------
        year : int
            Target year
        
        Returns
        -------
        float
            Global flux (PgC/yr)
        """
        if year == 2025:
            return self.global_totals['flux_2025']
        
        # Sum regional fluxes
        total = 0
        for region in self.regional_data:
            total += self.get_region_flux(region, year)
        
        return total
    
    def get_abrupt_fraction(self, region: Optional[str] = None) -> float:
        """
        Get fraction of flux from abrupt thaw
        
        Parameters
        ----------
        region : str, optional
            Region name
        
        Returns
        -------
        float
            Abrupt thaw fraction (0-1)
        """
        if region and region in self.regional_data:
            return self.regional_data[region]['abrupt_fraction']
        return self.global_totals['abrupt_fraction']
    
    def get_carbon_stocks(self) -> Dict:
        """
        Get permafrost carbon stocks
        
        Returns
        -------
        dict
            Carbon stocks by region
        """
        stocks = {}
        for region, data in self.regional_data.items():
            stocks[region] = {
                'carbon_pg': data['carbon_density'] * data['area_km2'] * 1e-6,
                'area_km2': data['area_km2']
            }
        
        stocks['global'] = {
            'carbon_pg': self.global_totals['total_carbon'],
            'area_km2': self.global_totals['total_area']
        }
        
        return stocks
    
    def summary(self) -> str:
        """Print summary of GTN-P data"""
        stocks = self.get_carbon_stocks()
        
        summary = f"""
╔════════════════════════════════════════════════════════════════╗
║                    GTN-P Permafrost Summary                   ║
╠════════════════════════════════════════════════════════════════╣
║  Boreholes          : {self.global_totals['n_boreholes']}                          ║
║  Total area         : {self.global_totals['total_area']/1e6:.1f} million km²            ║
║  Total carbon       : {self.global_totals['total_carbon']} PgC                        ║
║  Flux (2025)        : {self.global_totals['flux_2025']:.2f} PgC/yr                    ║
║  Abrupt fraction    : {self.global_totals['abrupt_fraction']*100:.0f}%                          ║
╠════════════════════════════════════════════════════════════════╣
║  Regional carbon stocks:                                      ║
║    Western Siberia   : {stocks['western_siberia']['carbon_pg']:.0f} PgC                      ║
║    Canadian zone     : {stocks['canadian_zone']['carbon_pg']:.0f} PgC                      ║
║    Alaska           : {stocks['alaska']['carbon_pg']:.0f} PgC                      ║
║    ESAS (submarine)  : {stocks['esas']['carbon_pg']:.0f} PgC                      ║
╚════════════════════════════════════════════════════════════════╝
        """
        return summary
