import os
import sqlite3

def read_file_with_fallback(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            return file.read()
    except UnicodeDecodeError:
        with open(file_path, 'r', encoding='latin-1') as file:
            return file.read()

def import_folders_to_db(base_folder_path, db_name):
    # Delete the existing database file if it exists
    if os.path.exists(db_name):
        os.remove(db_name)
    
    conn = sqlite3.connect(db_name)
    cursor = conn.cursor()

    for folder_name in os.listdir(base_folder_path):
        folder_path = os.path.join(base_folder_path, folder_name)
        if os.path.isdir(folder_path):
            table_name = folder_name.replace('-', '_').replace(' ', '_')
            cursor.execute(f"CREATE TABLE IF NOT EXISTS {table_name} (file_name TEXT, content TEXT)")
            
            for file_name in os.listdir(folder_path):
                file_path = os.path.join(folder_path, file_name)
                if os.path.isfile(file_path):
                    content = read_file_with_fallback(file_path)
                    cursor.execute(f"INSERT INTO {table_name} (file_name, content) VALUES (?, ?)", (file_name, content))
    
    conn.commit()
    conn.close()

# Use the current folder
base_folder_path = os.getcwd()
db_name = 'OBI-ONE.db'

# Import the text files from the folders in the current directory into the SQLite database
import_folders_to_db(base_folder_path, db_name)
