# database.py
from sqlalchemy.orm import Session
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from . import models
import os

# Get username and password from environment variables
db_username = os.getenv("DB_USERNAME")
db_password = os.getenv("DB_PASSWORD")

# Construct the database URL
SQLALCHEMY_DATABASE_URL = f"mysql://{db_username}:{db_password}@localhost:3306/aare_db"

# Remove the `connect_args` parameter
engine = create_engine(SQLALCHEMY_DATABASE_URL)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()


# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def init_db():
    Base.metadata.create_all(bind=engine)


def load_sample_data(session: Session):
    # Import models inside function to avoid circular dependency
    from .data import (
        contacts,
        return_addresses,
        dewars,
        proposals,
        shipments,
        pucks,
        samples,
        dewar_types,
        serial_numbers,
        slots,
        sample_events,
    )

    # If any data already exists, skip seeding
    if session.query(models.ContactPerson).first():
        return

    session.add_all(
        contacts
        + return_addresses
        + dewars
        + proposals
        + shipments
        + pucks
        + samples
        + dewar_types
        + serial_numbers
        + slots
        + sample_events
    )
    session.commit()
