import inspect
import logging
import os
from config import Config
from contextlib import contextmanager
from sqlalchemy import create_engine
from sqlalchemy.orm import (sessionmaker, scoped_session)
from typing import Generator

from log import log

MYSQL_CONNECT = os.environ.get('MM_DB')
if MYSQL_CONNECT is None:
    raise ValueError("MYSQL_CONNECT is undefined")
else:
    dbname = MYSQL_CONNECT.split('/')[-1]
    log.debug(f"Database: {dbname}")

# MM_ENV = os.environ.get('MM_ENV', 'PRODUCTION')
# testing = False
# if MM_ENV == 'TESTING':
#     dbname = os.environ.get('MM_TESTING_DBNAME', 'musicmuster_testing')
#     dbuser = os.environ.get('MM_TESTING_DBUSER', 'musicmuster_testing')
#     dbpw = os.environ.get('MM_TESTING_DBPW', 'musicmuster_testing')
#     dbhost = os.environ.get('MM_TESTING_DBHOST', 'localhost')
#     testing = True
# else:
#     raise ValueError(f"Unknown MusicMuster environment: {MM_ENV=}")
#
# MYSQL_CONNECT = f"mysql+mysqldb://{dbuser}:{dbpw}@{dbhost}/{dbname}"

engine = create_engine(
    MYSQL_CONNECT,
    encoding='utf-8',
    echo=Config.DISPLAY_SQL,
    pool_pre_ping=True,
    future=True
)


@contextmanager
def Session() -> Generator[scoped_session, None, None]:
    frame = inspect.stack()[2]
    file = frame.filename
    function = frame.function
    lineno = frame.lineno
    Session = scoped_session(sessionmaker(bind=engine, future=True))
    log.debug(
        f"Session acquired, {file=}, {function=}, "
        f"function{lineno=}, {Session=}"
    )
    yield Session
    log.debug(" Session released")
    Session.commit()
    Session.close()
