import os
from dotenv import load_dotenv
import pymysql

load_dotenv()

db_uri = os.environ.get('DATABASE_URI')
uri = db_uri.replace('mysql+pymysql://', '')
auth, rest = uri.split('@')
user, password = auth.split(':')
host, db_name = rest.split('/')

print("Importing database.sql into", db_name)
conn = pymysql.connect(host=host, user=user, password=password, database=db_name)

try:
    with conn.cursor() as cursor:
        with open('database.sql', 'r') as f:
            sql_script = f.read()
            
        # Very simple parser - might break on semicolons inside strings!
        # But this is generated by SQLAlchemy, so it's usually safe-ish.
        # Let's use a safer approach since PyMySQL can run multiple statements anyway?
        # No, PyMySQL execute() usually runs 1 statement. To run multiple, we could just split.
        commands = sql_script.split(';\n')
        for idx, cmd in enumerate(commands):
            cmd = cmd.strip()
            if cmd:
                try:
                    cursor.execute(cmd)
                except Exception as e:
                    with open('error.log', 'w') as err_file:
                        err_file.write(f"Error on command {idx}: {e}\n\n[SQL]:\n{cmd}")
                    print(f"Failed. See error.log")
                    raise e
    conn.commit()
    print("Import complete.")
finally:
    conn.close()
