from ..models import DbBaseModel
from ..utils import create_configured_db_engine
from pydantic import BaseModel
from sqlalchemy import text
from crud_start import DB_NAME



def add_new_record(record: BaseModel) -> DbBaseModel:
    """Insert a new record into the database table corresponding to the record's class name.

    Parameters
    ----------
    record: BaseModel :
        The Pydantic model instance to insert into the database.

    Returns
    -------
    DbBaseModel :
        The inserted database record with assigned ID.
    """
    conn = create_configured_db_engine(DB_NAME)
    table_name = record.__class__.__name__.lower() + "s"  # pluralize
    # Get the current max id
    query_max_id = text(f"SELECT MAX(id) FROM {table_name}")
    result = conn.execute(query_max_id)
    max_id = result.fetchone()[0] or 0
    new_id = max_id + 1
    
    # Insert the new record
    db_record = DbBaseModel(id=new_id, **record.model_dump())
    columns = ', '.join(db_record.model_dump().keys())
    placeholders = ', '.join([':{}'.format(k) for k in db_record.model_dump().
keys()])
    query_insert = text(f"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})")
    conn.execute(query_insert, db_record.model_dump())
    conn.commit()
    conn.close()
    return db_record
