# generate_jsons.py
"""
Reads data from blockchain_logic and writes JSON files for each species.
Put this in the project root (same place where app.py lives) and run:
    python generate_jsons.py
"""

import os
import json
import sys

# If you had import problems like ModuleNotFoundError for local modules,
# ensure project root is on sys.path:
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
if PROJECT_ROOT not in sys.path:
    sys.path.insert(0, PROJECT_ROOT)

try:
    import blockchain_logic   # <- adapt if module name/path differs
except Exception as e:
    print("Error importing blockchain_logic:", e)
    print("Make sure this script runs from the project root and that blockchain_logic.py is importable.")
    raise

# --- ADAPT BELOW: how to extract data from blockchain_logic ---
# I'll provide two common patterns. Use the one that matches your code.

# Pattern A: blockchain_logic exposes get_all_species() and get_blocks_for_species(species)
def pattern_a():
    species_list = blockchain_logic.get_all_species()
    out = {}
    for sp in species_list:
        blocks = blockchain_logic.get_blocks_for_species(sp)
        out[sp] = blocks
    return out

# Pattern B: blockchain_logic exposes get_all_blocks() returning list of dicts each with 'species' key
def pattern_b():
    all_blocks = blockchain_logic.get_all_blocks()
    out = {}
    for b in all_blocks:
        sp = b.get('species') or b.get('Species') or 'unknown'
        out.setdefault(sp, []).append(b)
    return out

# Try to detect which pattern works
try:
    if hasattr(blockchain_logic, "get_all_species") and hasattr(blockchain_logic, "get_blocks_for_species"):
        data_by_species = pattern_a()
    elif hasattr(blockchain_logic, "get_all_blocks"):
        data_by_species = pattern_b()
    else:
        # Fallback: if blockchain_logic has a 'blocks' variable
        if hasattr(blockchain_logic, "blocks"):
            data_by_species = {}
            for b in blockchain_logic.blocks:
                sp = b.get("species", "unknown")
                data_by_species.setdefault(sp, []).append(b)
        else:
            raise RuntimeError("Could not detect how to read blocks from blockchain_logic.py. "
                               "Please adapt generate_jsons.py to your module's API.")
except Exception:
    raise

# Write JSON files under static/json/<species>.json and optionally per-block files.
out_dir = os.path.join(PROJECT_ROOT, "static", "json")
os.makedirs(out_dir, exist_ok=True)

for species, blocks in data_by_species.items():
    safe_name = species.lower().replace(" ", "_")
    filename = f"{safe_name}.json"
    path = os.path.join(out_dir, filename)
    with open(path, "w", encoding="utf-8") as f:
        json.dump({"species": species, "blocks": blocks}, f, ensure_ascii=False, indent=2)
    print("Wrote", path)

# Optionally, write per-block jsons
for species, blocks in data_by_species.items():
    sname = species.lower().replace(" ", "_")
    species_dir = os.path.join(out_dir, sname)
    os.makedirs(species_dir, exist_ok=True)
    for block in blocks:
        # ensure block number/id exists
        block_id = block.get("block_number") or block.get("id") or block.get("block") or "unknown"
        path = os.path.join(species_dir, f"block_{block_id}.json")
        with open(path, "w", encoding="utf-8") as f:
            json.dump(block, f, ensure_ascii=False, indent=2)
