from sqlmodel import Session, select
from app.core.database import engine
from app.models.user import User, UserRole, DriverProfile, VehicleType
from app.models.telemetry import Telemetry, VehicleStatus
from app.core.security import get_password_hash
from datetime import datetime

def seed_users():
    users_to_create = [
        {
            "email": "admin@sibu.com",
            "password": "admin",
            "full_name": "Administrador Sistema",
            "role": UserRole.ADMIN
        },
        {
            "email": "promo@sibu.com",
            "password": "promo",
            "full_name": "Promotor de Negocios",
            "role": UserRole.PROMOTER
        },
        {
            "email": "usuario@sibu.com",
            "password": "usuario",
            "full_name": "Usuario Pasajero",
            "role": UserRole.PASSENGER
        },
        {
            "email": "conductor@sibu.com",
            "password": "conductor",
            "full_name": "Juan Perez (Conductor)",
            "role": UserRole.DRIVER
        }
    ]

    with Session(engine) as session:
        for u_data in users_to_create:
            existing = session.exec(select(User).where(User.email == u_data["email"])).first()
            if existing:
                print(f"User {u_data['email']} already exists. Updating password and role.")
                existing.hashed_password = get_password_hash(u_data["password"])
                existing.role = u_data["role"]
                session.add(existing)
                session.commit()
                session.refresh(existing)
                user = existing
            else:
                user = User(
                    email=u_data["email"],
                    full_name=u_data["full_name"],
                    hashed_password=get_password_hash(u_data["password"]),
                    role=u_data["role"],
                    is_active=True,
                    is_verified=True
                )
                session.add(user)
                session.commit()
                session.refresh(user)
                print(f"Created user: {u_data['email']}")
            
            # If it's a driver, ensure they have a profile
            if user.role == UserRole.DRIVER:
                profile = session.exec(select(DriverProfile).where(DriverProfile.user_id == user.id)).first()
                if not profile:
                    profile = DriverProfile(
                        user_id=user.id,
                        cedula="8-000-0000",
                        vehicle_type=VehicleType.BUS,
                        license_plate="BUS-1234",
                        cooperative_name="Cooperativa David-Boquete",
                        shift="Mañana",
                        speaks_english=True
                    )
                    session.add(profile)
                    print(f"Created driver profile for {user.email}")
                
                # Add sample telemetry for the driver (near David/Boquete area)
                # David coordinates approx: 8.43, -82.43
                telemetry = Telemetry(
                    user_id=user.id,
                    latitude=8.435,
                    longitude=-82.428,
                    status=VehicleStatus.ACTIVE,
                    speed=0.0,
                    heading=0.0,
                    timestamp=datetime.utcnow()
                )
                session.add(telemetry)
                print(f"Added sample telemetry for driver {user.email}")
        
        session.commit()
    print("User seeding completed successfully.")

if __name__ == "__main__":
    seed_users()
