defmodule ExMCP.ACP.Adapters.Codex.SlashCommands do
  @moduledoc """
  Pure slash-command parsing helpers for the Codex ACP adapter.
  """

  @commands %{
    "compact" => :compact,
    "init" => :init,
    "review" => :review,
    "review-branch" => :"review-branch",
    "review-commit" => :"review-commit",
    "logout" => :logout
  }

  @init_command_prompt """
  Generate a file named AGENTS.md that serves as a contributor guide for this repository.
  Your goal is to produce a clear, concise, and well-structured document with descriptive headings and actionable explanations for each section.
  Follow the outline below, but adapt as needed - add sections if relevant, and omit those that do not apply to this project.

  Document Requirements

  - Title the document "Repository Guidelines".
  - Use Markdown headings (#, ##, etc.) for structure.
  - Keep the document concise. 200-400 words is optimal.
  - Keep explanations short, direct, and specific to this repository.
  - Provide examples where helpful (commands, directory paths, naming patterns).
  - Maintain a professional, instructional tone.

  Recommended Sections

  Project Structure & Module Organization

  - Outline the project structure, including where the source code, tests, and assets are located.

  Build, Test, and Development Commands

  - List key commands for building, testing, and running locally (e.g., npm test, make build).
  - Briefly explain what each command does.

  Coding Style & Naming Conventions

  - Specify indentation rules, language-specific style preferences, and naming patterns.
  - Include any formatting or linting tools used.

  Testing Guidelines

  - Identify testing frameworks and coverage requirements.
  - State test naming conventions and how to run tests.

  Commit & Pull Request Guidelines

  - Summarize commit message conventions found in the project's Git history.
  - Outline pull request requirements (descriptions, linked issues, screenshots, etc.).

  (Optional) Add other sections if relevant, such as Security & Configuration Tips, Architecture Overview, or Agent-Specific Instructions.
  """

  @spec init_input_items() :: [map()]
  def init_input_items, do: [%{"type" => "text", "text" => @init_command_prompt}]

  @spec parse([map()]) :: {:ok, {atom(), String.t()}} | :error
  def parse([%{"type" => "text", "text" => text} | _]) when is_binary(text) do
    case Regex.run(~r/^\/([A-Za-z][A-Za-z0-9_-]*)(?:\s+(.*))?$/s, String.trim_leading(text)) do
      [_, name | rest] -> command_result(name, List.first(rest) || "")
      _ -> :error
    end
  end

  def parse(_items), do: :error

  defp command_result(name, rest) do
    case Map.fetch(@commands, name) do
      {:ok, command} -> {:ok, {command, rest}}
      :error -> :error
    end
  end
end
