// Questions are requests for information, independent of permission approvals.

///|
#derive(Debug, Eq)
pub(all) struct UserQuestion {
  id : String
  title : String
  options : Array[String]?
}

///|
#derive(Debug, Eq)
pub(all) struct AskUserPayload {
  questions : Array[UserQuestion]
}

///|
#derive(Debug, Eq)
pub(all) struct PendingUserQuestion {
  id : String
  session : String
  questions : Array[UserQuestion]
}

///|
#derive(Debug, Eq)
pub(all) struct UserQuestionSnapshot {
  generation : Int32
  requests : Array[PendingUserQuestion]
}

///|
/// Null answers explicitly skip the whole request. Otherwise each question
/// has one nonblank answer: either an option's text or the user's own text.
#derive(Debug, Eq)
pub(all) struct UserQuestionAnswer {
  id : String
  session : String
  answers : Map[String, String]?
}

///|
pub impl ToJson for UserQuestion with fn to_json(self) {
  let fields : Map[String, Json] = {
    "id": Json(self.id),
    "title": Json(self.title),
  }
  if self.options is Some(options) {
    fields["options"] = Json(options)
  }
  Json(fields)
}

///|
pub impl FromJson for UserQuestion with fn from_json(json, path) {
  guard json is Object(fields) else {
    raise JsonDecodeError((path, "expected user question object"))
  }
  let id : String = question_field(fields, "id", path)
  let title : String = question_field(fields, "title", path)
  guard !id.is_blank() && !title.is_blank() else {
    raise JsonDecodeError((path, "question id and title must not be blank"))
  }
  let options : Array[String]? = if fields.get("options") is Some(value) &&
    !(value is Null) {
    let options : Array[String] = @json.from_json(
      value,
      path=path.add_key("options"),
    )
    guard !options.any(option => option.is_blank()) else {
      raise JsonDecodeError(
        (path.add_key("options"), "options must not be blank"),
      )
    }
    Some(options)
  } else {
    None
  }
  { id, title, options, }
}

///|
pub impl ToJson for AskUserPayload with fn to_json(self) {
  { "questions": Json(self.questions) }
}

///|
pub impl FromJson for AskUserPayload with fn from_json(json, path) {
  guard json is Object(fields) else {
    raise JsonDecodeError((path, "expected ask_user request object"))
  }
  let questions : Array[UserQuestion] = question_field(
    fields, "questions", path,
  )
  guard !questions.is_empty() else {
    raise JsonDecodeError((path, "at least one question is required"))
  }
  let ids : Map[String, Unit] = Map([])
  for question in questions {
    guard !ids.contains(question.id) else {
      raise JsonDecodeError((path, "question ids must be unique"))
    }
    ids[question.id] = ()
  }
  { questions, }
}

///|
pub impl ToJson for PendingUserQuestion with fn to_json(self) {
  { "id": self.id, "session": self.session, "questions": Json(self.questions) }
}

///|
pub impl FromJson for PendingUserQuestion with fn from_json(json, path) {
  guard json is Object(fields) else {
    raise JsonDecodeError((path, "expected pending user question object"))
  }
  let payload : AskUserPayload = @json.from_json(json, path~)
  {
    id: question_field(fields, "id", path),
    session: question_field(fields, "session", path),
    questions: payload.questions,
  }
}

///|
pub impl ToJson for UserQuestionSnapshot with fn to_json(self) {
  { "generation": self.generation, "requests": Json(self.requests) }
}

///|
pub impl FromJson for UserQuestionSnapshot with fn from_json(json, path) {
  guard json is Object(fields) else {
    raise JsonDecodeError((path, "expected user question snapshot object"))
  }
  let generation : Int32 = question_field(fields, "generation", path)
  guard generation >= 0 else {
    raise JsonDecodeError((path, "negative question generation"))
  }
  { generation, requests: question_field(fields, "requests", path), }
}

///|
pub impl ToJson for UserQuestionAnswer with fn to_json(self) {
  {
    "id": self.id,
    "session": self.session,
    "answers": self.answers.map_or(null, answers => Json(answers)),
  }
}

///|
pub impl FromJson for UserQuestionAnswer with fn from_json(json, path) {
  guard json is Object(fields) else {
    raise JsonDecodeError((path, "expected user question answer object"))
  }
  {
    id: question_field(fields, "id", path),
    session: question_field(fields, "session", path),
    answers: match fields.get("answers") {
      None =>
        raise JsonDecodeError(
          (path.add_key("answers"), "missing required field"),
        )
      Some(Null) => None
      Some(value) => Some(@json.from_json(value, path=path.add_key("answers")))
    },
  }
}

///|
pub extend UserQuestion with Debug::{to_repr}

///|
pub extend UserQuestion with Eq::{equal, not_equal}

