import plyvel
import json
import sqlite3
import os
import sys

def dump_to_sqlite(ldb_path, sqlite_path):
    # Connect to SQLite
    conn = sqlite3.connect(sqlite_path)
    cursor = conn.cursor()

    # Create a generic table for all key-value pairs with JSON type support
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS foundry_data (
            key TEXT PRIMARY KEY,
            value JSON
        )
    ''')
    
    # Clear existing data
    cursor.execute('DELETE FROM foundry_data')

    try:
        # Open LevelDB
        db = plyvel.DB(ldb_path, create_if_missing=False)
        
        count = 0
        for key, value in db:
            try:
                # Decode key and value as utf-8 (Foundry data is typically JSON strings)
                k_str = key.decode('utf-8')
                v_str = value.decode('utf-8')
                
                cursor.execute(
                    'INSERT INTO foundry_data (key, value) VALUES (?, ?)',
                    (k_str, v_str)
                )
                count += 1
            except UnicodeDecodeError:
                # Fallback for any binary internal keys/values
                k_hex = f"hex:{key.hex()}"
                cursor.execute(
                    'INSERT INTO foundry_data (key, value) VALUES (?, ?)',
                    (k_hex, value.hex())
                )
                count += 1
            except Exception as e:
                print(f"Error processing key {key}: {e}")

        db.close()
        conn.commit()
        print(f"Successfully dumped {count} raw entries to {sqlite_path}")

    except Exception as e:
        print(f"Error opening LevelDB: {e}")
    finally:
        conn.close()

if __name__ == "__main__":
    # Default to our Monster Slayer DB if no arguments
    ldb = 'monster-slayer-subclass/packs/monster-slayer-db'
    sqlite = 'monster-slayer-items.db'
    
    if len(sys.argv) > 1:
        ldb = sys.argv[1]
    if len(sys.argv) > 2:
        sqlite = sys.argv[2]

    dump_to_sqlite(ldb, sqlite)
