# -*- coding: utf-8 -*-
# Generated by BMDB - DO NOT EDIT MANUALLY
# ======================================================================

from sqlalchemy import Column, Integer, String, Text, Float, Boolean, Date, DateTime, ForeignKey, create_engine
from sqlalchemy.orm import declarative_base, sessionmaker, Session
from sqlalchemy.orm import relationship
import os
from dotenv import load_dotenv
from pathlib import Path

Base = declarative_base()

# Load DB connection from .env at runtime
# Try to find .env in current directory first
env_path = Path.cwd() / '.env'
if env_path.exists():
    load_dotenv(dotenv_path=env_path)
else:
    load_dotenv()

DB_URL = os.getenv('DB_CONNECTION', '').strip('"')
engine = create_engine(DB_URL, echo=False) if DB_URL else None
SessionLocal = sessionmaker(bind=engine) if engine else None

class ModelMixin:
    '''Mixin to add CRUD methods to models'''
    
    def save(self):
        '''Create or update this instance'''
        if not SessionLocal:
            raise RuntimeError('Database not configured. Check your .env file')
        session = SessionLocal()
        try:
            session.add(self)
            session.commit()
            session.refresh(self)
            return self
        except Exception as e:
            session.rollback()
            raise e
        finally:
            session.close()
    
    def delete(self):
        '''Delete this instance'''
        if not SessionLocal:
            raise RuntimeError('Database not configured. Check your .env file')
        session = SessionLocal()
        try:
            session.delete(self)
            session.commit()
            return True
        except Exception as e:
            session.rollback()
            raise e
        finally:
            session.close()
    
    @classmethod
    def get(cls, id):
        '''Get record by ID'''
        if not SessionLocal:
            raise RuntimeError('Database not configured. Check your .env file')
        session = SessionLocal()
        try:
            return session.query(cls).filter(cls.id == id).first()
        finally:
            session.close()
    
    @classmethod
    def all(cls):
        '''Get all records'''
        if not SessionLocal:
            raise RuntimeError('Database not configured. Check your .env file')
        session = SessionLocal()
        try:
            return session.query(cls).all()
        finally:
            session.close()
    
    @classmethod
    def filter(cls, **kwargs):
        '''Filter records by field values'''
        if not SessionLocal:
            raise RuntimeError('Database not configured. Check your .env file')
        session = SessionLocal()
        try:
            query = session.query(cls)
            for key, value in kwargs.items():
                if hasattr(cls, key):
                    query = query.filter(getattr(cls, key) == value)
            return query.all()
        finally:
            session.close()
    
    @classmethod
    def first(cls, **kwargs):
        '''Get first record matching filters'''
        if not SessionLocal:
            raise RuntimeError('Database not configured. Check your .env file')
        session = SessionLocal()
        try:
            query = session.query(cls)
            for key, value in kwargs.items():
                if hasattr(cls, key):
                    query = query.filter(getattr(cls, key) == value)
            return query.first()
        finally:
            session.close()
    
    @classmethod
    def count(cls, **kwargs):
        '''Count records matching filters'''
        if not SessionLocal:
            raise RuntimeError('Database not configured. Check your .env file')
        session = SessionLocal()
        try:
            query = session.query(cls)
            for key, value in kwargs.items():
                if hasattr(cls, key):
                    query = query.filter(getattr(cls, key) == value)
            return query.count()
        finally:
            session.close()
    
    def to_dict(self):
        '''Convert model instance to dictionary'''
        result = {}
        for column in self.__table__.columns:
            result[column.name] = getattr(self, column.name)
        return result

class User(Base, ModelMixin):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String)  # String
    email = Column(String, unique=True)  # String @unique
    password = Column(String)  # String
    age = Column(Integer)  # Integer
