flowchart TD
    A["HyprTile / overlay_ai"] -->|"TTS aktiv"| B["hyprtile-tts CLI"]
    B -->|"POST /tts"| C["llama-moss-tts-server"]

    C --> HTTP["HTTP Server"]
    HTTP --> Health["GET /health"]
    HTTP --> Voices["GET /voices"]
    HTTP --> TTS["POST /tts oder POST /"]
    HTTP --> Options["OPTIONS / CORS"]
    HTTP --> Shutdown["Shutdown Guard"]

    Health --> HealthJSON["JSON: ok, service, persistent_models"]
    Voices --> VoicesJSON["JSON: voices + default_voice"]

    TTS --> ParseReq["Request parsen"]
    ParseReq --> Text["text"]
    ParseReq --> Voice["voice / speaker"]
    ParseReq --> RefAudio["reference_audio"]
    ParseReq --> Language["language / Server Default"]
    ParseReq --> ErrorMissing["Fehler: missing text"]

    C --> Engine["moss_tts_engine"]

    Engine --> Config["server_config"]
    Config --> ModelPath["-m / --model"]
    Config --> EncoderPath["--audio-encoder-model"]
    Config --> DecoderPath["--audio-decoder-model"]
    Config --> DefaultRef["--reference-audio"]
    Config --> VoiceDir["--voice-dir"]
    Config --> DefaultVoice["--default-voice"]
    Config --> Lang["--language"]
    Config --> GPU["-ngl / GPU Layers"]
    Config --> Sampling["Sampling Parameter"]
    Config --> MaxTokens["--max-new-tokens"]
    Config --> Seed["--seed"]
    Config --> HostPort["--host / --port"]

    Engine --> Init["Engine Init"]
    Init --> LoadBackbone["MOSS Backbone einmal laden"]
    Init --> ReadVocab["Vocab + text_vocab"]
    Init --> DelayCfg["moss_delay_config aus GGUF-Metadaten"]
    Init --> LoadDecoder["Audio Decoder einmal laden"]
    Init --> DefaultRefEncode["Default Reference einmal encoden"]

    DefaultRefEncode --> AudioEncoder["moss-tts-audio-encoder GGUF"]
    AudioEncoder --> RefCodes["reference_codes + reference_frames Cache"]

    TTS --> Synth["moss_tts_engine_synth"]

    Synth --> VoiceResolve["Voice/Reference auflösen"]
    VoiceResolve --> ReqRef["Request reference_audio"]
    VoiceResolve --> VoiceID["voice/speaker -> Voice-Datei"]
    VoiceResolve --> DefaultVoiceResolve["default_voice -> Voice-Datei"]
    VoiceResolve --> DefaultCachedRef["cached default reference"]

    ReqRef --> Safety["Pfad prüfen / safe voice id"]
    VoiceID --> Safety
    DefaultVoiceResolve --> Safety

    Safety --> VoiceCache{"Voice bereits gecached?"}
    VoiceCache -->|"Nein"| EncodeVoice["Voice WAV encoden"]
    VoiceCache -->|"Ja"| UseVoiceCache["voice_code_cache verwenden"]

    EncodeVoice --> AudioEncoder
    AudioEncoder --> VoiceCodes["Voice reference codes"]
    VoiceCodes --> UseVoiceCache

    Synth --> PromptBuild["moss_build_prompt_input"]
    UseVoiceCache --> PromptBuild
    DefaultCachedRef --> PromptBuild
    Text --> PromptBuild
    Lang --> PromptBuild

    PromptBuild --> PackedPrompt["packed_ids"]
    PromptBuild --> PromptFrames["prompt_frames"]
    PromptBuild --> ReferenceFrames["reference_frames"]

    PackedPrompt --> Generate["moss_generate_from_prompt_loaded_model"]

    Generate --> InitDelayState["moss_init_delay_state"]
    InitDelayState --> DelayState["moss_delay_state"]
    DelayState --> TextHistory["text_history"]
    DelayState --> AudioHistory["audio_history"]
    DelayState --> Flags["is_audio / is_stopping / delayed_length"]

    Generate --> DecodeLoop["Generation Loop bis max_new_tokens"]
    DecodeLoop --> GetLogits["llama_get_logits_ith"]
    GetLogits --> SplitLogits["Text-Logits + Audio-Logits splitten"]
    SplitLogits --> DelayStep["moss_delay_step"]
    DelayStep --> TextSample["Text Token Sampling"]
    DelayStep --> AudioSample["Audio Code Sampling pro VQ-Kanal"]
    TextSample --> SamplingRules["temperature / top_p / top_k"]
    AudioSample --> SamplingRules
    AudioSample --> RepetitionPenalty["audio_repetition_penalty"]

    DelayStep --> PackedRow["nächste packed row"]
    PackedRow --> LlamaDecode["llama_decode"]
    LlamaDecode --> DecodeLoop

    DecodeLoop --> StopCheck{"is_stopping?"}
    StopCheck -->|"Nein"| DecodeLoop
    StopCheck -->|"Ja oder max tokens"| DecodeGenAudio["moss_decode_generation_audio"]

    DecodeGenAudio --> RawCodes["raw audio codes"]
    RawCodes --> AudioDecode["moss_decode_audio_llama_loaded_model"]

    AudioDecode --> DecoderModel["moss-tts-audio-decoder GGUF"]
    DecoderModel --> ValidateDecoder["sample_rate / downsample_rate / quantizers prüfen"]
    ValidateDecoder --> EncodeCodes["llama_encode Audio-Codes"]
    EncodeCodes --> Embeddings["Embeddings -> float audio samples"]
    Embeddings --> SaveWav["save_wav16"]

    SaveWav --> TempWav["temporäre WAV-Datei"]
    TempWav --> StreamResponse["stream_wav_response"]
    StreamResponse --> ClientWav["HTTP Response audio/wav"]
    ClientWav --> HyprtileTTS["hyprtile-tts spielt WAV ab"]
    HyprtileTTS --> AudioOut["Audioausgabe / paplay / aplay"]

    ErrorMissing --> ErrorJSON["HTTP 400 JSON"]
    Synth --> TryCatch["try/catch"]
    TryCatch --> ErrorTTS["HTTP 500 JSON bei TTS Fehler"]

    subgraph Persistent["Persistente Server-Vorteile"]
        P1["Backbone bleibt geladen"]
        P2["Audio Decoder bleibt geladen"]
        P3["Default Reference gecached"]
        P4["Voice Reference Codes gecached"]
        P5["Schneller als pro Request neu laden"]
    end

    Engine --> Persistent