import os
import sys
from sqlalchemy.orm import Session
from passlib.context import CryptContext
from ..database import SessionLocal
from .. import models

pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto")

def reset_admin():
    db = SessionLocal()
    try:
        username = "Admin"
        password = "Admin123!"
        hashed_password = pwd_context.hash(password)
        
        user = db.query(models.User).filter(models.User.username == username).first()
        if user:
            user.hashed_password = hashed_password
            user.role = "admin"
            print(f"✅ User '{username}' found. Password has been reset to: {password}")
        else:
            new_user = models.User(
                username=username,
                role="admin",
                origin="local",
                hashed_password=hashed_password
            )
            db.add(new_user)
            print(f"✅ User '{username}' not found. Created new admin with password: {password}")
            
        db.commit()
        print("💾 Changes saved to database.")
    except Exception as e:
        print(f"❌ Error resetting admin: {e}")
        db.rollback()
    finally:
        db.close()

if __name__ == "__main__":
    reset_admin()
