from flask import Flask, render_template, jsonify, request, redirect, url_for, Response
import json
import os
import time

app = Flask(__name__, static_folder='static')

DATEN_DATEI = "session_daten.json"
FUELLWOERTER_DATEI = "fuellwoerter.json"

def lade_daten():
    if os.path.exists(DATEN_DATEI):
        with open(DATEN_DATEI, "r", encoding="utf-8") as f:
            return json.load(f)
    return {"status": "wartend", "sessions": [], "fehler": None}

def lade_fuellwoerter():
    if os.path.exists(FUELLWOERTER_DATEI):
        with open(FUELLWOERTER_DATEI, "r", encoding="utf-8") as f:
            return json.load(f)
    return ["äh", "ähm", "ehm", "mhm", "hm", "halt", "also", "sozusagen", "irgendwie"]

def speichere_fuellwoerter(woerter):
    with open(FUELLWOERTER_DATEI, "w", encoding="utf-8") as f:
        json.dump(woerter, f, ensure_ascii=False, indent=2)

@app.route("/")
def index():
    daten = lade_daten()
    fuellwoerter = lade_fuellwoerter()
    return render_template("dashboard.html", daten=daten, fuellwoerter=fuellwoerter)

@app.route("/api/daten")
def api_daten():
    return jsonify(lade_daten())

@app.route("/stream")
def stream():
    def event_stream():
        letzter_stand = None
        while True:
            daten = lade_daten()
            aktueller_stand = json.dumps(daten, ensure_ascii=False)
            if aktueller_stand != letzter_stand:
                letzter_stand = aktueller_stand
                yield f"data: {aktueller_stand}\n\n"
            time.sleep(1)
    return Response(event_stream(), mimetype="text/event-stream")

@app.route("/fuellwort/hinzufuegen", methods=["POST"])
def fuellwort_hinzufuegen():
    woerter = lade_fuellwoerter()
    neues_wort = request.form.get("wort", "").strip().lower()
    if neues_wort and neues_wort not in woerter:
        woerter.append(neues_wort)
        speichere_fuellwoerter(woerter)
    return redirect(url_for("index"))

@app.route("/fuellwort/entfernen/<wort>")
def fuellwort_entfernen(wort):
    woerter = lade_fuellwoerter()
    if wort in woerter:
        woerter.remove(wort)
        speichere_fuellwoerter(woerter)
    return redirect(url_for("index"))

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True, threaded=True)
