=== MAIN GEMA ===
/api/songs")
def get_songs(nur_gema: bool = False, db: Session = Depends(get_db)):
    query = db.query(models.Song)
    if nur_gema:
        query = query.filter(models.Song.gema_pflichtig == True)
    return query.order_by(models.Song.titel.asc()).all()

@app.post("/api/songs")
def create_song(song: SongCreate, db: Session = Depends(get_db)):
    db_song = models.Song(**song.model_dump())
    db.add(db_song)
    db.commit()
    db.refresh(db_song)
    return db_song

@app.delete("/api/songs/{song_id}")
def delete_song(song_id: int, db: Session = Depends(get_db)):
    song = db.query(models.Song).filter(models.Song.id == song_id).first()
    if not song:
        return {"error": "Song nicht gefunden"}
    
    setlists = db.query(models.Setlist).all()
    for sl in setlists:
        ids = json.loads(sl.song_ids_json or "[]")
        if song_id in ids:
            sl.song_ids_json = json.dumps([i for i in ids if i != song_id])

    db.delete(song)
    db.commit()
    return {"status": "Song gelöscht"}

@app.get("/api/setlists")
def get_setlists(db: Session = Depends(get_db)):
    setlists = db.query(models.Setlist).order_by(models.Setlist.datum.desc()).all()
    alle_songs = {s.id: s for s in db.query(models.Song).all()}
    
    ergebnis = []
    for sl in setlists:
        ids = json.loads(sl.song_ids_json or "[]")
        songs_in_list = [alle_songs[i] for i in ids if i in alle_songs]
        gesamt_sek = sum(s.dauer_sekunden for s in songs_in_list)
        gema_anzahl = sum(1 for s in songs_in_list if s.gema_pflichtig)
        ergebnis.append({
            "id": sl.id,
            "name": sl.name,
            "datum": sl.datum,
            "veranstalter_ort": sl.veranstalter_ort,
            "songs": songs_in_list,
            "gesamt_minuten": f"{gesamt_sek // 60}:{gesamt_sek % 60:02d}",
            "gema_anzahl": gema_anzahl
        })
    return ergebnis

@app.post("/api/setlists")
def create_setlist(sl: SetlistCreate, db: Session = Depends(get_db)):
    db_sl = models.Setlist(
        name=sl.name,
        datum=sl.datum,
        veranstalter_ort=sl.veranstalter_ort,
        song_ids_json=json.dumps(sl.song_ids)
    )
    db.add(db_sl)
    db.commit()
    db.refresh(db_sl)
    return db_sl

@app.get("/api/setlists/{setlist_id}/gema-export")
def export_gema_musikfolge(setlist_id: int, db: Session = Depends(get_db)):
    sl = db.query(models.Setlist).filter(models.Setlist.id == setlist_id).first()
    alle_songs = {s.id: s for s in db.query(models.Song).all()}
    ids = json.loads(sl.song_ids_json or "[]")
    
    output = io.StringIO()
    writer = csv.writer(output, delimiter=";")
    writer.writerow(["Lfd. Nr.", "Werktitel", "Komponist", "Textdichter", "Verlag", "GEMA-Werknummer / ISWC", "Spieldauer"])
    
    nr = 1
    for sid in ids:
        song = alle_songs.get(sid)
        if song and song.gema_pflichtig:
            dauer_str = f"{song.dauer_sekunden // 60}:{song.dauer_sekunden % 60:02d}"
            writer.writerow([
                nr,
                song.titel,
                song.komponist,
                song.textdichter or song.komponist,
                song.verlag or "",
                song.gema_werknummer or "",
                dauer_str
            ])
            nr += 1

    csv_inhalt = output.getvalue().encode("utf-8-sig")
    dateiname = f"GEMA_Musikfolge_{sl.datum}_{sl.name.replace(' ', '_')}.csv"
    
    with open(os.path.join("storage", "gema", dateiname), "wb") as f:
        f.write(csv_inhalt)

    return StreamingResponse(
        io.BytesIO(csv_inhalt),
        media_type="text/csv",
        headers={"Content-Disposition": f"attachment; filename={dateiname}"}
    )

# --- E-MAIL CENTER ---
def _lade_mail_config():
    if not os.path.exists(MAIL_CONFIG_FILE):
        return None
    with open(MAIL_CONFIG_FILE, "r", encoding="utf-8") as f:
        return json.load(f)

