from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models.models import Event, EventMedia, EventType, Client
from dotenv import load_dotenv
import os
from datetime import datetime, timedelta
import random

# .env laden
load_dotenv()

DB_USER = os.getenv("DB_USER")
DB_PASSWORD = os.getenv("DB_PASSWORD")
DB_HOST = os.getenv("DB_HOST")
DB_NAME = os.getenv("DB_NAME")

db_conn_str = f"mysql+pymysql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}/{DB_NAME}"
engine = create_engine(db_conn_str)
Session = sessionmaker(bind=engine)
session = Session()

now = datetime.now()


def random_time_on_day(day_offset: int, duration_hours: int = 1):
    """Erzeugt eine zufällige Start- und Endzeit zwischen 8 und 16 Uhr für einen Tag."""
    start_hour = random.randint(8, 15 - duration_hours + 1)
    start = (now + timedelta(days=day_offset)).replace(hour=start_hour,
                                                       minute=0, second=0, microsecond=0)
    end = start + timedelta(hours=duration_hours)
    return start, end


# Hole alle Clients aus der Datenbank
clients = session.query(Client).all()
created_by = 1  # Passe ggf. an

all_events = []

for client in clients:
    for i in range(10):
        day_offset = random.randint(0, 13)  # Termine in den nächsten 14 Tagen
        duration = random.choice([1, 2])    # 1 oder 2 Stunden
        start, end = random_time_on_day(day_offset, duration)
        event = Event(
            client_uuid=client.uuid,
            title=f"Termin {i+1} für {client.location or client.uuid[:8]}",
            description=f"Automatisch generierter Termin {i+1} für Client {client.uuid}",
            start=start,
            end=end,
            event_type=random.choice(list(EventType)),
            created_by=created_by,
            updated_by=None,
            is_active=True
        )
        all_events.append(event)

# Events speichern
for event in all_events:
    session.add(event)
session.commit()

print(f"{len(all_events)} Termine für {len(clients)} Clients wurden angelegt.")
