import os
import sqlite3
from ngfs_fetcher import get_ngfs_data
from ksic_mapper import get_ksic_carbon_beta

def initialize_database():
    """
    Creates the climate_risk.db SQLite database in the /data directory,
    fetches all Phase 1 data, and loads them into relational tables.
    """
    # Create data dir if not exists
    os.makedirs('data', exist_ok=True)
    
    db_path = 'data/climate_risk.db'
    conn = sqlite3.connect(db_path)
    
    print("1. Fetching NGFS Data...")
    df_ngfs = get_ngfs_data()
    
    # Store NGFS dataframe. Melt years into a single column for better SQL querying
    # Assumes years are dynamically derived from columns
    id_vars = ['model', 'scenario', 'region', 'variable', 'unit']
    year_cols = [c for c in df_ngfs.columns if c not in id_vars]
    
    df_ngfs_melted = df_ngfs.melt(
        id_vars=id_vars, 
        value_vars=year_cols, 
        var_name='year', 
        value_name='value'
    )
    
    # Dump to SQLite
    df_ngfs_melted.to_sql('ngfs_macro_time_series', conn, if_exists='replace', index=False)
    print("   -> Loaded 'ngfs_macro_time_series' table.")
    
    print("2. Generating KSIC Carbon Beta Mappings...")
    df_ksic = get_ksic_carbon_beta()
    
    # Dump to SQLite
    df_ksic.to_sql('ksic_carbon_beta', conn, if_exists='replace', index=False)
    print("   -> Loaded 'ksic_carbon_beta' table.")
    
    conn.close()
    print(f"Database successfully generated at {db_path}")

if __name__ == '__main__':
    initialize_database()
