import os
import json
import numpy as np


BASE_DIR = os.path.dirname(os.path.abspath(__file__))
POOL_FILE = os.path.join(BASE_DIR, "qrng_pool.json")


def load_pool():
    """Load entropy pool from qrng_pool.json."""
    if not os.path.exists(POOL_FILE):
        return []

    try:
        with open(POOL_FILE, 'r') as f:
            return json.load(f).get('pool', [])
    except json.JSONDecodeError:
        print("⚠️ Pool file corrupted or empty. Resetting pool.")
        return []


def save_pool(pool):
    """Save entropy pool to qrng_pool.json."""
    with open(POOL_FILE, 'w') as f:
        json.dump({'pool': pool}, f)


def draw_numbers(count):
    """Draw a specified number of entropy values from the pool."""
    pool = load_pool()

    if len(pool) < count:
        print(f"⚠️ Pool too small ({len(pool)} numbers), using simulated data.")
        data = np.random.randint(0, 256, size=count).tolist()
        source = "simulated"
    else:
        data = pool[:count]
        pool = pool[count:]
        save_pool(pool)
        source = "qrng_pool"

    return data, source


def generate_entropic_id(length=32, charset="0123456789"):
    """Generate an entropic ID from the pool."""
    data, source = draw_numbers(length)
    id_str = ''.join([charset[num % len(charset)] for num in data])

    print(f"✅ Generated entropic ID ({source}): {id_str}")
    return id_str


# Optional standalone test
if __name__ == "__main__":
    print(generate_entropic_id())