def _decode_mime_words(s):
    if not s:
        return ""
    decoded_fragments = decode_header(s)
    result = ""
    for fragment, encoding in decoded_fragments:
        if isinstance(fragment, bytes):
            result += fragment.decode(encoding or "utf-8", errors="replace")
        else:
            result += fragment
    return result

@app.get("/api/mail/config")
def get_mail_config():
    cfg = _lade_mail_config()
    if not cfg:
        return {"konfiguriert": False}
    return {
        "konfiguriert": True,
        "email_adresse": cfg.get("email_adresse", ""),
        "imap_server": cfg.get("imap_s

=== HTML GEMA ===
id="gema" class="tab-section">
            <div class="grid-2">
                <div class="card">
                    <h3>➕ Song in Repertoire & GEMA-Pool aufnehmen</h3>
                    <form onsubmit="speichereSong(event)">
                        <input type="text" id="songTitel" placeholder="Songtitel *" required>
                        <input type="text" id="songKomponist" placeholder="Komponist(en) * (für GEMA-Musikfolge)" required>
                        <input type="text" id="songTextdichter" placeholder="Textdichter(in) (falls abweichend)">
                        <div class="grid-2">
                            <input type="text" id="songVerlag" placeholder="Verlag (optional)">
                            <input type="text" id="songWerkNr" placeholder="GEMA-Werk-Nr. / ISWC">
                            <input type="text" id="songDauer" placeholder="Dauer (z. B. 3:45)" value="3:30" required>
                            <input type="text" id="songTonart" placeholder="Tonart (z. B. Am / E)">
                        </div>
                        <label style="display:flex; align-items:center; gap:0.5rem; margin-top:0.3rem; cursor:pointer;">
                            <input type="checkbox" id="songGemaPflichtig" checked style="width:18px; height:18px;">
                            <span><strong>GEMA-pflichtiger Titel</strong> (erscheint automatisch auf GEMA-Setlists)</span>
                        </label>
                        <button type="submit" class="primary">Song speichern</button>
                    </form>
                </div>

                <div class="card">
                    <h3>📋 Neue Setlist / GEMA-Musikfolge zusammenstellen</h3>
                    <form onsubmit="speichereSetlist(event)">
                        <div style="display:flex; gap:0.5rem;">
                            <select id="gigVorlage" onchange="uebernehmeGigDaten()" style="flex:1;">
                                <option value="">-- Optional: Gig aus Kalender übernehmen --</option>
                            </select>
                        </div>
                        <input type="text" id="slName" placeholder="Setlist-Name / Veranstaltung *" required>
                        <div class="grid-2">
                            <input type="date" id="slDatum" required>
                            <input type="text" id="slOrt" placeholder="Location / Veranstalter">
                        </div>
                        
                        <label style="font-size:0.85rem; color:var(--muted); margin-top:0.4rem;">Songs für diese Setlist anklicken (in Spielreihenfolge):</label>
                        <div id="songAuswahlPool" style="max-height:180px; overflow-y:auto; background:#121417; border:1px solid var(--border); border-radius:6px; padding:0.5rem;"></div>
                        <div id="gewaehlteSongsVorschau" style="font-size:0.85rem; color:#4ade80; min-height:1.4rem;"></div>
                        
                        <button type="submit" class="primary">Setlist speichern</button>
                    </form>
                </div>
            </div>

            <div class="card">
                <h3>Gespeicherte Setlists & GEMA-Musikfolgen</h3>
                <div id="setlistsContainer"></div>
            </div>

            <div class="card">
                <div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:0.5rem;">
                    <h3>Song-Verwaltung (Repertoire & GEMA-Status)</h3>
                    <select id="songFilter" onchange="ladeSongs()">
                        <option value="alle">Alle Songs anzeigen</option>
                        <option value="gema">Nur GEMA-pflichtige Songs</option>
                    </select>
                </div>
                <table>
                    <thead><tr><th>Status</th><th>Titel</th><th>Komponist / Text</th><th>Werk-Nr.</th><th>Dauer</th><th>Tonart</th><th>Aktion</th></tr></thead>
                    <tbody id="songListe"></tbody>
                </table>
            </div>
        </section>

        <!-- BEREICH 3: FINANZEN, PDF-RECHNUNGEN & FINANZAMT -->
        <section 