from sqlalchemy import create_engine
from .models import DbBaseModel
from pydantic import BaseModel
import requests
from sqlalchemy import create_engine
import pandas as pd

def create_configured_db_engine(db_name: str):
    """Create a configured database engine.

    Parameters
    ----------
    db_name: str :
        The name of the database.

    Returns
    -------
    Connection :
        A connection to the database.
    """
    engine = create_engine(f'sqlite:///{db_name}.db')
    return engine.connect()

def create_pydantic_record(record_class: BaseModel, row: tuple) -> DbBaseModel:
    """
    Create a Pydantic record from a database row.

    Parameters
    ----------
    record_class: BaseModel :
        The Pydantic model class corresponding to the database table.
    row: tuple :
        A tuple representing a row from the database table.

    Returns
    -------
    DbBaseModel :
        A Pydantic model instance representing the database record.
    """
    record = dict(zip(record_class.model_json_schema()["properties"].keys(), (row[0],)+row[2:]))
    record['id'] = row[1]
    return DbBaseModel(**record)

def init_table_from_get_url(db_name: str, table_name: str, url: str):
    """Create a table in a sqlite database from data fetched via a GET request.

    Parameters
    ----------
    db_name: str :
        The name of the database.
    table_name: str :
        The name of the table to initialize.
    url: str :
        The URL to fetch data from.

    Returns
    -------
    None
    """
    engine = create_engine(f'sqlite:///{db_name}.db')

    # Remplir la base de données sqlite avec les données posts
    response = requests.get(url)
    data = response.json()
    df = pd.DataFrame(data)
    df.to_sql(name=table_name, con=engine, if_exists='replace', index=False)