// Typed OpenAPI 3.0 model. Open by design: every struct keeps unparsed
// members in `extras` (including `x-` extensions), so nothing in the source
// document is silently dropped.

///|
/// `$ref` or an inlined value. The reference is kept as its raw string until
/// resolved (Resolver, ref.mbt).
#derive(Debug, Eq)
pub(all) enum RefOr[T] {
  Ref(RefTarget)
  Item(T)
}

///|
#derive(Debug, Eq)
pub(all) struct RefTarget {
  /// The raw `$ref` string (e.g. `#/components/schemas/Foo`).
  ref_ : String
  /// Optional OpenAPI 3.1 `$ref` sibling `summary`.
  summary : String?
  /// Optional OpenAPI 3.1 `$ref` sibling `description`.
  description : String?
  /// Preserved OpenAPI 3.1 `$ref` sibling keys (other than `$ref`).
  siblings : Array[(String, Node)]
}

///|
#derive(Debug, Eq)
pub struct OpenApiDoc {
  /// The `openapi` version string (e.g. "3.0.0", "3.1.0").
  openapi : String
  /// Optional OpenAPI 3.1 `jsonSchemaDialect` URI.
  json_schema_dialect : String?
  info : Info
  servers : Array[Server]
  /// Ordered `(path, PathItem)` pairs.
  paths : Array[(String, PathItem)]
  /// Ordered OpenAPI 3.1 `(name, PathItem)` webhooks.
  webhooks : Array[(String, PathItem)]
  components : Components?
  /// Document-level security alternatives (OR of AND-groups).
  security : Array[SecurityAlternative]
  tags : Array[Tag]
  /// Unrecognized top-level members (incl. `x-` extensions and `paths` `x-*`).
  extras : Array[(String, Node)]
}

///|
#derive(Debug, Eq)
pub struct Info {
  title : String
  version : String
  description : String?
  extras : Array[(String, Node)]
}

///|
#derive(Debug, Eq)
pub(all) struct ServerVariable {
  default : String
  enum_ : Array[String]
  description : String?
}

///|
#derive(Debug, Eq)
pub struct Server {
  url : String
  description : String?
  variables : Array[(String, ServerVariable)]
  extras : Array[(String, Node)]
}

///|
#derive(Debug, Eq)
pub struct Tag {
  name : String
  description : String?
  extras : Array[(String, Node)]
}

///|
#derive(Debug, Eq)
pub struct Components {
  /// Ordered component schemas.
  schemas : Array[(String, RefOr[Schema])]
  security_schemes : Array[(String, RefOr[SecurityScheme])]
  parameters : Array[(String, RefOr[Parameter])]
  request_bodies : Array[(String, RefOr[RequestBody])]
  responses : Array[(String, RefOr[Response])]
  headers : Array[(String, RefOr[Header])]
  path_items : Array[(String, RefOr[PathItem])]
  /// Preserved non-modeled sections (examples, links, callbacks, extensions...).
  other_sections : Array[(String, Node)]
}

///|
/// The eight HTTP methods OpenAPI paths may declare.
#derive(Debug, Eq)
pub(all) enum HttpMethod {
  Get
  Put
  Post
  Delete
  Options
  Head
  Patch
  Trace
}

///|
/// Parse a path-item member into a method (`get` -> `Some(Get)`).
pub fn HttpMethod::of_key(key : String) -> HttpMethod? {
  match key {
    "get" => Some(Get)
    "put" => Some(Put)
    "post" => Some(Post)
    "delete" => Some(Delete)
    "options" => Some(Options)
    "head" => Some(Head)
    "patch" => Some(Patch)
    "trace" => Some(Trace)
    _ => None
  }
}

///|
/// Upper-case wire form (`Get` -> "GET").
pub fn HttpMethod::to_wire(self : HttpMethod) -> String {
  match self {
    Get => "GET"
    Put => "PUT"
    Post => "POST"
    Delete => "DELETE"
    Options => "OPTIONS"
    Head => "HEAD"
    Patch => "PATCH"
    Trace => "TRACE"
  }
}

///|
#derive(Debug, Eq)
pub struct PathItem {
  /// Optional `$ref` target for a reusable PathItem.
  ref_ : String?
  summary : String?
  description : String?
  /// Optional path-item level server overrides.
  servers : Array[Server]
  /// Ordered operations in document order.
  operations : Array[(HttpMethod, Operation)]
  /// Path-item level parameters (shared by all operations).
  parameters : Array[RefOr[Parameter]]
  extras : Array[(String, Node)]
}

///|
#derive(Debug, Eq)
pub struct Operation {
  operation_id : String
  summary : String?
  description : String?
  tags : Array[String]
  deprecated : Bool
  /// Optional operation-level server overrides.
  servers : Array[Server]
  parameters : Array[RefOr[Parameter]]
  request_body : RefOr[RequestBody]?
  responses : Responses
  /// `None` = inherit document-level security; `Some([])` = explicitly public;
  /// an entry with empty `schemes` (`{}`) makes auth optional.
  security : Array[SecurityAlternative]?
  extras : Array[(String, Node)]
}

