import pyodbc
from datetime import datetime, timedelta, timezone

def get_changes_tables(schema: str, begin_time: str, end_time: str, cursor: pyodbc.Cursor) -> list[str]:
    """
    Retrieve a list of table names that have changes within a specified time range for a given schema.

    :param schema: Name of the database schema to check for changes (e.g., 'records')
    :param begin_time: Start timestamp for the change window (as a string)
    :param end_time: End timestamp for the change window (as a string)
    :param cursor: Active pyodbc cursor to execute the stored procedure
    :return: List of table names that have recorded changes during the specified time window
    """

    query = f"""
        EXEC axon.usp_GetTablesHaveChanges N'{begin_time}', N'{end_time}', N'{schema}'
        """
    tables = []
    try:
        cursor.execute(query)
        tables = [row.TableName for row in cursor.fetchall()]
    except Exception as e:
        print(f"Error fetching tables have changes: {e}")

    return tables
    
def fetch_columns_in_a_table(schema: str, table: str, cursor: pyodbc.Cursor):
    """
    Fetches the list of column names from the specified schema and table.

    :param schema: The schema name.
    :param table: The table name.
    :return: A list of column names.
    """
    query = """
        SELECT COLUMN_NAME
        FROM axon.uf_GetTableColumns(?, ?)
    """
    columns = []
    try:
        cursor.execute(query, (schema, table))
        columns = [row.COLUMN_NAME for row in cursor.fetchall()]
    except Exception as e:
        print(f"Error fetching columns: {e}")

    return columns


def fetch_primary_keys(schema: str, table: str, cursor: pyodbc.Cursor):
    """
    Fetches the list of primary key column names from the specified schema and table.

    :param schema: The schema name.
    :param table: The table name.
    :return: A list of primary key column names.
    """
    query = """
          select PRIMARY_KEY_COLUMN as COLUMN_NAME from axon.uf_GetPrimaryKeyColumns(?, ?)
    """

    primary_keys = []
    try:
        cursor.execute(query, (schema, table))
        primary_keys = [row.COLUMN_NAME for row in cursor.fetchall()]
    except Exception as e:
        print(f"Error fetching primary keys: {e}")

    return primary_keys


def concatenate_table_name_and_schema_name(schema: str, table: str) -> str:
    """
    Format a fully qualified table name with the given schema and table.

    :param schema: The name of the database schema (e.g., 'records')
    :param table: The name of the table
    :return: A string representing the fully qualified table name, e.g., '[records].[EntCase]'
    """
    return f"[{schema}].[{table}]"


def format_sql_value(row_data):
    """
    Format a column value for use in a SQL statement.

    :param row_data: The value from a table row (can be any type or None)
    :return: A string representation of the value; returns 'null' if None, otherwise wraps the value in single quotes
    """
    value = row_data
    if value is None:
        return 'null'

    return f"'{value}'"


def main() -> None:
    """
    Get DataStore Configs
    """
    datastore_conn_str = "<datastore_conn_str>"
    user_conn_str = "<user_conn_str>"

    datastore_conn = pyodbc.connect(datastore_conn_str)
    datastore_cursor = datastore_conn.cursor()

    user_conn = pyodbc.connect(user_conn_str)
    user_cursor = user_conn.cursor()


    """
    Example for time range
    From yesterday to now
    """
    begin_time_utc = datetime.now(timezone.utc) - timedelta(days=1)
    begin_time = begin_time_utc.strftime('%Y-%m-%d %H:%M:%S')

    end_time_utc = datetime.now(timezone.utc)
    end_time = end_time_utc.strftime('%Y-%m-%d %H:%M:%S')

    # Schema name in DataStore
    schema_name = 'RECORDS'

    # Schema name in User Database
    user_schema_name = 'RECORDS'

    tables = get_changes_tables(schema_name, begin_time, end_time, datastore_cursor)
    for table_name in tables:
        user_table_name = table_name
        columns = fetch_columns_in_a_table(schema_name, table_name, datastore_cursor)
        primary_keys = fetch_primary_keys(schema_name, table_name, datastore_cursor)
        num_primary_keys = len(primary_keys)

        statement = f"EXECUTE axon.usp_PullDataByRange N'{begin_time}', N'{end_time}', N'{schema_name}', N'{table_name}'"
        datastore_cursor.execute(statement)
        data = datastore_cursor.fetchall()

        for row in data:
            try:
                key_values = {}
                for i in range(num_primary_keys):
                    name_pattern = f"PK_Column{i + 1}Name"
                    value_pattern = f"PK_Column{i + 1}Value"
                    key_values[getattr(row, name_pattern, None)] = getattr(row, value_pattern, None)
                prepare_where_statement = " AND ".join([f"{name}='{key_values[name]}'" for name in key_values])
                prepare_statement = f"""SELECT {', '.join(columns)} FROM [{schema_name}].[{table_name}] WHERE ({prepare_where_statement})"""

                datastore_cursor.execute(prepare_statement)

                row_data = datastore_cursor.fetchone()
                operation = getattr(row, 'OperationType', None)

                """
                Execute in User Database
                """
                if operation == 'UPSERT':
                    column_names_without_primary_keys = datastore_cursor.description[len(primary_keys):]
                    upsert_perpare_statement = f"""
                    IF EXISTS(SELECT 1 FROM {concatenate_table_name_and_schema_name(user_schema_name, user_table_name)}
                                WHERE  ({prepare_where_statement}))
                        BEGIN
                        UPDATE {concatenate_table_name_and_schema_name(user_schema_name, user_table_name)}
                            SET {", ".join([f"{column_name[0]}={format_sql_value(getattr(row_data, column_name[0]))}" for column_name in column_names_without_primary_keys])}
                            WHERE ({prepare_where_statement})
                        END
                    ELSE
                        INSERT INTO {concatenate_table_name_and_schema_name(user_schema_name, user_table_name)} ({', '.join([column[0] for column in datastore_cursor.description])}) 
                        VALUES ({", ".join([f"{format_sql_value(i)}" for i in row_data])})
                    """
                    user_cursor.execute(upsert_perpare_statement)
                    user_cursor.commit()
                elif operation == "DELETE":
                    delete_prepare_statement = f"""
                        DELETE FROM {concatenate_table_name_and_schema_name(user_schema_name, user_table_name)}
                        WHERE ({prepare_where_statement})
                    """
                    user_cursor.execute(delete_prepare_statement)
                    user_cursor.commit()
            except Exception as e:
                print(f"SKIPPING - Error while running row data with {prepare_where_statement} - table {table_name} - primary keys value {key_values} - err:", str(e))
    print(f"DONE INCREMENTAL PULLING FROM {begin_time} TO {end_time}")


if __name__ == '__main__':
    main()