import os
from sqlalchemy import create_engine, text
import bcrypt

from dotenv import load_dotenv
load_dotenv()

DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./insurance.db")
engine = create_engine(DATABASE_URL)

def hash_password(password: str) -> str:
    salt = bcrypt.gensalt()
    return bcrypt.hashpw(password.encode('utf-8'), salt).decode('utf-8')

with engine.begin() as conn:
    for email in ['admin@mail.com', 'testadmin2@insuranceborder.com']:
        res = conn.execute(text("SELECT email, password_hash, role FROM users WHERE email=:email"), {"email": email}).fetchone()
        if res:
            email, pwd_hash, role = res
            print(f"User: {email}, Role: {role}")
            matched = False
            try:
                matched = bcrypt.checkpw("Secure@Password123".encode('utf-8'), pwd_hash.encode('utf-8'))
            except Exception as e:
                print("Bcrypt check failed:", e)
            print("Does password 'Secure@Password123' match?", matched)
            
            if not matched:
                new_hash = hash_password("Secure@Password123")
                conn.execute(text("UPDATE users SET password_hash = :h WHERE email = :email"), {"h": new_hash, "email": email})
                print(f"Password for {email} updated to 'Secure@Password123'")
        else:
            print(f"{email} not found!")
