import os
import sqlite3

def init_database():
    # Ensure data directory exists
    os.makedirs("data", exist_ok=True)
    
    # Connect to database
    conn = sqlite3.connect("data/cpu_storage.db")
    cursor = conn.cursor()
    
    # Create tables if they don't exist
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS mining_stats (
            cpu_id INTEGER,
            core_id INTEGER,
            thread_id INTEGER,
            hashes INTEGER DEFAULT 0,
            blocks_found INTEGER DEFAULT 0,
            last_hash_time REAL,
            PRIMARY KEY (cpu_id, core_id, thread_id)
        )
    """)
    
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS cpu_config (
            cpu_id INTEGER PRIMARY KEY,
            gate_delay REAL,
            switch_freq REAL,
            drift_speed REAL,
            clock_freq REAL,
            group_type INTEGER,
            core_count INTEGER,
            thread_count INTEGER,
            initialized INTEGER,
            last_updated INTEGER
        )
    """)
    
    conn.commit()
    print("Database initialized successfully!")
    
    # Show table structure
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
    tables = cursor.fetchall()
    
    print("\nDatabase Structure:")
    for table in tables:
        table_name = table[0]
        print(f"\nTable: {table_name}")
        cursor.execute(f"PRAGMA table_info({table_name})")
        columns = cursor.fetchall()
        for col in columns:
            print(f"  {col[1]}: {col[2]}")
    
    conn.close()

if __name__ == "__main__":
    init_database()