#  Copyright (C) 2023
#  ABM, Moscow
#
#  UNPUBLISHED PROPRIETARY MATERIAL.
#  ALL RIGHTS RESERVED.
#
#  Authors: Mike Orlov <m.orlov@abm-jsc.ru>
from sqlalchemy_tools.utils.text import camel_case_to_underscore

from entity_read.entity import Entity


def ensure_tablename(entity_type: type[Entity], table_name: str = None) -> None:
    if table_name:
        entity_type.__tablename__ = table_name
    if not entity_type.__tablename__:
        entity_type.__tablename__ = camel_case_to_underscore(entity_type.__name__)


def set_table_schema(entity_type: type[Entity], table_schema: str = None) -> None:
    if table_schema is None:
        return
    entity_type.__table_schema_name__ = table_schema
    table_args = getattr(entity_type, '__table_args__', None)
    if isinstance(table_args, tuple):
        if isinstance(table_args[-1], dict):
            target_dict = table_args[-1]
        else:
            entity_type.__table_args__ = table_args + (target_dict := {}, )
    elif isinstance(table_args, dict):
        target_dict = table_args
    elif table_args is None:
        entity_type.__table_args__ = (target_dict := {})
    else:
        raise TypeError(f'Table has "__table_args__" with unexpected type {type(table_args)}')

    if schema := target_dict.get('schema'):
        raise KeyError(f'Attempt to specify schema "{table_schema}", but entity "{entity_type.__name__}" '
                       f'already has schema specified as "{schema}"')
    target_dict["schema"] = table_schema
    print()
