"""
Seed the database with initial batteries and devices.
Safe to run multiple times — exits early if data already exists.
"""

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

import config
from models import Base, Battery, Device


def seed():
    engine = create_engine(config.SQLALCHEMY_DATABASE_URI, pool_pre_ping=True)
    Base.metadata.create_all(engine)
    Session = sessionmaker(bind=engine)
    db = Session()

    if db.query(Battery).count() > 0:
        print("Database already seeded — skipping.")
        db.close()
        return

    # --- Devices ---
    device_specs = [
        ("RC Car",      4),
        ("TV Remote",   2),
        ("Flashlight",  3),
        ("Kids Toy 1",  3),
        ("Kids Toy 2",  2),
    ]
    devices = []
    for name, slots in device_specs:
        d = Device(name=name, battery_slots=slots)
        db.add(d)
        devices.append(d)

    # --- Batteries ---
    battery_specs = [
        ("ENL", "Panasonic Eneloop", 16),
        ("BON", "BONAI",             16),
        ("ENR", "Energizer NiMH",     8),
    ]
    for prefix, brand, count in battery_specs:
        for i in range(1, count + 1):
            label = f"{prefix}-{i:02d}"
            db.add(Battery(label=label, brand=brand, status="available"))

    db.commit()
    db.close()

    total = sum(c for _, _, c in battery_specs)
    print(f"Seeded {len(device_specs)} devices and {total} batteries.")


if __name__ == "__main__":
    seed()
