import mysql.connector
import os
import sys

# Add parent dir to path to import db
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from db import DB_CONFIG

def reset_and_seed():
    try:
        conn = mysql.connector.connect(**DB_CONFIG)
        cursor = conn.cursor()
        
        print("Dropping tables...")
        cursor.execute("SET FOREIGN_KEY_CHECKS = 0;")
        tables = ["order_photos", "order_files", "orders", "password_reset_tokens", "users", "services", "materials", "posts"]
        for table in tables:
            cursor.execute(f"DROP TABLE IF EXISTS {table};")
        cursor.execute("SET FOREIGN_KEY_CHECKS = 1;")
        
        print("Running schema.sql...")
        schema_path = os.path.join(os.path.dirname(__file__), "schema.sql")
        with open(schema_path, "r", encoding="utf-8") as f:
            # We need to split by semicolon, but be careful with multi-line statements
            sql = f.read()
            # A simple split by ; works if there are no semicolons inside strings
            sql_commands = sql.split(";")
            
        for command in sql_commands:
            cmd = command.strip()
            if cmd:
                try:
                    cursor.execute(cmd)
                except Exception as e:
                    # Skip database creation if exists
                    if "database exists" not in str(e).lower():
                        print(f"Error in command: {cmd[:50]}... -> {e}")
        
        conn.commit()
        print("Database reset and seeded successfully.")

        # Seed portfolio images
        try:
            from seed_portfolio import seed_portfolio
            seed_portfolio()
        except Exception as e:
            print(f"Portfolio seeding failed: {e}")
        
    except Exception as e:
        print(f"Error: {e}")
    finally:
        if 'conn' in locals() and conn.is_connected():
            cursor.close()
            conn.close()

if __name__ == "__main__":
    reset_and_seed()
