import mysql.connector
import os
from db import DB_CONFIG

def reseed_database():
    try:
        conn = mysql.connector.connect(**DB_CONFIG)
        cursor = conn.cursor()
        
        # Disable foreign key checks to truncate properly
        cursor.execute("SET FOREIGN_KEY_CHECKS = 0;")
        cursor.execute("TRUNCATE TABLE materials;")
        cursor.execute("TRUNCATE TABLE services;")
        cursor.execute("SET FOREIGN_KEY_CHECKS = 1;")
        
        # Re-run schema.sql seeds
        schema_path = os.path.join(os.path.dirname(__file__), "schema.sql")
        with open(schema_path, "r", encoding="utf-8") as f:
            sql_commands = f.read().split(";")
            
        for command in sql_commands:
            cmd = command.strip()
            if cmd.startswith("INSERT"):
                try:
                    cursor.execute(cmd)
                except mysql.connector.Error as e:
                    print(f"Error seeding: {e}")
        
        conn.commit()
        print("Database re-seeded successfully with localized keys")
        
    except mysql.connector.Error as err:
        print(f"Error: {err}")
    finally:
        if 'conn' in locals() and conn.is_connected():
            cursor.close()
            conn.close()

if __name__ == "__main__":
    reseed_database()