///|
/// A parameter location (`in`).
#derive(Debug, Eq)
pub(all) enum ParameterLocation {
  Path
  Query
  Header
  Cookie
}

///|
pub fn ParameterLocation::of_str(s : String) -> ParameterLocation? {
  match s {
    "path" => Some(Path)
    "query" => Some(Query)
    "header" => Some(Header)
    "cookie" => Some(Cookie)
    _ => None
  }
}

///|
/// Serialization styles (OpenAPI 3.0 full set; the Golem API uses `simple`
/// and `form`).
#derive(Debug, Eq)
pub(all) enum ParameterStyle {
  Matrix
  Label
  Form
  Simple
  SpaceDelimited
  PipeDelimited
  DeepObject
}

///|
pub fn ParameterStyle::of_str(s : String) -> ParameterStyle? {
  match s {
    "matrix" => Some(Matrix)
    "label" => Some(Label)
    "form" => Some(Form)
    "simple" => Some(Simple)
    "spaceDelimited" => Some(SpaceDelimited)
    "pipeDelimited" => Some(PipeDelimited)
    "deepObject" => Some(DeepObject)
    _ => None
  }
}

///|
#derive(Debug, Eq)
pub struct Parameter {
  name : String
  location : ParameterLocation
  required : Bool
  deprecated : Bool
  description : String?
  /// Effective `(style, explode)` pair, always present: absent `style`
  /// defaults per location (path/header -> simple, query/cookie -> form);
  /// absent `explode` defaults per OAS 3.0.3 (form -> true, all others -> false).
  style : (ParameterStyle, Bool)
  /// Decoded parameter schema (`None` when `content` is used instead).
  schema : RefOr[Schema]?
  /// `content` alternative (media type -> media type object).
  content : Array[(String, MediaType)]
  extras : Array[(String, Node)]
}

///|
#derive(Debug, Eq)
pub struct RequestBody {
  description : String?
  required : Bool
  content : Array[(String, MediaType)]
  extras : Array[(String, Node)]
}

///|
/// A media type object under a content-type key.
#derive(Debug, Eq)
pub struct MediaType {
  schema : RefOr[Schema]?
  example : Node?
  /// Optional per-part `encoding..contentType` map (multipart / form).
  encoding : Array[(String, String)]
  extras : Array[(String, Node)]
}

///|
/// Status codes: exact three-digit HTTP status (`100..=599`), canonical
/// uppercase wildcard (`"1XX"`..`"5XX"`), or `"default"`.
#derive(Debug, Eq)
pub(all) enum StatusCode {
  Code(Int32)
  Wildcard(String)
  Default
}

///|
/// Parse a responses key: `default`, an exact three-digit HTTP status code
/// (`"100"`..`"599"`), or a wildcard (`"1XX"`..`"5XX"`, normalized to upper).
pub fn StatusCode::of_key(key : String) -> StatusCode? {
  if key == "default" {
    return Some(Default)
  }
  if key.length() != 3 {
    return None
  }
  let c0 = key[0]
  let c1 = key[1]
  let c2 = key[2]
  if c0 is ('1'..<='5') && c1 is ('0'..<='9') && c2 is ('0'..<='9') {
    match parse_int64_text(key) {
      Some(v) => return Some(Code(v.to_int()))
      None => ()
    }
  }
  if c0 is ('1'..<='5') && c1 is ('X' | 'x') && c2 is ('X' | 'x') {
    return Some(Wildcard(key.to_upper()))
  }
  None
}

///|
#derive(Debug, Eq)
pub struct Responses {
  /// Ordered status-code entries.
  entries : Array[(StatusCode, RefOr[Response])]
  /// Extension members (`x-*`) on the responses object.
  extras : Array[(String, Node)]
}

///|
#derive(Debug, Eq)
pub struct Response {
  description : String
  headers : Array[(String, RefOr[Header])]
  content : Array[(String, MediaType)]
  extras : Array[(String, Node)]
}

///|
#derive(Debug, Eq)
pub struct Header {
  required : Bool
  deprecated : Bool
  description : String?
  /// Effective `(style, explode)` pair (OAS default: `(Simple, false)`).
  style : (ParameterStyle, Bool)
  schema : RefOr[Schema]?
  extras : Array[(String, Node)]
}

///|
/// One scheme requirement inside a security alternative object (`"Token": []`).
#derive(Debug, Eq)
pub(all) struct SecurityRequirement {
  scheme : String
  scopes : Array[String]
}

///|
/// One entry of an OpenAPI `security` array. Entries in the array are OR'd;
/// all `schemes` inside one `SecurityAlternative` are AND'd. An empty
/// `schemes` array corresponds to `{}` (optional / anonymous access allowed).
#derive(Debug, Eq)
pub(all) struct SecurityAlternative {
  schemes : Array[SecurityRequirement]
}

