import uuid


def get_or_create_session_id(visit_id, sqlite_db):
    """Gets or creates a new session UUID given a Piwik visit ID.

    :param visit_id: Piwik visit ID from current row in database
    :param sqlite_db: SQLite3 database handle
    :return: session UUID as str
    """
    cursor = sqlite_db.cursor()
    query = "SELECT session_id FROM session_ids WHERE visit_id='{p_id}'".format(p_id=str(visit_id))
    cursor.execute(query)

    session_ids = cursor.fetchall()

    if len(session_ids) > 1:
        raise Exception("Multiple session ID\'s found for single Piwik visit ID")

    if session_ids:
        return str(session_ids[0][0])

    session_uuid = str(uuid.uuid4())
    query = "INSERT INTO session_ids (visit_id, session_id) VALUES ('{visit}', '{session}');".format(
        visit=str(visit_id), session=session_uuid
    )
    cursor.execute(query)
    sqlite_db.commit()
    return session_uuid