import json
import sys
from pathlib import Path

repo = Path.home() / 'TibiaPilotNG'
sys.path.insert(0, str(repo))

from tinydb import Query, TinyDB

from src.importers.bbot import import_bbot


source = Path(sys.argv[1]) if len(sys.argv) > 1 else next((Path.home() / 'Downloads').glob('*.bbot'))
db = TinyDB(repo / 'file.json')
profile = db.get(Query().enabled == True)
config, report = import_bbot(source, profile['config'])
profile['config'] = config
db.update(profile, doc_ids=[profile.doc_id])
db.close()

print(json.dumps({
    'source': source.name,
    'waypoints': report['waypoints'],
    'targets': report['targets'],
    'loot': report['lootItems'],
    'warnings': report['warnings'],
    'unsupported': report['unsupported'],
    'resetBackpacks': sum(
        waypoint['type'] == 'bbotResetBackpacks'
        for waypoint in config['ng_cave']['waypoints']['items']
    ),
}))
