from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from pathlib import Path

import logging.config
import yaml
from platformdirs import PlatformDirs
from sqlalchemy import create_engine, select
from sqlalchemy.orm import sessionmaker

from schema import Comic, Publisher, Base

parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument('--recreate-db', action='store_true')
parser.add_argument('--verbose', '-v', action='count', default=0)
parser.add_argument('--file', '-f', default='~/data.json')
parser.add_argument('--config', '-c', default='kontor-docker')
args = parser.parse_args()


def get_logger(level: int, config: str):
    dirs = PlatformDirs(config)
    logging_config = Path(dirs.user_config_dir, 'logging-config.yaml')
    with open(logging_config, 'rt') as f:
        configDict = yaml.safe_load(f.read())
    logging.config.dictConfig(configDict)
    logger = logging.getLogger('development')
    if level is not None:
        match level:
            case 0:
                logger.setLevel(logging.INFO)
            case 1:
                logger.setLevel(logging.DEBUG)
            case _:
                logger.setLevel(logging.CRITICAL)
    return logger


if __name__ == '__main__':
    log = get_logger(args.verbose, args.config)
    log.info('kontor started')
    dirs = PlatformDirs(args.config)
    database_config = Path(dirs.user_config_dir, 'database-config.yaml')
    with open(database_config, 'rt') as f:
        db_config = yaml.safe_load(f.read())
    print(db_config)
    connect_string = ('mariadb+mariadbconnector://{}:{}@{}:{}/{}'.format(
        db_config['mariadb']['user'],
        db_config['mariadb']['password'],
        db_config['mariadb']['host'],
        db_config['mariadb']['port'],
        db_config['mariadb']['database']
    ))
    engine = create_engine(connect_string)
    Base.metadata.create_all(bind=engine, checkfirst=True)
    __session__ = sessionmaker(engine)
    with __session__() as session:
        comics = session.scalars(select(Comic)).all()
        for comic in comics:
            print(comic)
        publishers = session.scalars(select(Publisher)).all()
        for publisher in publishers:
            print(publisher)
            print(len(publisher.comics))
    log.info('kontor finished')
