import os
import sqlite3
import pandas as pd

def export_db_to_csv():
    print("--- Phase 3: SQLite Data Integrity Check & CSV Exporter ---")
    
    db_path = 'data/climate_risk.db'
    export_dir = 'data/exports'
    
    if not os.path.exists(export_dir):
        os.makedirs(export_dir)
        
    conn = sqlite3.connect(db_path)
    
    # Tables to export
    tables = [
        'ngfs_macro_time_series',
        'ksic_carbon_beta',
        'shocks_ir',
        'shocks_credit',
        'shocks_equity'
    ]
    
    for table in tables:
        try:
            df = pd.read_sql(f"SELECT * FROM {table}", conn)
            
            # Integrity Check
            null_count = df.isnull().sum().sum()
            if null_count > 0:
                print(f"[Warning] Table {table} contains {null_count} NULL values.")
            else:
                print(f"[Pass] Table {table} integrity check passed (No NULLs).")
                
            # Export
            out_path = os.path.join(export_dir, f"{table}.csv")
            df.to_csv(out_path, index=False)
            print(f" -> Exported {len(df)} rows to {out_path}")
            
        except Exception as e:
            print(f"[Error] Failed to process table {table}: {e}")
            
    conn.close()
    print("Export process finished successfully.\n")

if __name__ == '__main__':
    export_db_to_csv()