///|
/// One OAuth 2.0 flow configuration (`implicit`, `password`,
/// `clientCredentials`, or `authorizationCode`).
#derive(Debug, Eq)
pub(all) struct OAuthFlow {
  authorization_url : String?
  token_url : String?
  refresh_url : String?
  scopes : Array[(String, String)]
}

///|
/// OAuth 2.0 flows container (`components.securitySchemes..flows`).
#derive(Debug, Eq)
pub(all) struct OAuthFlows {
  implicit : OAuthFlow?
  password : OAuthFlow?
  client_credentials : OAuthFlow?
  authorization_code : OAuthFlow?
}

///|
/// Security scheme type.
#derive(Debug, Eq)
pub(all) enum SecuritySchemeType {
  /// `type: http` with `scheme: bearer|basic|...` (+ `bearerFormat`).
  Http(scheme~ : String, bearer_format~ : String?)
  /// `type: apiKey` located in header/query/cookie with its wire name.
  ApiKey(location~ : ParameterLocation, name~ : String)
  /// `type: oauth2` with decoded OAuth 2.0 `flows`.
  Oauth2(flows~ : OAuthFlows)
  /// `type: openIdConnect` with its discovery document URL.
  OpenIdConnect(url~ : String)
  /// Unrecognized / newer scheme type (e.g. `mutualTLS`), preserved with its
  /// unmodeled properties in `SecurityScheme.extras`.
  Other(String)
}

///|
/// Decoded OpenAPI `components.securitySchemes` entry.
#derive(Debug, Eq)
pub struct SecurityScheme {
  type_ : SecuritySchemeType
  description : String?
  extras : Array[(String, Node)]
}

///|
/// Discriminator object on tagged unions.
#derive(Debug, Eq)
pub struct Discriminator {
  property_name : String
  /// Ordered mapping entries (tag value -> $ref).
  mapping : Array[(String, String)]
  extras : Array[(String, Node)]
}

///|
/// JSON Schema / OpenAPI validation keywords.
#derive(Debug, Eq)
pub(all) struct SchemaConstraints {
  minimum : String?
  maximum : String?
  exclusive_minimum : String?
  exclusive_maximum : String?
  multiple_of : String?
  min_length : Int32?
  max_length : Int32?
  pattern : String?
  min_items : Int32?
  max_items : Int32?
  unique_items : Bool
  min_properties : Int32?
  max_properties : Int32?
}

///|
pub fn SchemaConstraints::empty() -> SchemaConstraints {
  {
    minimum: None,
    maximum: None,
    exclusive_minimum: None,
    exclusive_maximum: None,
    multiple_of: None,
    min_length: None,
    max_length: None,
    pattern: None,
    min_items: None,
    max_items: None,
    unique_items: false,
    min_properties: None,
    max_properties: None,
  }
}

///|
pub fn SchemaConstraints::is_empty(self : SchemaConstraints) -> Bool {
  self.minimum is None &&
  self.maximum is None &&
  self.exclusive_minimum is None &&
  self.exclusive_maximum is None &&
  self.multiple_of is None &&
  self.min_length is None &&
  self.max_length is None &&
  self.pattern is None &&
  self.min_items is None &&
  self.max_items is None &&
  !self.unique_items &&
  self.min_properties is None &&
  self.max_properties is None
}

///|
/// OpenAPI 3.0 / 3.1 Schema, kept open: recognized keywords are typed,
/// everything else (incl. `x-` extensions) lands in `extras`.
#derive(Debug, Eq)
pub struct Schema {
  /// Primary non-null type (e.g. `"string"` for `"string"` or `["string", "null"]`),
  /// `"null"` when only null is allowed, or `None` when absent or multi-type.
  type_ : String?
  /// Full OpenAPI 3.1 `type` list (`["string"]`, `["string", "null"]`,
  /// `["string", "integer"]`, or `[]` when omitted).
  types : Array[String]
  format : String?
  title : String?
  description : String?
  enum_ : Array[Node]?
  /// OpenAPI 3.1 / JSON Schema `const` single-value constraint.
  const_ : Node?
  items : RefOr[Schema]?
  properties : Array[(String, RefOr[Schema])]
  required : Array[String]
  additional_properties : AdditionalProperties?
  all_of : Array[RefOr[Schema]]?
  one_of : Array[RefOr[Schema]]?
  any_of : Array[RefOr[Schema]]?
  not : RefOr[Schema]?
  nullable : Bool
  read_only : Bool
  write_only : Bool
  constraints : SchemaConstraints
  discriminator : Discriminator?
  default : Node?
  example : Node?
  /// OpenAPI 3.1 / JSON Schema `examples` array.
  examples : Array[Node]
  deprecated : Bool
  extras : Array[(String, Node)]
}

///|
#derive(Debug, Eq)
pub(all) enum AdditionalProperties {
  Allowed(Bool)
  Schema(RefOr[Schema])
}

///|
/// The `$ref` string of a Ref, if it is one.
pub fn[T] ref_or_ref_value(value : RefOr[T]) -> String? {
  match value {
    Ref(target) => Some(target.ref_)
    Item(_) => None
  }
}