defmodule MatchmakingEx do
  @moduledoc """
  A robust, OTP-based matchmaking system in Elixir.

  This library provides the core components for a fault-tolerant matchmaking service,
  built on core OTP principles like GenServer and DynamicSupervisor.

  ## Core Components

  - `MatchmakingEx.Server`: The central queue where players wait for a match. It is responsible for pairing compatible players.
  - `MatchmakingEx.Player`: A GenServer process representing each individual player, handling their state and communication with the system.
  - `MatchmakingEx.PendingMatch`: A temporary, supervised process that manages the two-way confirmation phase once a potential match is found. It lives only for the duration of the confirmation.
  - `MatchmakingEx.CooldownManager`: A dedicated GenServer that manages penalties for players who decline matches, preventing them from immediately re-joining the queue.

  ## System Workflow

  The matchmaking process follows these steps:

  1.  **Start Player Process**: For each user, a `MatchmakingEx.Player` process is started via `MatchmakingEx.Player.start_link/1`. This gives them an entry point into the matchmaking system.

  2.  **Search for Match**: The player initiates a search using `MatchmakingEx.Player.search/2`. They can optionally provide filters (e.g., `%{rank: "gold", mode: "2v2"}`). This function checks if the player is on cooldown before proceeding.

  3.  **Queueing & Pairing**: The `MatchmakingEx.Server` receives the search request. It scans its queue for a compatible opponent based on the provided filters.
      - If no opponent is found, the player is added to the queue.
      - If a compatible opponent is found, both players are removed from the queue, and a new `PendingMatch` process is created for them.

  4.  **Match Confirmation**: The newly created `PendingMatch` process notifies both players that a match is ready. They have a limited time to respond with `accept` or `decline`.

  5.  **Resolution**:
      - **Confirmed**: If both players `accept`, they are notified of the confirmed match, and the `PendingMatch` process terminates normally.
      - **Declined**: If either player `declines`, the match is cancelled. The declining player is put on a cooldown by the `CooldownManager`. The other player is re-queued by the `Server`. The `PendingMatch` process terminates.
      - **Timeout**: If the confirmation timer runs out, the match is cancelled. Any player who had already accepted is re-queued. The `PendingMatch` process terminates.
  """
end