///|
pub extend UserQuestion with ToJson::{to_json}

///|
pub extend UserQuestion with FromJson::{from_json}

///|
pub extend AskUserPayload with Debug::{to_repr}

///|
pub extend AskUserPayload with Eq::{equal, not_equal}

///|
pub extend AskUserPayload with ToJson::{to_json}

///|
pub extend AskUserPayload with FromJson::{from_json}

///|
pub extend PendingUserQuestion with Debug::{to_repr}

///|
pub extend PendingUserQuestion with Eq::{equal, not_equal}

///|
pub extend PendingUserQuestion with ToJson::{to_json}

///|
pub extend PendingUserQuestion with FromJson::{from_json}

///|
pub extend UserQuestionSnapshot with Debug::{to_repr}

///|
pub extend UserQuestionSnapshot with Eq::{equal, not_equal}

///|
pub extend UserQuestionSnapshot with ToJson::{to_json}

///|
pub extend UserQuestionSnapshot with FromJson::{from_json}

///|
pub extend UserQuestionAnswer with Debug::{to_repr}

///|
pub extend UserQuestionAnswer with Eq::{equal, not_equal}

///|
pub extend UserQuestionAnswer with ToJson::{to_json}

///|
pub extend UserQuestionAnswer with FromJson::{from_json}

///|
fn[T : FromJson] question_field(
  fields : Map[String, Json],
  name : String,
  path : @json.JsonPath,
) -> T raise @json.JsonDecodeError {
  guard fields.get(name) is Some(value) else {
    raise JsonDecodeError((path.add_key(name), "missing required field"))
  }
  @json.from_json(value, path=path.add_key(name))
}

///|
/// Encode the answer for the model and transcript.
pub fn encode_question_response(
  request_id : String,
  questions : Array[UserQuestion],
  answers : Map[String, String]?,
) -> String {
  let status = if answers is Some(_) { "answered" } else { "skipped" }
  let output = StringBuilder()
  output.write_string(
    "\n",
  )
  for question in questions {
    output.write_string(
      "\n",
    )
    output.write_string(
      "\{question_attribute(question.title)}\n",
    )
    if question.options is Some(options) {
      output.write_string("\n")
      for option in options {
        output.write_string("\n")
      }
      output.write_string("\n")
    }
    if answers is Some(answers) && answers.get(question.id) is Some(answer) {
      output.write_string("\{question_attribute(answer)}\n")
    }
    output.write_string("\n")
  }
  output.write_string("")
  output.to_string()
}

///|
fn question_attribute(text : String) -> String {
  let output = StringBuilder()
  for char in text {
    match char {
      '&' => output.write_string("&")
      '"' => output.write_string(""")
      '<' => output.write_string("<")
      '>' => output.write_string(">")
      '\r' => output.write_string("
")
      '\n' => output.write_string("
")
      _ => output.write_char(char)
    }
  }
  output.to_string()
}

///|
pub const AskUserDescription : String = "Ask the user questions in this conversation. Supply unique question ids, clear titles, and optional suggested choices; the user can always type their own answer. This is for information and preferences, not permission approval. Returns immediately with the request id and pending status. The answer or skip arrives as a new message in this conversation. Continue independent work. When progress needs the answer, tell the user what is waiting and end your message. Use finish when your work is complete. Finishing or stopping the turn closes its unanswered questions."

///|
pub fn ask_user_schema() -> Json {
  {
    "type": "object",
    "additionalProperties": false,
    "required": ["questions"],
    "properties": {
      "questions": {
        "type": "array",
        "minItems": 1,
        "items": {
          "type": "object",
          "additionalProperties": false,
          "required": ["id", "title"],
          "properties": {
            "id": { "type": "string", "minLength": 1 },
            "title": { "type": "string", "minLength": 1 },
            "options": {
              "type": "array",
              "items": { "type": "string", "minLength": 1 },
            },
          },
        },
      },
    },
  }
}

///|
pub fn question_receipt(id : String) -> Json {
  { "id": Json(id), "status": "pending", "answers": null }
}

///|
/// The host submits this text through ordinary prompt/steer admission.
#derive(Debug, Eq, ToJson, FromJson)
pub(all) struct QuestionInput {
  submission_id : String
  text : String
}

///|
pub fn UserQuestionAnswer::submission_id(self : UserQuestionAnswer) -> String {
  self.id + "-result"
}

///|
pub fn PendingUserQuestion::accepts(
  self : PendingUserQuestion,
  answer : UserQuestionAnswer,
) -> Bool {
  match answer.answers {
    None => true
    Some(values) =>
      values.length() == self.questions.length() &&
      self.questions.all(q => {
        values.get(q.id).map_or(false, value => !value.is_blank())
      })
  }
}