import json
from pathlib import Path

from ttfrog.db import schema
from ttfrog.db.manager import db

DATA_PATH = Path(__file__).parent


def load(data: str = ""):
    db.metadata.drop_all(bind=db.engine)
    db.init()
    with db.transaction():
        if not data:
            data = (DATA_PATH / "bootstrap.json").read_text()
        db.load(json.loads(data))
        tiefling = db.Ancestry.filter_by(name="tiefling").one()
        human = db.Ancestry.filter_by(name="human").one()
        fighter = db.CharacterClass.filter_by(name="fighter").one()
        rogue = db.CharacterClass.filter_by(name="rogue").one()

        sabetha = schema.Character("Sabetha", ancestry=tiefling, _intelligence=14)
        sabetha.add_class(fighter)
        sabetha.add_class(rogue)
        sabetha.level_up(fighter, 2)
        sabetha.level_up(rogue, 3)

        bob = schema.Character("Bob", ancestry=human)

        # persist all the records we've created
        db.add_or_update([sabetha, bob])
