defmodule A2aAgentWebWeb.StoryController do
  @moduledoc """
  Controller for generating stories using OpenAI.
  """
  use A2aAgentWebWeb, :controller

  @doc """
  POST /api/story
  Receives JSON {"text": ...} and returns a story generated by the LLM.
  """
  @spec create(Plug.Conn.t(), map()) :: Plug.Conn.t()
  def create(conn, %{"text" => text}) do
    graph = %{story: %{operator: A2aAgentWebWeb.Operators.LLMOperator, deps: []}}
    agent_map = %{}
    input = %{"prompt_template" => "Write a short story about: ~s", "context" => %{"topic" => text}}

    result = HypergraphAgent.BasicOrchestrator.orchestrate(graph, agent_map, input)

    require Logger
    Logger.error("story orchestrator result: #{inspect(result)}")

    case result do
      {:ok, %{:story => %{"summary" => story}}} ->
        json(conn, %{"story" => story})
      {:ok, %{"story" => %{"summary" => story}}} ->
        json(conn, %{"story" => story})
      {:ok, %{story: {:ok, story}}} ->
        json(conn, %{"story" => story})
      {:ok, %{"story" => {:ok, story}}} ->
        json(conn, %{"story" => story})
      {:ok, %{"story" => story}} when is_binary(story) ->
        json(conn, %{"story" => story})
      {:ok, other} ->
        Logger.error("Unexpected orchestrator result in story: #{inspect(other)}")
        conn |> put_status(500) |> json(%{"error" => "Unexpected result: #{inspect(other)}", "raw" => inspect(other)})
      {:error, reason} ->
        Logger.error("story error: #{inspect(reason)}")
        conn |> put_status(500) |> json(%{"error" => inspect(reason)})
      other ->
        Logger.error("story received unhandled result: #{inspect(other)}")
        conn |> put_status(500) |> json(%{"error" => "Unhandled result: #{inspect(other)}"})
    end
  end
end
