import plyvel
import json
import os
import shutil

# Items to include
item_files = [
    'feat-hunters-sense.json',
    'feat-magic-users-nemesis.json',
    'feat-slayers-counter.json',
    'feat-slayers-prey.json',
    'feat-supernatural-defense.json',
    'subclass-monster-slayer.json'
]

src_path = 'monster-slayer-subclass/src'
dest_path = 'monster-slayer-subclass/packs/monster-slayer-db'

if os.path.exists(dest_path):
    shutil.rmtree(dest_path)

os.makedirs(dest_path, exist_ok=True)

db = plyvel.DB(dest_path, create_if_missing=True)

for f_name in item_files:
    f_path = os.path.join(src_path, f_name)
    if not os.path.exists(f_path):
        print(f"Skipping {f_path} (not found)")
        continue
        
    with open(f_path, 'r') as f:
        item = json.load(f)
    
    item_id = item['_id']
    
    # Extract effects if present (Foundry LevelDB stores them separately)
    effects = item.pop('effects', [])
    
    # Save the main item
    key = f"!items!{item_id}".encode('utf-8')
    value = json.dumps(item).encode('utf-8')
    db.put(key, value)
    
    # Save embedded effects
    for effect in effects:
        effect_id = effect['_id']
        # Link effect to source item flags if needed (e.g. for cleanup logic)
        # But we'll do that in the source JSON instead to be explicit
        effect_key = f"!items.effects!{item_id}.{effect_id}".encode('utf-8')
        effect_value = json.dumps(effect).encode('utf-8')
        db.put(effect_key, effect_value)
        print(f"  + Added Effect: {effect['name']} ({effect_id})")

    print(f"Added {item['name']} ({item_id})")

db.close()
print(f"LevelDB rebuilt at {dest_path}")
