defmodule Symbiont.Application do
  @moduledoc """
  OTP Application for Symbiont — the self-sustaining AI orchestrator.

  Supervision tree:
    Symbiont.Supervisor
    ├── Task.Supervisor (Symbiont.TaskSupervisor)
    ├── Symbiont.Ledger        — append-only cost log
    ├── Symbiont.Queue         — persistent task queue
    ├── Symbiont.Heartbeat     — periodic health checks + queue processing
    └── Bandit (Symbiont.API)  — HTTP API (skipped when port=0)
  """
  use Application

  @impl true
  def start(_type, _args) do
    data_dir = Application.get_env(:symbiont, :data_dir, "data")
    File.mkdir_p!(data_dir)

    port = Application.get_env(:symbiont, :port, 8111)

    base_children = [
      {Task.Supervisor, name: Symbiont.TaskSupervisor},
      {Symbiont.Ledger, data_dir: data_dir},
      {Symbiont.Queue, data_dir: data_dir},
      {Symbiont.Heartbeat, []}
    ]

    children =
      if port > 0 do
        base_children ++ [{Bandit, plug: Symbiont.API, port: port, scheme: :http}]
      else
        base_children
      end

    opts = [strategy: :rest_for_one, name: Symbiont.Supervisor]
    Supervisor.start_link(children, opts)
  end
end
