from flask import Blueprint, request, jsonify
from database import Session
from models.models import Event, EventMedia, MediaType
from datetime import datetime, timezone
from sqlalchemy import and_
import sys
sys.path.append('/workspace')

events_bp = Blueprint("events", __name__, url_prefix="/api/events")


@events_bp.route("", methods=["GET"])
def get_events():
    session = Session()
    start = request.args.get("start")
    end = request.args.get("end")
    # geändert: jetzt group_id statt client_uuid
    group_id = request.args.get("group_id")
    query = session.query(Event).filter(Event.is_active == True)
    if start and end:
        query = query.filter(and_(Event.start < end, Event.end > start))
    if group_id:
        # geändert: filter auf group_id
        query = query.filter(Event.group_id == int(group_id))
    events = query.all()
    result = []
    for e in events:
        result.append({
            "Id": str(e.id),
            "GroupId": e.group_id,  # geändert: gibt group_id zurück
            "Subject": e.title,
            "StartTime": e.start.isoformat() if e.start else None,
            "EndTime": e.end.isoformat() if e.end else None,
            "IsAllDay": False,
        })
    session.close()
    return jsonify(result)


@events_bp.route("/<event_id>", methods=["DELETE"])
def delete_event(event_id):
    session = Session()
    event = session.query(Event).filter_by(id=event_id).first()
    if not event:
        session.close()
        return jsonify({"error": "Termin nicht gefunden"}), 404
    session.delete(event)
    session.commit()
    session.close()
    return jsonify({"success": True})


@events_bp.route("", methods=["POST"])
def create_event():
    data = request.json
    session = Session()

    # Pflichtfelder prüfen
    required = ["group_id", "title", "description",
                "start", "end", "event_type", "created_by"]
    for field in required:
        if field not in data:
            return jsonify({"error": f"Missing field: {field}"}), 400

    event_type = data["event_type"]
    event_media_id = None
    slideshow_interval = None

    # Präsentation: event_media_id und slideshow_interval übernehmen
    if event_type == "presentation":
        event_media_id = data.get("event_media_id")
        slideshow_interval = data.get("slideshow_interval")
        if not event_media_id:
            return jsonify({"error": "event_media_id required for presentation"}), 400

    # Website: Webseite als EventMedia anlegen und ID übernehmen
    if event_type == "website":
        website_url = data.get("website_url")
        if not website_url:
            return jsonify({"error": "website_url required for website"}), 400
        # EventMedia für Webseite anlegen
        media = EventMedia(
            media_type=MediaType.website,
            url=website_url,
            file_path=website_url
        )
        session.add(media)
        session.commit()
        event_media_id = media.id

    # created_by aus den Daten holen, Default: None
    created_by = data.get("created_by")

    # Start- und Endzeit in UTC umwandeln, falls kein Zulu-Zeitstempel
    start = datetime.fromisoformat(data["start"])
    end = datetime.fromisoformat(data["end"])
    if start.tzinfo is None:
        start = start.astimezone(timezone.utc)
    if end.tzinfo is None:
        end = end.astimezone(timezone.utc)

    # Event anlegen
    event = Event(
        group_id=data["group_id"],
        title=data["title"],
        description=data["description"],
        start=start,
        end=end,
        event_type=event_type,
        is_active=True,
        event_media_id=event_media_id,
        slideshow_interval=slideshow_interval,
        created_by=created_by  # <--- HIER hinzugefügt
    )
    session.add(event)
    session.commit()
    return jsonify({"success": True, "event_id": event.id})
