# scheduler/db_utils.py
from dotenv import load_dotenv
import os
from datetime import datetime
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from models.models import Event
# import sys
# sys.path.append('/workspace/server')

load_dotenv('/workspace/.env')

# DB-URL aus Umgebungsvariable oder Fallback
DB_CONN = os.environ.get("DB_CONN", "mysql+pymysql://user:password@db/dbname")
engine = create_engine(DB_CONN)
Session = sessionmaker(bind=engine)


def get_active_events(start: datetime, end: datetime, group_id: int = None):
    session = Session()
    query = session.query(Event).filter(Event.is_active == True)
    if start and end:
        query = query.filter(Event.start < end, Event.end > start)
    if group_id:
        query = query.filter(Event.group_id == group_id)
    events = query.all()
    session.close()
    return events
