%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#4a90d9'}}}%%
flowchart TB
    subgraph Clients["Client Layer"]
        Browser["Web Browser<br/>(HTML/CSS/JS)"]
        CLI["CLI Client<br/>(Main.py)"]
    end

    subgraph Server["Server Layer (FastAPI)"]
        direction TB
        Middleware["Middleware<br/>Auth, Rate Limit, Error Handler"]
        
        subgraph API["API Routers"]
            AuthAPI["/api/auth"]
            AnimeAPI["/api/anime"]
            QueueAPI["/api/queue"]
            ConfigAPI["/api/config"]
            SchedulerAPI["/api/scheduler"]
            HealthAPI["/health"]
            WebSocketAPI["/ws"]
        end
        
        subgraph Services["Services"]
            AuthService["AuthService"]
            AnimeService["AnimeService"]
            DownloadService["DownloadService"]
            ConfigService["ConfigService"]
            ProgressService["ProgressService"]
            WebSocketService["WebSocketService"]
        end
    end

    subgraph Core["Core Layer"]
        SeriesApp["SeriesApp"]
        SeriesCache["SeriesCache<br/>(In-Memory)"]
        SerieScanner["SerieScanner"]
        SerieList["SerieList"]
    end

    subgraph Data["Data Layer"]
        SQLite[("SQLite<br/>aniworld.db")]
        ConfigJSON[(config.json)]
        FileSystem[(File System<br/>Anime Episodes)]
        LegacyFiles[("Legacy Files<br/>key/data<br/>(Deprecated)")]
    end

    subgraph External["External"]
        Provider["Anime Provider<br/>(aniworld.to)"]
    end

    %% Client connections
    Browser -->|HTTP/WebSocket| Middleware
    CLI -->|Direct| SeriesApp

    %% Middleware to API
    Middleware --> API

    %% API to Services
    AuthAPI --> AuthService
    AnimeAPI --> AnimeService
    QueueAPI --> DownloadService
    ConfigAPI --> ConfigService
    SchedulerAPI --> AnimeService
    WebSocketAPI --> WebSocketService

    %% Services to Core
    AnimeService --> SeriesApp
    DownloadService --> SeriesApp

    %% Services to Data
    AuthService --> ConfigJSON
    ConfigService --> ConfigJSON
    DownloadService --> SQLite
    AnimeService --> SQLite

    %% Core to Data
    SeriesApp --> SeriesCache
    SeriesCache -.->|Cached Series| SQLite
    SeriesApp --> SerieScanner
    SeriesApp --> SerieList
    SerieScanner -->|Scan Episodes| FileSystem
    SerieScanner -->|Detect Series| SQLite
    SerieScanner -->|Migrate Legacy| LegacyFiles
    SerieScanner --> Provider

    %% Event flow
    ProgressService -.->|Events| WebSocketService
    DownloadService -.->|Progress| ProgressService
    WebSocketService -.->|Broadcast| Browser
